I am sending a ajax request with 2 post values, the first is "action" wich defines what actions my php script has to parse, the other is "id" wich is the id of the user it has to parse the script for.
The server returns 6 values inside a 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 to working JSON?
Try below code. Json parse() method is not required since your datatype is json itself. Parse is needed to convert text into a JavaScript object.
Firstly, it will help if you set the headers of your PHP to serve JSON:
Secondly, it will help to adjust your ajax call:
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).
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
You need to call the
For example:
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 thedataType
property set tojson
and even that got the wrong response type. Defining theheader('Content-type: application/json');
in the server may correct the problem, but if you are returningtext/html
or any other type, the$.ajax
method should convert it tojson
. I make a test with older versions of jQuery and only after version1.4.4
the$.ajax
force to convert any content-type to thedataType
passed. So if you have this problem, try to update your jQuery version.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
JS (Change the dataType from json to html or just don't set it jQuery will figure it out)