53

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?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Flaashing
  • 731
  • 2
  • 11
  • 18
  • Can you also dump your JSON response to get a better idea of the problem? Not sure what you mean by "/" so it becomes "/" – Sid Feb 01 '12 at 15:41
  • have you tried http://api.jquery.com/jQuery.getJSON/ ? – ka_lin Feb 01 '12 at 15:42
  • sorry sid i made a backslash but it kinda disappeared :) but every normal slash gets a backslash before it "backslash"+"normal slash" ka_lin: i looked at it but i didnt understand it, and if i did, how would i send some post data with the request ? – Flaashing Feb 01 '12 at 15:44

5 Answers5

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.

Guilherme
  • 1,980
  • 22
  • 23
  • it returns an error: missing ) after argument list "alert(data.0);" – Flaashing Feb 01 '12 at 16:22
  • yes, it was an example. You have to define your array with a key that can be converted to an object, because numbers can be. like $response['html'] = "something"; than you call it using the parseJSON json.html (like the example above). – Guilherme Feb 01 '12 at 19:06
  • 1
    pls make correction use alert(json.html); instead of alert(data.html); – PHP Ferrari Jan 22 '13 at 08:40
  • 6
    when `dataType: "json"` is used in the ajax-call then you should not need to `$.parseJSON`; from the jQuery docs: "(dataType:)"json": Evaluates the response as JSON and returns a **JavaScript object**. " – low_rents Feb 11 '15 at 09:56
  • Yes @northkildonan, you are right, in fact, the @sgb answer is the right answer, but if you look at the jquery code, when you pass `dataType` it really converts the response in the specific type, but Flaashing done that already, and it didn't converted. I don't know why this happens, but I have this same problem once, and the only way is parsing the response. – Guilherme Feb 11 '15 at 13:28
  • @Guilherme it just happened to me today for the first time, because i double encoded my JSON with PHP by accident. – low_rents Feb 11 '15 at 13:48
  • i think, its the best answer. thanks man! – Rafik Bojes Mar 01 '22 at 06:17
43

Firstly, it will help if you set the headers of your PHP to serve JSON:

header('Content-type: application/json');

Secondly, it will help to adjust your ajax call:

$.ajax({
    url: "main.php",
    type: "POST",
    dataType: "json",
    data: {"action": "loadall", "id": id},
    success: function(data){
        console.log(data);
    },
    error: function(error){
         console.log("Error:");
         console.log(error);
    }
});

If successful, the response you receieve should be picked up as true JSON and an object should be logged to console.

NOTE: If you want to pick up pure html, you might want to consider using another method to JSON, but I personally recommend using JSON and rendering it into html using templates (such as Handlebars js).

sgb
  • 2,234
  • 2
  • 19
  • 31
  • i tried your example, in my firebug console i get the response : missing } after property list "sucess: function(data){" yeah, you missed a coma after setting data. but now it gives me a response coded in json in firebug – Flaashing Feb 01 '12 at 15:52
  • I had a syntax error - "sucess" should be "success", and I missed a comma. You should be able to explore your response now and output parts of it into the DOM. – sgb Feb 01 '12 at 15:55
  • yes about that, how do u split the array into 6 bits in jquery and output them in 6 diffrent elements ? – Flaashing Feb 01 '12 at 15:59
  • it depends on the structure of your JSON, if you link a sample, I can help. – sgb Feb 01 '12 at 16:00
  • you'll need your PHP to output an array into JSON rather than html to do that. – sgb Feb 01 '12 at 16:59
  • what ? i get the json array fine now i just want to display each response in its respective element. if you take a look at the link, in the console you can see – Flaashing Feb 01 '12 at 17:03
  • it returns valid? i dont see where you are going with this ? – Flaashing Feb 01 '12 at 17:07
  • Okay, well your JSON is valid, but it contains '0' every other value. You're also using raw HTML which i don't recommend. But here's an example of how to get your content. http://jsfiddle.net/vf7TB/1/ – sgb Feb 01 '12 at 17:14
  • thanks alot :) no, i know what you mean but i will see what i can do to fix it :) – Flaashing Feb 01 '12 at 17:19
  • okay so now i have tried a couple of things, but i just wont work, its only if i say data.responseText, that i can display the array but then its only a string, if i just say json = data; i get value "null", its not an array when i get the response. why ? – Flaashing Feb 01 '12 at 18:45
2

Connect your javascript clientside controller and php serverside controller using sending and receiving opcodes with binded data. So your php code can send as response functional delta for js recepient/listener

see https://github.com/ArtNazarov/LazyJs

Sorry for my bad English

ArtNazarov
  • 83
  • 4
2

Since you are creating a markup as a string you don't have convert it into json. Just send it as it is combining all the array elements using implode method. Try this.

PHP change

$response = array();
$response[] = "<a href=''>link</a>";
$response[] = 1;
echo implode("", $response);//<-----Combine array items into single string

JS (Change the dataType from json to html or just don't set it jQuery will figure it out)

$.ajax({
   type: "POST", 
   dataType: "html", 
   url: "main.php", 
   data: "action=loadall&id=" + id,
   success: function(response){
      $('#main').html(response);
   }
});
ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
1

Try this code. You don't require the parse function because your data type is JSON so it is return JSON object.

$.ajax({
    url : base_url+"Login/submit",
    type: "POST",
    dataType: "json",
    data : {
        'username': username,
        'password': password
    },
    success: function(data)
    {
        alert(data.status);
    }
});
Dharman
  • 30,962
  • 25
  • 85
  • 135