2

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

3
  • please console.log(datos) Commented Dec 29, 2015 at 23:15
  • 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); Commented Dec 29, 2015 at 23:16
  • so go for Clayton solution datos = JSON.parse( datos ); Commented Dec 29, 2015 at 23:18

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Small note - Content-Type: application/json does not work for IE8 if you plan to support that browser.
That is why i mentioned I would suggest you to use a combination of first one and third one..
That won't work for IE8 since it will still prompt to download (horrible browser bug), you still need to set the content type to Content-Type: text/html. Most people don't support IE8 so it's probably not an issue for most folks.
@Clayton ohh i didn't know about this.
1

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);
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.