I am having some odd problems with data coming back from a jquery Ajax call that I cannot figure out.
I have a c# asp.net web page that binds a valid JSON data blob to the UI with client side JavaScript on page load. This part works just fine. I set up a jquery Ajax post back that returns the same data and calls the same JavaScript data binding method, and this throws an error when I attempt to bind the data. It looks like the JSON written to the page on load is properly treated as a JSON object, but the data returned by the ajax call isn't.
Here is the ajax call:
jQuery.ajax({
type: 'POST',
data: "{'move_list': '1-2,3-2'}",
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
url: 'Puzzle.aspx/ProcessMove',
complete: OnComplete,
success: function(data){BindData(data);},
error: OnError
});
Here is a sample of the JSON data that is being processed:
{"game": [{"x":0,"y":0,"color":"Blue"},{"x":1,"y":0,"color":"Green"}]}
Here is the code that loads the data when the page is first loaded:
<script type="text/javascript">
// method returns JSON object above.
// client side code appears like this:
// BindData({"game": [{"x":0,"y":0,"color":"Blue"},{"x":1,"y":0,"color":"Green"}]});
BindData(<%=Game.SerializeToJson()%>);
</script>
and finally, the JavaScript binding function:
function BindData(data)
{
try
{
document.getElementById("square1").className = data.game[0].color;
// much more of the same....
}
catch(exception)
{
alert(exception.message);
// error thrown here is 'data.game is undefined'.
// the data object is being treated like a string and not a JSON object.
// so the indexing into the object fails.
}
}
I have double checked the JSON data with several online JSON parsers, and the data is formatted correctly. The server side code generates the same output in either case.
I tried to change the jquery Ajax call to...
success: function(data){BindData(JSON.parse(data));},
...to see if it was just treating the returned data as a string as opposed to a JSON object, but that just generates this message:
SyntaxError: JSON.parse: unexpected character
BindData(JSON.parse(data));
Completely stumped by this one. I have been reading everything I can find and trying all sorts of things, but nothing seems to work.
Related
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 trying to develop a function to send json data via get method using javascript instead of curl.
And it also works fine with the get method of jquery ajax api.For example,
$.ajax({
url : url,
type : "GET",
data : json,
dataType: "json",
//.....
//other code here.
})
But something wrong happened, when I try to send the same json data by the follow code as someone else suggest here.
xmlhttp.open("GET",url+"?pretty="+encodeURIComponent(JSON.stringify(json)),true);
xmlhttp.setRequestHeader("Content-type","application/json");
xmlhttp.send();
However,it seems that the json data is too large to be encoded inside the url, and the url was truncated.
So, I wander how I can send the large json with javascript just as the jquery does.
I have the following code, as part of a code to add some value to a database.
After executing the $.ajax succesfully, I want a specific div (with class 'lijst') to be reloaded with the refreshed data.
$.ajax({
url: \"frontend/inc/functions/add_selectie.php\",
type: \"POST\",
data: ({ 'p_id' : p_id, 'v_id' : v_id, 'pd_id' : pd_id }),
cache: false,
success: function()
{
$(\".lijst\").hide().fadeIn('slow');
}
});
However, with this solution, only the div is refreshed, not the actual PHP variables that are specified in there. When I refresh my browser manually, the values are updated.
How can I refresh the div and also update the variables?
According to the jQuery.ajax documentation, the function signature of "success".
Type: Function( PlainObject data, String textStatus, jqXHR
jqXHR ) A function to be called if the request succeeds. The function
gets passed three arguments: The data returned from the server ...
So in other words:
success: function(data) {
$(".lijst").html(data).hide().fadeIn('slow');
}
Actually, the PHP variables specified in the html are worked at the sever part. PHP variables in the html have replaced by the string of there value when it is ready to be sent to the browser. And your ajax request will cause PHP to update database. So when you have sent the request and then refresh the page, PHP will replace the varables in the html again.
According to this above, your ajax request and the server repsonse are not aware of the PHP variables's existence. So you must update the content yourself.
Maybe you will do something like this:
success: function(data) {
$(".lijst").hide();
$(".title").html(data.title); // $(".title") may be a tag that surround a PHP variable
$(".content").html(data.content); // the same as $(".title")
$(".lijst").fadeIn('slow');
}
I am parsing generated json with jquery $.ajax but there is one option that I dont understand. I saw it in some examples and tried to look for at jquery.com but still not sure about it:
this option is:
data: { get_param: 'value' }
which is used like this:
$.ajax({
type: 'GET',
url: 'http://example/functions.php',
data: { get_param: 'value' }, //why we shell use that in that case?
success: function (data) {
var names = data
$('#cand').html(data);
}
});
I know that "data:" is what sent to the server but parsing JSON I thought i don't send but retrieve from server with GET type. And the next part "get_param: 'value'"
does not make sense to me in that case either, could anyone please explain when and what for and in what cases it shell be used?
thank you.
I know that "data" is what sent to the server
Yes. If data is an object, it gets serialized to an application/x-www-form-urlencoded string and then placed in the query string or request body as appropriate for the request type (GET/POST).
jQuery does all the escaping necessary for this.
(It also, by default, collapses nested data structures (you don't have any in your example) into PHP-style by adding [] to key names).
but parsing JSON
JSON is not involved (unless the server responds with some).
when and what for and in what cases it shell be used
Whenever you want to pass data to the server rather than requesting a static URI.
You don't send JSON (usually), you send simple GET or POST HTTP parameters. They are given to the ajax method in an object literal usually, but you could have used the string "getparam=value", too. If you provide an object, jQuery will do the parameter-serialisation and URL-encoding for you - they're sent as x-www-form-urlencoded.
To cite from the docs:
data (Object, String)
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests. See
processData option to prevent this automatic processing. Object must
be Key/Value pairs. If value is an Array, jQuery serializes multiple
values with same key based on the value of the traditional setting.
I have a weird scinario. I have been using $.ajax() to make ajax calls to my server for data and have been using the same sort of format for these server calls. All has been going fine but suddenly I wrote a function and returned a JSON object that jQuery is unable to drill into. I looked at it in Firebug and everything appears normal. Can someone help me here to understand why suddenly I am unable to drill into this particular data object?
Here is the ajax code:
$.ajax(
{
type: "GET",
url: "php/getoptions.php",
dataType: 'json',
data: 'id='+id,
success: function(j)
{
alert(j.isdefault);
}
});
when I try to do this, the alert gives me "undefined." I have tried "alert(JSON.stringify(j))" and I see the valid json being returned. I have even taken the json that I saw in Firebug and run it through JSONLint and it returned valid.
Here is a sample of the json coming back:
[{"isdefault":"1","option1":"1","option2":"0","option3":"0","option4":"1","option5":"1"}]
WHAT IS GOING ON? Why can jQuery suddenly not drill into this data set?
thanks!
You need...
alert(j[0].isdefault);
...because the object that has the isdefault property is at index 0 of an Array.