2
votes

Because I get undefined. Where I am failing?

Code:


    function add(id,cost){
            var info = {
                    "id" : id,
                    "cost": cost,
            };
            $.ajax({
                    data:  info,
                    url:   'a.php',
                    type:  'post',
                    success:  function (datos) {
                             alert(datos+"\n r1: "+datos.r1+"\n r2:"+datos.r2);
                    }
            });
    }

archive a.php PHP:


    $cost=$_POST['id']*$_POST['cost'] + 137;
    echo json_encode(array("r1" =>$_POST['id'], "r2" => $cost));

image

2
please console.log(datos) - Abdelrahman M. Allam
make a console.log(datos) and you will see, that this is still a string, not yet a json! so transfor it first via jsdatos = JSON.parse(datos); - Jeff
so go for Clayton solution datos = JSON.parse( datos ); - Abdelrahman M. Allam

2 Answers

4
votes

Why do you think $.ajax will understand datos as a JSON? You need to specify it, you can do it using several ways.

Parsing it

    success:  function (datos) {
      datos = JSON.parse(datos);
      alert(datos+"\n r1: "+datos.r1+"\n r2:"+datos.r2);
    }

Specifying in $.ajax itself

$.ajax({
                    data:  info,
                    url:   'a.php',
                    type:  'post',
                    dataType:"json",
      ....

Setting header in PHP (doesn't work for < IE8)

header('Content-Type: application/json');

I would suggest you to use a combination of first one and third one. Lets not leave any stone unturned.

1
votes

Datos is probably a string

You can do:

datos = JSON.parse( datos );

Or, you can set the return type to JSON:

$.ajax({
    data:  info,
    dataType: 'json',
    url:   'a.php',
    type:  'post',
    success:  function (datos) {
    alert(datos+"\n r1: "+datos.r1+"\n r2:"+datos.r2);
    }
});