E. Andrade
E. Andrade

Reputation: 3

retrieve data sent through ajax

I'm sending data from a textarea with ajax:

$('a#btn-send').click(function()
{
    var user = $("input#user").val();
    var conv = $("input#conv").val();
    var msj = $("textarea#msj").val();  
    if(msj!=''){
        var data = '{user:' + user + ',msj:'+msj+',conv:'+conv+'}' ;
        $("textarea#msj").val('');

        $.ajax(
        {
           type: "POST",
           url: "messajes.php",
           data: data,
           cache: false,
           success: function()
           {
                parent.fadeOut('slow', function() {$(this).add();});
                toastr.options = {
                    "closeButton": true,
                    "debug": false,
                    "newestOnTop": false,
                    "progressBar": true
                }
                toastr.success("Message semt","Success");
           }
        });
    }
});

For starters I don't know if that is the correct way to send data, however I've done this before, only with one data element (?) I mean, only with an "id". Now that I'm trying to send multiple data, I'm not able to catch it with the php controller:

if ($_SERVER['REQUEST_METHOD'] == 'POST'){
    include_once('conection.php');
    $connection = connect();
    if(isset($_POST['msj'])){
        $msj = $_POST['mjs'];
        $conv = $_POST['conv'];
        $user = $_POST['user'];
        $sql = "INSERT INTO messages (msj, conversation, user) VALUES('$msj',$conv,'$user')";
        $statement = $connection->prepare($sql);
        $statement->execute();
    }
}

Is there anything that I'm missing?

I'm guessing I have to encode/decode data with JSON but I'm not a pro with that and I haven't found any examples addressing this exact scenario.

Edit

Now I have this in the Jquery code:

$('a#btn-enviar').click(function()
{
    var user = $("input#user").val();
    var conv = $("input#conv").val();
    var msj = $("textarea#msj").val();  

    if(msj!=''){
       var data = {user: user, msj: msj, conv: conv};
       $("textarea#msj").val('');

        $.ajax(
        {
           type: "POST",
           url: "mensajes.php",
           data: data,
           dataType: 'json',
           cache: false,
           success: function()
           {
                //code
           }
        });
    }
});

and the php as follows:

if ($_SERVER['REQUEST_METHOD'] == 'POST'){
    include_once('conectar.php');
    $conexion = conectar();

    if(isset($_POST['data'])){
        $data = json_decode($_POST['data']);
        $msj = $data->msj;
        $conv = $data->conv;
        $user = $data->user;

        $sql = "INSERT INTO messages(conversation, msj, user) VALUES ($conv, '$msj', '$user')";
        $statement = $conexion->prepare($sql);
        $statement->execute();
    }

}

Upvotes: 0

Views: 79

Answers (1)

Saral
Saral

Reputation: 1160

Do not quote data. You are making data string. It should be

 var data = {user: user, msj: msj, conv: conv};

If you are working with JSON, send dataType: 'json' in $.ajax():

$.ajax(
    {
       type: "POST",
       url: "messajes.php",
       data: data,
       dataType: 'json',
       cache: false,
       success: function()
       {
            //code
       }
    });

Your PHP code is supposed to be

if(isset($_POST['user'], $_POST['msj'], $_POST['conv'])){

    include_once('conectar.php');
    $conexion = conectar();


    $msj = $_POST['msj'];
    $conv = $_POST['conv'];
    $user = $_POST['user'];


    $sql = "INSERT INTO messages(conversation, msj, user) VALUES (?, ?, ?)";
    $statement = $conexion->prepare($sql);
    $statement->execute(array($conv, $msj, $user));
}

You are directly using variables in your query so the statement can not be prepared statement even if it looks like. I've changed the code according to the PDO prepared statements, if you are using mysqli change your code accordingly.

mysqli: http://php.net/manual/es/mysqli.prepare.php

pdo: http://php.net/manual/en/pdo.prepare.php

If this code is for inserting into the database and notifying the user of successful insert, you clearly do not need the dataType:'json', dataType:'text' does the job. Then you can echo some identifier such as echo 'TRUE'; on successful insert in your PHP and in your JavaScript you can check for that text TRUE and notify the user.

Upvotes: 1

Related Questions