Asked  7 Months ago    Answers:  5   Viewed   37 times

I am sending an ajax request with two post values, the first is "action" which defines what actions my php script has to parse, the other is "id" which is the id of the user it has to parse the script for.

The server returns 6 values inside an array() and is then encoded to JSON with the PHP function: json_encode();

Some of my responses are HTML, but when I encode it to JSON, it escapes "/" so it becomes "/"
How do I disable that?

Also when I don't know how to display this in jQuery when I get the server response, I just thought that putting it all into a div would just display the numbers and HTML codes I had requested, but it displays the array as it is encoded in PHP.

PHP

$response = array();
$response[] = "<a href=''>link</a>";
$response[] = 1;
echo json_encode($response);

jQuery:

$.ajax({
    type: "POST",
    dataType: "json",
    url: "main.php",
    data: "action=loadall&id=" + id,
    complete: function(data) {
        $('#main').html(data.responseText);
    }
});

How do I make this into working JSON?

 Answers

84

You need to call the

$.parseJSON();

For example:

...
success: function(data){
       var json = $.parseJSON(data); // create an object with the key of the array
       alert(json.html); // where html is the key of array that you want, $response['html'] = "<a>something..</a>";
    },
    error: function(data){
       var json = $.parseJSON(data);
       alert(json.error);
    } ...

see this in http://api.jquery.com/jQuery.parseJSON/

if you still have the problem of slashes: search for security.magicquotes.disabling.php or: function.stripslashes.php

Note:

This answer here is for those who try to use $.ajax with the dataType property set to json and even that got the wrong response type. Defining the header('Content-type: application/json'); in the server may correct the problem, but if you are returning text/html or any other type, the $.ajax method should convert it to json. I make a test with older versions of jQuery and only after version 1.4.4 the $.ajax force to convert any content-type to the dataType passed. So if you have this problem, try to update your jQuery version.

Wednesday, March 31, 2021
 
bumperbox
answered 7 Months ago
21

Set the dataType:"JSON" and callback in your ajax call.

For example:

$.ajax({
    url: "yourphp.php?id="+yourid,
    dataType: "JSON",
    success: function(json){
        //here inside json variable you've the json returned by your PHP
        for(var i=0;i<json.length;i++){
            $('#items_container').append(json[i].item_id)
        }
    }
})

Please also consider in your PHP set the JSON content-type. header('Content-type: application/json');

Wednesday, March 31, 2021
 
TheFrack
answered 7 Months ago
44

Use parseJSON on the return data:

if (msg) {
  msg = $.parseJSON(msg);
  alert(msg.hello);
}
Friday, May 28, 2021
 
alioygur
answered 5 Months ago
44

I encountered this error before, and solved after using jquery-JSONP

[Example]

$.getJSON('http://server-url/Handler.ashx/?Callback=DocumentReadStatus',
  {
      userID: vuserID,
      documentID: vdocumentID
  },
  function(result) {
      if (result.readStatus == '1') {
          alert("ACCEPTED");
      }
      else if (result.readStatus == '0') {
          alert("NOT ACCEPTED");
      }
      else {
          alert(result.readStatus);
      }
  });
Wednesday, August 4, 2021
 
Dobz
answered 3 Months ago
17

You don't get to return the result because it's not defined by the time your outer function finishes. Your AJAX call is happening asynchronously and the callback function is being called after the POST happens. To deal with your result, you need to do something like this:

function myjsfunc(some_data) {
    $.post("/myscript.php", { some_data: some_data }, function(response) {
            if (some_data.prop) {
                myReturnHandler(response);
            } else {
                myOtherHandler(response);
            }
        }
    );
}

Where you'll define myReturnHandler separately and it will need to know how to take over processing with the result data.

-- EDITED --

You can also perform tests to determine how to handle your response. Added extra code to demonstrate.

Wednesday, September 1, 2021
 
thebluephantom
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :