I am working on the backend for a webpage that displays EPG information for TV channels from a SQlite3 database. The data is provided by a PHP script echoing a JSON string. This itself works, executing the php program manually creates a JSON string of this format
[{"id":"0001","name":"RTL","frequency":"626000000"},{"id":...
I want to use these objects later to create HTML elements but the ajax function to get the string doesn't work. I have looked at multiple examples and tutorials but they all seemed to be focused more on having PHP return self contained HTML elements. The relevant js on my page is this:
var channelList;
$(document).ready(function() {
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data.success);
channelList = data;
}
});
});
However the channelList variable remains empty when inspected via console.
What am I doing wrong?
Please ensure that your PHP echoing the correct type of content.
To echo the JSON, please add the content-type in response header.
<?php
header(‘Content-type:text/json’); // To ensure output json type.
echo $your_json;
?>
It's because the variable is empty when the program runs. It is only populated once AJAX runs, and isn't updating the DOM when the variable is updated. You should use a callback and pass in the data from success() and use it where you need to.
Wrap the AJAX call in a function with a callback argument. Something like this:
function getChannels(callback){
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data);
if (typeof(callback) === 'function') {
callback(data);
}
},
error: function(data) {
if (typeof(callback) === 'function') {
callback(data);
}
}
});
}
Then use it when it becomes available. You should also use error() to help debug and it will quickly tell you if the error is on the client or server. This is slightly verbose because I'm checking to make sure callback is a function, but it's good practice to always check and fail gracefully.
getChannels(function(channels){
$('.channelDiv').html(channels.name);
$('.channelDiv2').html(channels.someOtherProperty);
});
I didn't test this, but this is how the flow should go. This SO post may be helpful.
EDIT: This is why frameworks like Angular are great, because you can quickly set watchers that will handle updating for you.
I am making an ajaxSubmit call to a web service, that will return XML.
When I make a call to the same service using XMLHttpRequest.send, the response is correct.
However if I use:
$(form).ajaxSubmit({
error: function _(response) {
$(iframeEl).remove();
config.error.call(scope, Thunderhead.util.JSON.decode(response));
},
success: function _(response) {
console.log(response);
$(iframeEl).remove();
var result = response;
config.success.call(scope, result);
},
iframe: true
});
This returns the correct XML response, but all tags have been transformed to lowercase.
I've checked the call in the Network tab in the developer console, and the case is correct in there, but when it is returned by the ajaxSubmit, it is lowercase.
Does anyone know what is causing this or how to rectify it?
Are you using Malsups jQuery form plugin
This plugin does a lot of toLowerCase transforms, I've not looked too closely but it does seem to lowercase the tag names of something, so this is probably your culprit.
I'd recommend refactoring to using a simple jQuery.ajax() call instead
$(form).on('submit', function(e) {
var url = $(form).attr('action');
e.preventDefault();
$.ajax( url, {
error: function _(jqXHResponse) {
// your code
},
success: function _(response) {
console.log(response);
// your code
}
});
This might be happening, because js is assuming xml as an answer. There is no difference for most xml-parsers which case is used in xml tag names.
I suggest trying to change response data type.
For example there is such option in jQuery.ajax method: http://api.jquery.com/jquery.ajax/ (named dataType). I would try using "text" dataType if case is really important.
Some further issues arose from this in the end, so just posting my eventual solution in case anyone else has this problem. I'm fairly new to javascript, so this might have been obvious to most, but it might help someone else out.
The success callback can actually take in 3 parameters, the third of which (arg2) is the actual response from the request, without any changes from the Malsups form plugin.
So in the end, the solution was simply to use this third parameter instead of the response parameter.
$(form).ajaxSubmit({
error: function _(response) {
$(iframeEl).remove();
config.error.call(scope, Thunderhead.util.JSON.decode(response));
},
success: function _(response, arg1, arg2) {
console.log(response);
$(iframeEl).remove();
var result = response;
config.success.call(scope, arg2.responseXML);
},
iframe: true
});
I'm fairly new to JQuery. The code below works and I can see the correct JSON response in Firebug. But I couldn't find a way how to get and parse it in the code. Alert window only shows
"[object Object]" but not any json text.
<script>
$.ajaxSetup({ cache: false });
var _token;
function make_token_auth(user, token) {
var tok = user + ':' + token;
return "Token " + tok;
}
$.ajax
({
type: "GET",
url: "url",
dataType: 'json',
beforeSend: function (xhr){
xhr.setRequestHeader('Auth', make_token_auth('userid', 'token'));
},
success: function (data){
alert(data);
}
});
</script>
The fact you precised
dataType: 'json',
tells jQuery to parse the received answer and give it as a javascript object to your success callback.
So what you have here is fine and what is alerted is correct (this is an object, so
alert simply prints the result of data.toString()).
Use console.log to see what it is exactly :
success: function (data){
console.log(data);
}
and open the developer tools in Chrome or the console in Firebug to browse the properties of the object.
don't use alert() for debugging -- it's often unhelpful (as in this case), and also has serious issues when used with asyncronous code (ie anything Ajax) because it interrupts the program flow.
You would be much better off using the browser's console.log() or console.dir() functions, and seeing the object displayed in the console. It is much more functional, and doesn't interrupt the flow of the program.
So instead of alert(myjsonvar) use console.log(myjsonvar).
You can get the json string by using JSON.stringify
var jsonstr = JSON.stringify(data);
alert(jsonstr);
The alert function expects you to pass in a string or number.
Try doing something like this:
for(x in data) {
alert(x + ': ' + data[x]);
}
Update in response to comments: You can use alert in development or production to see string and number values in the object returned by the server-side code.
However, carefully rereading your question, it looks like what you really want to see is the actual JSON text. Looking at #dystroy's answer above, I think that if you remove the dataType: 'json' from your $.ajax invokation, jQuery will treat the response as plain text instead of automatically converting it to an Object. In this case, you can see the text by passing it to the alert function.
Try using
data = JSON.parse(data)
Then do whatever you want with the data.
Source: JSON.parse() (MDN)
I had a problem with jquery's post api.
$(".MGdi").click(function () {
id=$(this).attr("rel")
$.post( 'Mdeger.asp?cmd=MG', { id: id, drm: $(this).html()} ,
function( data ) {
var $response=$(data);
var snc = $response.find('#snc').html();
alert(snc);
},"application/x-www-form-urlencoded");
});
Another way is:
$(".Pasif").click(function () {
id=$(this).attr("rel")
$.post( 'Mdeger.asp?cmd=Pasif', { id: id, drm: $(this).html()} ,
function( data ) {
$(this).html(data);
alert(data)
},"application/x-www-form-urlencoded");
});
Everything is OK on serverside but clientside's success function does nothing.
Even basic codes like alert("hoho"); success not triggering.
this usually happens when respond couldn't be parsed. you should check the respond using firebug or similar debugging tool.
especially the methods that expects json data, strictly validates the respond and if there is anything invalid it just does nothing, no-error, no-warning, no-exception.
when your callback function doesn't run, you should suspect that your respond isn't correct.
// Türkçe özet
uzun lafın kısası dönüş değerinde bir terslik varsa dönüş fonksiyonu çalışmayacaktır. sunucudan gelen değerleri iyice kontrol etmekte fayda var. jquery dönüş değerinde veya dönüş fonksiyonunda bir hata olursa seni uyarmadan işi sonlandırıyor.
I had this problem as well. It turns out I was making an AJAX call to the same domain, but on a different port, which is not allowed (for security reasons) in Javascript.
See this relevant question for more info:
How do I send an AJAX request on a different port with jQuery?
I was very surprised that the AJAX call would POST/GET to the server, (which I was able to verify by looking at the server log) but that the response was never read. I would have thought that both sending and receiving would be disallowed.
I had this error too, and that was a stupid problem : I set dataType to "json" in my JS, but the page called was returning plain HTML. And this cause to not fire the success function at all.
I've tried to parse the following json response with both the JQuery getJSON and ajax:
[{"iId":"1","heading":"Management Services","body":"<h1>Program Overview</h1><h1>January 29, 2009</h1>"}]
I've also tried it escaping the "/" characters like this:
[{"iId":"1","heading":"Management Services","body":"<h1>Program Overview <\/h1><h1>January 29, 2009<\/h1>"}]
When I use the getJSON it dose not execute the callback. So, I tried it with JQuery ajax as follows:
$.ajax({
url: jURL,
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
success: function(data){
wId = data.iId;
$("#txtHeading").val(data.heading);
$("#txtBody").val(data.body);
$("#add").slideUp("slow");
$("#edit").slideDown("slow");
},//success
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest="+XMLHttpRequest.responseText+"\ntextStatus="+textStatus+"\nerrorThrown="+errorThrown);
}
});
The ajax hits the error ans alerts the following:
XMLHttpRequest=[{"iId":"1","heading":"Management Services","body":"<h1>Program Overview </h1><h1>January 29, 2009</h1>"}]
textStatus=parseerror
errorThrown=undefined
Then I tried a simple JQuery get call to return the JSON using the following code:
$.get(jURL,function(data){
var json = eval("("+data+");");
wId = json.iId;
$("#txtHeading").val(json.heading);
$("#txtBody").val(json.body);
$("#add").slideUp("slow");
$("#edit").slideDown("slow");
})
The .get returns the JSON, but the eval comes up with errors no matter how I've modified the JSON (content-type header, other variations of the format, etc.)
What I've come up with is that there seem to be an issue returning the HTML in the JSON and getting it parsed. However, I have hope that I may have missed something that would allow me to get this data via JSON. Does anyone have any ideas?
The JSON string you have is an array with 1 object inside of it, so to access the object you have to access the array first. With a json.php that looks like this:
[
{
"iId": "1",
"heading": "Management Services",
"body": "<h1>Program Overview</h1><h1>January 29, 2009</h1>"
}
]
I just tried this
$.getJSON("json.php", function(json) {
alert(json[0].body); // <h1>Program Overview</h1><h1>January 29, 2009</h1>
alert(json[0].heading); // "Management Services"
alert(json[0].iId); // "1"
});
I also tried this:
$.get("json.php", function(data){
json = eval(data);
alert(json[0].body); // <h1>Program Overview</h1><h1>January 29, 2009</h1>
alert(json[0].heading); // "Management Services"
alert(json[0].iId); // "1"
});
And they both worked fine for me.
If anyone is still having problems with this it's because your response needs to be a JSON string and content-type "application/json".
Example for HTTP in asp.net (c#):
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
context.Response.Write("{ status: 'success' }");
}
hth,
Matti
Did you try XML-encoding the HTML (i.e. <H1>)?
You could have it return as text and then parse it with the json.org parser
To see if it works any differently
Pleas note that in the question there is a syntax error. The line with
x.overrideMimeType("application/j-son;charset=UTF-8");
should read
x.overrideMimeType("application/json; charset=UTF-8");
This makes a big difference too.
Remove the [], on front and last on JsonData, and it work.
Disabling Firebug Lite fixed this problem for me.
Bug with combination of: jQuery 1.4, ajax/json, Firebug Lite and IE 8
This is a working example and tested!
<script type="text/javascript">
function fetchData() {
var dataurl = "pie.json";
$.ajax({
url: dataurl,
cache: false,
method: 'GET',
dataType: 'json',
success: function(series) {
var data = [];
//alert(series.length);
for (var i=0; i<series.length;i++){
data[i]=series[i];
}
$.plot(
$("#placeholder"),
data,
{
series: {
pie: {
show: true,
label: {
show: true
}
}
},
legend: {
show: true
}
}
);
}
});
//setTimeout(fetchData, 1000);
}
</script>
And the json source is the following (pie.json):
[{ "label": "Series1", "data": 10},
{ "label": "Series2", "data": 30},
{ "label": "Series3", "data": 90},
{ "label": "Series4", "data": 70},
{ "label": "Series5", "data": 80},
{ "label": "Series6", "data": 110}]
First, try to pinpoint if the problem is with general JSON encoding/decoding. try simpler objects, with numbers and plain strings, then with quoted HTML.
After you get JSON working, you really should really consider removing the HTML from there. Much better is to move just data, and leave presentation details to the templates. When using AJAX, that means a hidden template in the HTML, and use jQuery to replicate it and fill with the data. check any of the jQuery template plugins. Of these, jTemplates is a common favorite.
I think you are asking wrong question. Using $.getJSON() is much easier, and if you got problem with it, would be better to ask for $.getJSON() than for $.ajax().
You might also find useful looking at getJSON function source code, because I see, you got a lot of useless stuff there with mimeTypes. That's not the way.
The value you are trying to parse is wrapped in brackets [], which means it is an array. You are trying to eval an array. Try to eval the first element of the array, and it should work...
var json = eval("("+data[0]+");");
Also, I would recommend using the JSON.parse() provided here instead of calling eval() directly.
I received a similar error. Took me a while to find out - little did I know that PHP has not (natively) supported JSON since PHP5.2. Critical reminder...
Yesterday at $. Ajax still no mistakes, today is quoted the mistake, some say parsererror jquery version of the problem, what I use is jquery-1.3.2.min.js, yesterday. This edition also done, today is washed-up. Data sources: no change. Don't know what reason be?
It is maybe because your output buffer is not empty, so AJAX receive bytes which don't belong to the JSON.
Try clean buffer with ob_clean() on server side just before output your json with echo or die(). And you don't need to specify contentType, I think for you default value will work correctly.
I had the same problem and it solve it.
Hope to help you.
in my case, the error was caused by a html tag in the json.
INCORRECT (parsererror)
{"msg": "Gracias,< br >Nos pondremos en contacto."}
CORRECT
{"msg": "Gracias, nos pondremos en contacto."}
BROWSER: IE7/IE8
also try this
$.ajax({
url: url,
data:datas,
success:function(datas, textStatus, jqXHR){
var returnedData = jQuery.parseJSON(datas.substr(datas.indexOf('{')));
})};
in my case server responds with unknow character before '{'
Don't use an array box, and make sure you format your data properly:
{"account":{"iId":"1","heading":"Management Services","body":"<h1>Program Overview</h1><h1>January 29, 2009</h1>"}}