6

I've read dozens of related posts, but I still can't get this to work.

I want to alert the response in jquery I get from PHP.

PHP:

$msg=array();

    if(empty($whatever)){
        $msg['cenas']="Não há contas";
    }else{
        $msg['cenas']="Há contas";
    };

    echo json_encode($msg);

JS:

$.ajax({
    url: 'myscript.php',
    dataType: 'json',
    success: function(response){
       alert(response.cenas);
    }
});

PHP is echoing

{cenas: "Há contas}" But I can't get it to alert in JS.

  • 3
    using firebug or chrome developer tools log the alert instead as `console.log(response)`. That will reveal your entire object response and should let you see what's wrong. – Harvey A. Ramer Feb 07 '14 at 22:25
  • @HarveyA.Ramer console.log(response) returns "success" –  Feb 07 '14 at 22:44
  • 1
    That means, I believe, that you are just returning a string from your myscript.php file on success. In that case, you'll need to modify it to return an object to do what you're trying to do. This might be instructive: http://stackoverflow.com/questions/8649621/returning-a-json-object-from-php-in-ajax-call – Harvey A. Ramer Feb 08 '14 at 03:08

3 Answers3

4

The php should echo back {"cenas": "Há contas"}, but what did you get in the alert? Did you get an undefined? If so, try to use jQuery.parseJSON before alert. e.g:

$.ajax({
    url:"myscript.php",
    dataType: "json",
    success:function(data){
       var obj = jQuery.parseJSON(data);
       alert(obj.cenas);
    }
});
VVLeon
  • 399
  • 3
  • 8
  • That's right, I get undefined. With your recommendation, the success function, is never executed, therefore, no alert. –  Feb 07 '14 at 23:55
0

Try

$.ajax({
    url:"myscript.php",
    dataType: "json",
    success:function(data){
       alert(data.cenas);
    }
});

You have a syntax error.

Check out the Docs for $.ajax

Christopher Marshall
  • 10,678
  • 10
  • 55
  • 94
0

You should tell jQuery to expect (and parse) JSON in the response (although jQuery could guess this correctly...) and you should write your javascript correctly:

$.ajax({
    url: 'myscript.php',
    dataType: 'json',
    success: function(response){
       alert(response.cenas);
    }
});
jeroen
  • 91,079
  • 21
  • 114
  • 132
  • Thanks, I've just edited my question. I do include dataType: 'json' in the ajax call –  Feb 07 '14 at 22:35
  • @NunoNogueira Check the differences between your and my ajax call (parenthesis for the function, quoting strings, etc.). – jeroen Feb 07 '14 at 22:36
  • I dit that, I get undefined –  Feb 08 '14 at 00:19