I need to contact via ajax on the server and get the answer as an array. Here is the php code:

$result = json_encode($xmlChange); echo $result; 

Type of answer:

 {"transaction":[{"id":"0","btc":"0.2","dtime":"25"},{"id":"1","btc":"0.2","dtime":"25"}]} 

Here is the ajax function:

 $.ajax({ type: 'GET', url:'index.php', success:function(msg){ var result = JSON.parse(msg); $('.result').html(result); } }); 

Nothing in reply

  • So what's the answer, what will be in msg ? - Evgeny Ivanov
  • @ YevgenyIvanov there is nothing there now, I need an array - Winteriscoming
  • @ YevgenyIvanov later I’m shoving this array by tags - Winteriscoming
  • That is, now there is nothing in the msg variable itself? Is it empty? - Evgeny Ivanov
  • In the browser console looked? You parse the response into an object and try to push it into the jQuery string parameter of the .html() function - RifmaMan

1 answer 1

 $.ajax({ type: 'GET', url:'index.php', success:function(msg){ //var result = JSON.parse(msg); console.log(typeof msg, msg); }, error: function(request) { console.log("ERROR", request); } }); 

Report that in the browser console.

string {"transaction": [{"id": "0", "btc": "0.2", "dtime": "25"}, {"id": "1", "btc": "0.2", "dtime": "25"}]}

A string comes to the success handler (which is odd, I thought that jQuery, in the absence of a dataType trying to determine the type of response data). After JSON.parse string is converted to an object. The function $().html(...) takes an html string or function. When a js object is served there, the innerHTML selected DOM elements is cleared.

 success:function(msg){ var result = JSON.parse(msg); for (var i = 0; i < result.transaction.length; i++) { $('.result').append($("<div></div>").text(result.transaction[i].dtime)); } } 

Option without JSON.parse :

 dataType: "json", success:function(result){ for (var i = 0; i < result.transaction.length; i++) { $('.result').append($("<div></div>").text(result.transaction[i].dtime)); } } 
  • string {"transaction":[{"id":"0","btc":"0.2","dtime":"25"},{"id":"1","btc":"0.2","dtime":"25"}]} - Winteriscoming
  • one
    @Winteriscoming Lord, you read the comment from me above in the question, in $('.result').html() you need to pass a string, and you function var result = JSON.parse(msg); parsed the data into the js object how do you collect the object to push into the string parameter? try this: $('.result').html(result.transaction[0].dtime) - RifmaMan 1:46 pm
  • When I do this with pens $('.result').html("123"); All OK - Winteriscoming
  • @RifmaMan If everything is normal, then it should see at least "[object Object]". - Igor
  • @RifmaMan thanks, works. - Winteriscoming