5

I trie to get an json in my jquery ajax successe: to worke but i dose not.......

Thats what i tried to do:

$("#addcatform").submit(function() {
  var str = $(this).serialize();
  $.ajax({
    type: "POST",
    url: "ajax.php",
    data: str,
    success: function(data){
      var json_x = data;
      alert(json_x.firstName2);
      $('#result').html(json_x.firstName2); 
      $('#result2').html(json_x.b); 
    }
  }); 

  return false;
  event.preventDefault();
}); // submit end

the php echos this:

$arr = array ('firstName2'=>'hallo','b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);

Whats wrong with this? Thanks for helping!!!!

Sumurai8
  • 20,333
  • 11
  • 66
  • 100
user1606423
  • 75
  • 1
  • 1
  • 7
  • Please note that `event` is undefined in your example. You should change the first line to `$("#addcatform").submit( function( event ) {` – Sumurai8 Jul 05 '13 at 20:35

3 Answers3

8

You need to parse your json before using it,

You can add a dataType in your request - jQuery will parse your response json

$.ajax({
    type: "POST",
    url: "ajax.php",
    dataType: 'json',

Or, you can parse it yourself -

success: function(data){
    var json_x = $.parseJSON(data);
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
  • Thanks Mohammad. If you are gonna parse it by yourself, remember to manage the error thrown if the parse action fails. – sataniccrow Nov 29 '13 at 11:16
2

You could try this:

var data=$.ajax({
        type: "POST",
        url: 'ajax.php',
        data: {
            data:str
        }, 
        async: false,
        dataType: 'json'
    });
    var msg= data.responseText;
    msg=jQuery.parseJSON(msg);

I usually send either an array or the message 'error' from my php page

if(msg=='error')
{
/* do something */
}
else
// use the data

This works with jquery 1.6->1.8

EDIT: Since jquery 1.8 async is deprecated. i would recommend this format :

$.ajax({
        type: "POST",
        url: 'ajax.php',
        data: {
            data:str
        }, 
        dataType: 'json',
     ).done(function(data) {
      // do something with the data
     })
   .fail(function() {
    // give appropriate message
    })

http://api.jquery.com/jquery.ajax/

Indra
  • 692
  • 6
  • 18
0

data is a string in your example. Use jQuery.getJSON(). Edit: As you cannot do a POST-request with getJSON (dûh) use .ajax with the appropiate dataType instead. This will retrieve the data via ajax, and parses the resulting string as if it is JSON. Even with getJSON, the result will be an array (or an array like object, not sure). This has no methods or variables you can access with the dot-notation. You'll need to access it via data['a'].

$.ajax({
  dataType: "json",
  type: "POST",
  url: "ajax.php",
  data: str,
  success: function(data){
    var json_x = data;
    alert(json_x['firstName2']);
    $('#result').html(json_x['firstName2']);
    $('#result2').html(json_x['b']); 
  } 
}); 
Sumurai8
  • 20,333
  • 11
  • 66
  • 100
  • Correct explanation, but `getJSON` doesn't accept an object as first argument. Have a look at the documentation again. – Felix Kling Jul 05 '13 at 20:32
  • You are right; and as he needs a post request... well... he'll need to use .ajax with the appropiate dataType. I believe this will still parse the returned data as if it is JSON. – Sumurai8 Jul 05 '13 at 20:40
  • At the moment is use dataType: "json", i get no result without dataType: "json", i get an alert with undefined...????????? – user1606423 Jul 05 '13 at 21:20
  • Try `console.log( data );` and open your console (F12) to see what data the server sends. – Sumurai8 Jul 05 '13 at 21:42
  • {"firstName2":"hallo","b":2,"c":3,"d":4,"e":5} thats what i get from the server, but i dont get an output in my site... – user1606423 Jul 05 '13 at 21:47
  • with console.log you can check it's type. The server should send a 'Content-Type: text/json' with the response. – Sumurai8 Jul 05 '13 at 22:07
  • Accept application/json, text/javascript, */*; q=0.01 Accept-Encoding gzip, deflate Accept-Language de-de,de;q=0.8,en-us;q=0.5,en;q=0.3 Content-Length 11 Content-Type application/x-www-form-urlencoded; charset=UTF-8 Cookie ... Host localhost Referer http://localhost/eventdatenbank3/index.php User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0 X-Requested-With XMLHttpRequest – user1606423 Jul 05 '13 at 22:14
  • jQuery will not recognize that content type. You'll need to manually parse it then. See pXL's answer. – Sumurai8 Jul 05 '13 at 22:27
  • when I use this it dosnt worke;( dataType: "json", ...... var json_x = $.parseJSON(data); I have always tried to set the Content type.. contentType: "application/json", but nothing workes – user1606423 Jul 06 '13 at 14:09