a.php
$(document).ready(function() {
$("#submit_form").on("click",function(){
var json_hist = <?php echo $json_history; ?>;
$.ajax({
type: "POST",
url: "b.php",
data: "hist_json="+JSON.stringify(json_hist),
//contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){alert(data);},
failure: function(errMsg) {
alert(errMsg);
}
});
});
})
b.php
$obj=json_decode($_POST["hist_json"]);
var_dump($_POST);
If I comment
contentType: "application/json; charset=utf-8"
everything's works fine but if uncomment this.
The var dump will return null.
When you set the contentType in the ajax, you are setting the contentType for the request not the response.
It fails with the JSON contentType because the data you're sending is key/value formatted data (which is missing the encoding) and so the data doesn't match the contentType. The JSON contentType header is for when you're sending raw JSON with no identifiers, but in your case you have an identifier hist_json=.
I suggest changing to:
data: { hist_json : JSON.stringify(json_hist) },
Using an object with the hits_json key will mean that jQuery will safely URL encode the JSON and will allow the PHP to pick it up with $_POST['hits_json'].
If you want to use the JSON contentType then you will have to change the ajax to:
data: { JSON.stringify(json_hist) }, // <-- no identifier
and the PHP:
$obj = json_decode($HTTP_RAW_POST_DATA);
var_dump($obj);
From what I know it's bug that appears in FireFox.
you can read more on http://bugs.jquery.com/ticket/13758
There is also topic in stackoverflow about it
Cannot set content-type to 'application/json' in jQuery.ajax
The line you have commented out is trying to change the Content-type: header to application/json. While the data you are sending is in JSON format, the data is being transmitted as an HTTP POST request, so you need to use a content type of application/x-www-form-urlencoded;, which is the default. That's why it works with the line removed.
Related
I am writing my first Javascript/PHP Web application.
On the client side I am using the below code:
<script>
$.ajax({
url: "Search.php",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{SubGroup:"'+SubGroup+'",FlowerColor:"'+FlowerColor+'"}',
cache: false,
success: function (data) {
console.log("Back from AJAX - Success.");
// $(document).ajaxSuccess implements the success logic
},
error: function (data) {
console.log("Back from AJAX - Error.");
}
});
The Web Service Search.php runs perfectly with one major issue. The data sent from the ajax statement (SubGroup and FlowerColor) are not received. I am using the code below.
<?php
if (isset($_POST["SubGroup"])) {
$SubGroup = $_POST['SubGroup'];
} else {
error_log("Invalid input Received (SubGroup)");
exit;
}
Strangely enough i am receiving the rest of the header information perfectly with the below code:
// Getting headers sent by the client.
$headers = apache_request_headers();
foreach($headers as $key => $value)
{
error_log($key . ' = ' . $value);;
}
If you pass data as a string, it should be URL-encoded, and not a string representation of JSON : SubGroup=...&FlowerColor=...
You can also pass you data as an object :
data: {SubGroup: 'mygroup', FlowerColor: 'mycolor'}
From the JQuery Doc
processData (default: true)
Type: Boolean
By default, data passed in
to the data option as an object (technically, anything other than a
string) will be processed and transformed into a query string, fitting
to the default content-type "application/x-www-form-urlencoded". If
you want to send a DOMDocument, or other non-processed data, set this
option to false.
I'm trying to send back multiple variables from a php file to ajax using json in an array. The code in the php file works perfectly and does everything with my database like it should. But as soon as I add dataType: "json" in ajax, nothing happens in the php file anymore. I googled a bit and some people mentioned it could be a browser problem, but so far it doesn't work in either firefox, chrome or IE. I'm using the latest version of jQuery.
This is what happens inside php:
<?php
//Create variables and update database
echo json_encode(array("id" => "$realid", "un" => "$username", "date" => "$date"));
?>
And this is the ajax code:
.ajax(
{
url: 'UpdateComments.php',
type: 'POST',
dataType: "json",
data:
{
type: "add",
comment: $("#comment").val(),
id: videoID
},
success: function (data)
{
//Get the data variables from json and display them on page
}
});
I'm clueless on this, any advice would be greatly appreciated!
Common issue is that browser prints "something else" before JSON whether that is some readable or unreadable(invisible) char. Try doing something like this:
<?php
//at the very beginning start output buffereing
ob_start();
// do your logic here
// right before outputting the JSON, clear the buffer.
ob_end_clean();
// now print
echo json_encode(array("id" => $realid, "un" => $username, "date" => $date));
?>
Now, all supplement data (before JSON) will be discarded and you should have it working...
I believe if you use dataType you should be using contentType, "The official Internet media type for JSON is application/json".
.ajax(
{
url: 'UpdateComments.php',
type: 'POST',
contentType: "application/json",//note the contentType defintion
dataType: "json",
data:
{
type: "add",
comment: $("#comment").val(),
id: videoID
},
success: function (data)
{
//Get the data variables from json and display them on page
}
});
It's easy to forget about an echo or a var_dump() that you may have been using in the past to test how your script is working.
In my own script I had a var_dump(), which I had forgotten about, that wasn't using JSON_encode-ed text and sent plain text to the browser. This broke the dataType:"json" requirement and caused the success function not to work.
Took me a while to find the problem as I had ctrl+f(ed) for echo only and forgot about the vagabond var_dump().
printf is probably another suspect.
If you set the dataType in jQuery, that actually sets the Content-Type header attribute. Perhaps, in your PHP script you will need to declare this MIME type as accepted. Did you notice if the code even enters the PHP script when you make the request? I doubt it is a browser problem if it doesn't work in Firefox, Chrome or IE.
To gain a better perspective at your AJAX request, subscribe to the ajaxBeforeSend (not sure if the event name is right check jQ docs) event and log the xhr object.
I wouldn't use the dataType if it is causing you issues, also I've personally not used an object as the data value before maybe that has something to do with it?
Anyway I've tweaked the main ajax routine I hope this helps.
$.ajax(
{
url: 'UpdateComments.php',
type: 'POST',
data:
{
type: "add",
comment: $("#comment").val(),
id: videoID
},
success: function (response)
{
//Get the data variables from json and display them on page
var data = $.parseJSON(response);
alert(data.id);
}
});
Try defining the error handler as part of the $.ajax call
$.ajax({
...,
error: function(xml, error) {
console.log(error);
}
});
Then check your debugging console for any errors that can help you diagnose the problem.
$.ajax({
url: '/route/',
type: 'POST',
dataType: "json",
data:
{
type: "add",
comment: $("#comment").val(),
id: videoID
},
success: data => {console.log(data);}
});
<?php
ob_start();
ob_end_clean();
echo json_encode(array("id" => "$realid", "un" => "$username", "date" => "$date"));
?>
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?
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.
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).
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);
}
});
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
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);
}
});
By using Alert on the response paramater after a jquery success will display the values I need, and the problem is picking them out with k/v. I don't know if this is some incompatibily issue with json format or what, from php. Either nothing happens (no Alert) or the alert will say 'undefined' if I attempt to get values by using the keys to them.
Relevant code:
JQuery:
var curr = $(this).val();
// alert(curr);
$.ajax({
type: 'GET',
url: 'CurrencyResponse.php?q='+curr,
contentType: "application/json; charset=utf-8",
success: function(response) {
var items = response.d;
// alert(response); this will display some json key value from server
$.each(items, function (index, item) {
// alert(item.msg); or updating some div tag here, eventless
});
},
PHP:
<?php
// $query = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
// $query = $_GET["q"];
$response = array();
$response["msg"] = "Hjksa!";
$response["nok"] = "9.32";
echo json_encode($response);
?>
Help here will be much appreciated! =)
Use the dataType parameter for jQuery's AJAX, like so:
$.ajax({
type: 'GET',
url: 'CurrencyResponse.php?q='+curr,
dataType: 'json',
success: function( json) {
alert( json.msg); // Will output Hjksa!
}
});
This tells jQuery that the response from the server is JSON, and that it should return a JSON object to the callback functions that take the server response as their parameters.
Read more about dataType on jQuery's site.
Judging from the documentation, it'll read the MIME type from the response header, and use that, unless you explicitly specify it. So either set the headers on the PHP script to application/json or set the "dataType" param to "json".
I recommend sending an object to the client script. It makes it easier to read the data.
echo json_encode((object) $array);
I was working through a similar problem for a couple of days, I had set
dataType: "json",
but it was still coming back as a string. Specifying json in the header of my php file in addition to in the jquery request resolved the issue for me.
header("Content-type: application/json");
Hopefully that helps someone!
I am trying to send simple data to theservre, and I need a "rough and ready" way to do this.
This is what I have so far:
var emails = ['a#123.com', 'b#123.com', 'c#123.com'];
var ruff_json = "{ 'emails': [";
for (i in emails)
ruff_json += ((i == 0) ? '' : ', ') + '\''+emails[i]+'\'';
ruff_json += '] }';
jQuery.ajax({
type: 'POST',
url: '1.php',
data: ruff_json,
dataType: "json",
timeout: 2000,
success: function(result){
//do something
},
error: function (xhr, ajaxOptions, thrownError){
//do something
}
});
Using Firebug, I can see that the data is POSTed to the server - however, at the server, there is no data ($_POST is empty) - what am I doing wrong?
We post all of our data with json.
var myobj = { this: 'that' };
$.ajax({
url: "my.php",
data: JSON.stringify(myobj),
processData: false,
dataType: "json",
success:function(a) { },
error:function() {}
});
then in php we do
<?php
$json = json_decode(file_get_contents("php://input"), true);
// Access your $json['this']
// then when you are done
header("Content-type: application/json");
print json_encode(array(
"passed" => "back"
));
?>
This way we don't even mess with the post variables, and in general, its faster than having jQuery process them.
Your data field should contain an object with key-value pairs, because it gets encoded as POST key-values pairs.
data = {my_json: encoded_string};
Then on the PHP side you can access the data as:
$data = json_decode($_POST['my_json']);
PHP populates $_POST by parsing the data received. However, it only knows form-encoded data, JSON data cannot be parsed automatically. So $_POST will be useless in this case. You need to get the raw post data and parse it with json_decode.