dataType: "json" won't work - php

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"));
?>

Related

Getting an ajax post data in php

$.ajax({
url: '/gateway/',
type: 'POST',
data: {test : 'test'},
dataType: 'json',
}).done(function(){
console.log('done');
});
Above is my AJAX post, below is my PHP:
var_dump($_POST['test']);
die();
The problem is, this fails to work (I get a NULL value) - why?
I know my call is getting to the PHP code as I can dump any old string:
var_dump('hello');
die();
Where am I going wrong?
Just remove this dataType: 'json'. Your $_POST['test'] is a string value, not a JSON string.
The POST value that you are testing with is not JSON, it's a string.
Remove the
dataType: 'json',
and it should work.
When you set dataType: "json" within the AJAX request it means the expected response should be parsed as json, (not the outgoing POST, as others have said).
Heres is a stripped down copy&paste example, for you to build upon. Hope it helps
<?php
//is it POST
if($_SERVER['REQUEST_METHOD'] == 'POST'){
// set var
$test = isset($_POST['test']) ? $_POST['test'] : null;
//do some logic - skip that bit ;p
//was the request from AJAX, ok send back json
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//always a good idea
header('Content-Type: application/json');
//json encode, notice the ABC, then look at the jQuery below
die(json_encode(
array('ABC' => 'From Response: '.$test)
));
}
}
?>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
jQuery(document).ready(function(){
var ajax = $.ajax({
url: "./",
type: "POST",
data: {test : 'test'},
dataType: "json"
});
ajax.done(function(data) {
$("#result").html(data.ABC); /* << See data is an object */
});
ajax.fail(function(xhr, status, error) {
$("#result").html(xhr.responseText);
});
});
</script>
<span id="result"></span>
I'm not totally sure if this is the issue, but .done is deprecated. Additionally, as others mentioned, you are asking for json from the server and not receiving json.
Your code should look like this
$.ajax({
url: '/gateway/',
type: 'POST',
data: {test : 'test'},
success: function () {console.log('done');}
});
I would like to recommend you my code. and please do check the following points.
check the location of the url you are giving. If it is in parent directory then you can access it using ../ and the most important thing give the extension of the file. like 'gateway.php'
and write success and failure function. It gives a better insight of what's going on.
$.ajax({
type:'POST',
url:'gateway',
data:{test:'test'},
success: function(data){
if(data)
{
alert(data);
}
},
failure: function(){
alert(failed);
}
}) ;
comment if there are any errors
hope it helps :). If it does then don't forget to green it :P
Or change PHP code
header('Content-Type: application/json');
exit(json_encode(array('data' => 'Bla bla bla')));

Sending additional variable to server with dataUrl

This should be a simple fix, but I just have not been able to find anything about it.
I am using both postData and editData to POST a variable to the server for form editing. This variable is used in a switch to select the appropriate function. This php contains ALL of the functions for the project. I want to avoid having many different php pages.
So all of that is fine, but I cannot find a way to do the same thing for dataUrl. The one lead I've been able to find is using ajaxSelectOptions, specifically the data option. If this is the appropriate way to go about this, what is the way to use it? Like this?:
ajaxSelectOptions:{
contentType: "application/json",
dataType:'json',
type:'POST',
action: function(){
return 'popCodeAdjust';
}
}
In general you can use data property of ajaxSelectOptions. The code cam look like
ajaxSelectOptions: {
type: "POST",
data: {
action: "popCodeAdjust";
}
}
or
ajaxSelectOptions: {
type: "POST",
data: {
action: function () {
return "popCodeAdjust";
}
}
}
See here or here.
The problem can be if you really need to send the data in JSON format. In the case you can need either to serialize the value of the parameter data (like JSON.stringify({action: actionValue})) or the value with parameter name (like action: JSON.stringify(actionValue)). See the answer which role play BodyStyle attribute (WebMessageBodyStyle.Wrapped, WebMessageBodyStyle.WrappedResponse etc) in WCF method in the case.
In jqGrid 4.4.2 or higher (see the answer, my pull request and the fix) you can use postData as function. You can define it either inside of ajaxSelectOptions
ajaxSelectOptions: {
contentType: "application/json",
dataType: "json",
type: "POST",
postData: function (rowid, value, name) {
return JSON.stringify({action: "popCodeAdjust"});
//or depend on the relinquishment of the server side
//return {action: JSON.stringify("popCodeAdjust")});
}
}
You can specify postData alternatively inside of editoptions (see here).
How about?
$.ajax({
type: 'POST',
url: 'url',
data: { varName: JSON.stringify(arrayValues) },
dataType: 'json',
success: function(msg) {...},
error: function(res, status, exeption) {...}
});
Server-side:
$var = json_decode($_POST['varName'], true);
Inside your grid setup it would be:
postData: { KeyName: KeyValue },
You will see this extra parameter go out with your POST.
The example below will set the postData value, (if it was to change) and then trigger a reload of the grid.
$('#gridName').jqGrid('setGridParam', { postData: { UserName: userName }).trigger('reloadGrid', [{ page: 1}]);

jQuery ajax request with json response, how to?

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);
}
});

How to get data out of PHP generated JSON in JQuery

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!

jquery ajax not working?

i have a jquery ajax post that for some reasons doesn't work:
<script>
var callback = function(data) {
if (data['order_id']) {
$.ajax({
type: 'POST',
url: '<?php echo $_SERVER['PHP_SELF']; ?>',
data: { myid: 123456 },
success: function(data) {
alert("Transaction Completed!");
}
});
}}
</script>
<?php if ($_POST['myid']) { echo $_POST['myid']; } ?>
the 'callback' functions works fine(i test it), just that it stops at the ajax post
and i cant see my echo's
any ideas on what i am doing wrong?
thanks
edit:
i edited the script a bit at the point where the ajax is posting successfully but i cant get the php to echo anything
If the AJAX - Call is succeeding now, you can't just echo anything with PHP. The data is sent to the client, but PHP is interpreted at the server. You're not sending an HTTP - Request anymore (which is pretty much the point of an AJAX-Call), so PHP is not going to do anything at this point.
You have to add your new content to the DOM with JavaScript. Try this and see if you get the message shown on your page. I append it to the body, because I don't know how your Markup and your returned data looks like:
$.ajax({
type: 'POST',
url: '<?php echo $_SERVER['PHP_SELF']; ?>',
data: { myid: 123456 },
success: function(data) {
alert("Transaction Completed!");
$('body').prepend('<p>Successful AJAX - Call</p>');
}
});
Then you can take a look at your data-variable with console.log(data), access the returned data and modify the DOM via JavaScript.
ok, for a start.
writeback("Transaction Completed!";
fix it to:
writeback("Transaction Completed!");
you have a trailing comma after 123456
data: { myid: 123456, },
you're missing a closing } to your callback function

Categories