Does not recognize when changing javascript variable to php using ajax

1

I am here in this opportunity to pose a small problem that I have been turning a long time ago.

It turns out that I'm developing a small, private chat, 1 to 1. The interface is simple and has a select and option to change user.

Use websocket, but to save and insert the corresponding data I use ajax.

The problem is that when changing channels (when changing a different option), it does not recognize the option change.

I leave you an image: Design image to better understand

Then when sending any message a request is made to "pagina.php" in which they are saved, but the problem is that they do not recognize the chat_room id, which is important to differentiate existing channels.

I leave the code here:

index.php (when selecting the option "1", page.php correctly receives the value, but when selecting "2" it continues recognizing "1"). Please see the ajax request made in

var cod = $('#cod').val();

$.post('pagina.php',{name:mensaje,cr:cod},function(){
})

now yes, the index.php:

<?php
session_start();
if(!isset($_SESSION["user"])){
  header("location:../login.php");
}
<html lang="en">
<head>
    <?php
        header("Access-Control-Allow-Origin: *");
    ?>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
    <title>Chat con nodejs + socket.io</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
</head>
<body>

    <div class="container">
        <div class="row">
            <div class="col-md-12 text-center">
            <h2>Websocket & Socket.io Chat</h2>
</div>

    <script type="text/javascript">
     var socket = io.connect( 'http://localhost:1334' );
        //var socket = io();
        $(function(){
            $("form").submit(function(){
                var mensaje = $("#msg").val();

                if(mensaje=='') return false;
                if(mensaje==' ') return false;

                //evento message en el server nodejs
                console.log(mensaje)
var cod = $('#cod').val();

$.post('pagina.php',{name:mensaje,cr:cod},function(){
})


                socket.emit('message',mensaje);
                $("#msg").val('').focus();
                return false;
            });
            $("#channel").change(function(){
                socket.emit('change channel',$("#channel").val());
            });
        });

        socket.on('message',function(msg){
            $('#message').append($('<p><strong>' + '<?echo $_SESSION["user"]?>' + ': </strong>' + msg + '</p>'));
        $('.chat-window').scrollTop($('#message').height());
        });
        socket.on('change channel',function(channel){
            $("#message").html('').append($('<li>').text('system : Bienvenido al Canal '+channel+' !'));
        });

    </script>

    <div class="col-md-12">
        <div class="chat-window">
              <div id="message">
        </div>
    </div>
    <div id="controls">

    <form action="" id="form" method="POST">
            <select name="channel" id="channel">
            <div class="col-md-12">

          <option id="cod" name="cr" value="1">1</option>
          <option id="cod" name="cr" value="2">2</option>

        </select>

            <div class="col-md-12">
                <div class="input-group enter-chat-message">
                    <input type="text" id="msg" name="name" class="form-control" placeholder="Chat Message...">
                    <input class="input-group-addon submit-chat-message" type="submit" id="btn" name="submit" value="Enviar">
                </div>
            </div>
</div>
        </form>
</div>

    </div></div></div></div>
    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
            <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
            <script src="js/bootstrap.js"></script>

</body>
</html>

pagina.php (when I do an echo to $_POST['cr']; regardless if in the index I select the 1 or the 2, always recognizes the "1")

<?
session_start();
if(!isset($_SESSION["user"])){
  header("location:../login.php");
}

require "../config.php";

$conn = mysqli_connect($hostname,$username,$passw,$database);

$q1 = mysqli_query($conn,"SELECT * FROM usuario2 WHERE Usuario = '".$user."'");
while($row = mysqli_fetch_assoc($q1)){
$id = mysqli_real_escape_string($conn, $row['ID']);
}

$user=$_SESSION["user"];
$cod = $_POST['cr'];
$mensaje = $_POST['name'];
echo $cod;


$sql4 = "INSERT INTO chat2 (cr_id, username, mensaje) VALUES('$cod', '$user', '$mensaje')";
$resultado = mysqli_query($conn, $sql4);

?>

chat.js (this is the essence for the websocket to work).

var express = require( 'express' );
var http = require('http');
var socket = require('socket.io');
var bodyParser = require('body-parser')
var PORT = process.env.PORT || 8080;
var fs= require('fs');
var app = express();
var server = http.createServer( app );

var io = socket.listen( server );


app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

io.on('connection',function(socket){
        console.log("usuario id : %s",socket.id);

    var channel = 'channel-a';

    //socket.broadcast.emit('message','El usuario '+socket.id+' se ha conectado!','System');

    socket.join(channel);

    socket.on('message',function(msj){
        //io.emit('message',msj,socket.id); //envia a todos los usuarios,canales...
        io.sockets.in(channel).emit('message',msj,socket.id); //enviar a todos del canal
        //socket.broadcast.to(channel).emit('message',msj,socket.id); //enviar a todos del canal menos a mi
    });

    socket.on('disconnect',function(){
        console.log("Desconectado : %s",socket.id);
    });

    socket.on('change channel',function(newChannel){
        socket.leave(channel);
        socket.join(newChannel);
        channel = newChannel;
        socket.emit('change channel',newChannel);
    });

});

server.listen( 1334, function() {
    console.log('lisning to port 1334');
});

All help is received, thank you very much! Probably the error is something basic but I admit that it has surpassed me.

    
asked by Sebastian Hanania 21.06.2018 в 03:33
source

1 answer

1

The problem

When you do this:

var cod = $('#cod').val();

You tell him to find you the value of the element whose id is cod .

The problem is that having the select like this:

    <select name="channel" id="channel">
      <option id="cod" name="cr" value="1">1</option>
      <option id="cod" name="cr" value="2">2</option>
    </select>

The value that will take you will always be the first element with id="cod" that you find , that is, the first option , which is 1 .

The solution

  • It is not advisable to have elements with repeated id in the DOM, to avoid confusions like these and more. Therefore, the option can not have the same id.

  • When you work with select , you get the value of the selected option using id or name of select , not% option .

  • Consequently you can:

    • Remove id to option
    • Give select the id="cod" or leave it as is, but knowing that you have to change the jQuery code for this:

      var cod = $('#channel').val();
      

      or you can capture it in on.change ...

    Then it would simply be like this:

        <select name="channel" id="channel">
          <option name="cr" value="1">1</option>
          <option name="cr" value="2">2</option>
        </select>
    

    Let's try:

    $("#channel").on('change', function() {
      var cod = $(this).val();
      console.log("Seleccionaste el canal: " + cod);
      /*En caso de querer obtenerlo por el id (fuera del onchange por supuesto*/
      var codById=$("#channel").val();
      console.log("Y obtenido por el id: " + codById);
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    Selecciona un canal:
    <hr />
    <select name="channel" id="channel">
      <div class="col-md-12">
        <option name="cr" value="1">1</option>
        <option name="cr" value="2">2</option>
      </div>
    </select>
      

    NOTES:

         

    There are more things to correct / optimize / ensure in the code:

         
  • You add the jQuery library several times, at the beginning and at the end ...?

  •   
  • You use queries to the database that are vulnerable to SQL injection attacks. It is convenient that you use prepared queries.

  •   
        
    answered by 21.06.2018 / 04:13
    source