jQuery ajax - blank response returned - ajax

I am trying to use jQuery ajax to get some values from the database and then return them in an array.
I have used the same code several times before but this time, no response is being returned. Although the post values are the correct values that I would expect. Here is the javascript code that I am using:
$.ajax({ url: '/BlogArchive.asmx/ChangePost'
, type: 'POST'
, contentType: 'application/json; charset=utf-8'
, data: '{FileName:"' + FileName + '"}'
, dataType: 'json'
, success: function (data)
{
var arrayList = data.d;
var BlogPostTitle = $(".BlogPostTitle")[0];
var BlogPostDate = $(".BlogPostDate")[0];
var BlogPostContent = $(".BlogPostContent")[0];
$(BlogPostTitle).html(arrayList[0]);
$(BlogPostDate).html(arrayList[1]);
$(BlogPostContent).html(arrayList[2]);
}
// , error: function (XMLHttpRequest, textStatus, errorThrown)
// {
// //There was an error
// alert('dfd');
// }
});
The only javascript error that I am receiving is that data is null, which I would expect as the response is blank.
It seems that the name of the web method that I am calling from my javascript is not even being read, because if I changed 'ChangePost' to 'ChangePost1' for example, it still returns a blank response, although I would expect an error message saying that the web method can't be found.
It seems that it does recognise that the BlogArchive.asmx web service exists because if I put something that would create an error in the VB code, the error appears as the response.
I am sure this must be something simple that I am doing wrong. Any help would be appreciated.

, data: '{FileName:"' + FileName + '"}'
Seems odd. You probably meant:
, data: {FileName: FileName}
(or 'FileName=' + FileName)
Furthermore, did you inspect the request (and response) via FireBug or similar?

You should try using jQuery getJSON with the minimal arguments.
Another thing, when you are using JSON with jQuery, if the answer data are not wellformed
(like a space before / after the starting JSON string) could lead to a blank answer from
jQuery.
Be sure using traditionnal AJAX with jQuery that your answered data are correct.

Related

jQuery Cross Domain Request to get JSON Response without Callback

I am trying to retrieve a JSON from this URL
http://www.iheartquotes.com/api/v1/random?format=json
via jQuery. I know the solution is JSONP, but since I have no control over the response text of the service or to wrap it in my own callback function, my aim is to somehow retrieve the response of the above URL using client-end scripts.
I have tried almost all the methods suggested from several answers from StackOverflow.
These are the code blocks I have tried and the response's I've got.
1 . A direct call which returned the expected Access-Control-Allow-Origin error
$.getJSON("http://www.iheartquotes.com/api/v1/random?format=json",
function(data) {
alert(data);
});
Response:
XMLHttpRequest cannot load
=1376682146029">http://www.iheartquotes.com/api/v1/random?format=json&=1376682146029.
Origin http://stackoverflow.com is not allowed by
Access-Control-Allow-Origin.
2 . The above code with the callback parameter added:
$.getJSON("http://www.iheartquotes.com/api/v1/random?format=json&callback=?",
function(data) {
alert(data);
});
Response:
Uncaught SyntaxError: Unexpected token :
Please note that when I click on the error, it takes me to the expected JSON response.
{"json_class":"Fortune","tags":["simpsons_homer"],"quote":"Holy Moly! The bastard's rich!\n\n\t\t-- Homer Simpson\n\t\t Oh Brother, Where Art Thou?","link":"http://iheartquotes.com/fortune/show/5501","source":"simpsons_homer"}
This is also expected as there is no callback function defined in the response.
3 . Through jQuery's Ajax method
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://www.iheartquotes.com/api/v1/random?format=json",
success: function(data){
alert(data);
},
});
Response:
Uncaught SyntaxError: Unexpected token :
Adding the callback parameter to the above function doesn't change the response.
Any help or pointers from the experts to retrieve the JSON from the URL? I am testing this from the Chrome Dev Tools. I know I could call the service from the server-end code and then send it across to the client-end. But I want to see if this can be done through jQuery alone from the client-end.
EDIT:
Based on Kevin B's comment:
Got the expected output via YQL using jQuery's Ajax. But my question remains the same. Is there a native way to do it via jQuery as YQL is still a dependency?
// Using YQL and JSONP
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql",
// the name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// tell jQuery we're expecting JSONP
dataType: "jsonp",
// tell YQL what we want and that we want JSON
data: {
q: "select * from json where url=\"http://www.iheartquotes.com/api/v1/random?format=json\"",
format: "json"
},
// work with the response
success: function( response ) {
console.log( response.query.results.json ); // server response
}
});
This gives the expected response.
This won't work in all browsers, but depending on which version of JQuery you're using try:
$.support.cors = true;
Obviously this also depends on the headers of the server response.

jQuery $.ajax failing silently, no error messages, and server responded with 200 OK

I am about to do my head in over this problem. I am using very simple jQuery ajax calls to get values from a database and populate a few select elements with the values, all returned as JSON. It works seamlessly for me on most browsers, however the client is reporting that neither them nor their clients are seeing the result.
I added some Console.log() commands along the way to make sure the code was executing, and it was. Sometimes the ajax GET to the URL in question works, other times is STILL returns 200 OK but the code simply does not execute further, and NO ajax error messages are shown in the error callback.
Here is the code I am using, can someone spot something obvious that may result in some browsers choking? If so, I'd be grateful if you could point it out:
var $j = jQuery.noConflict(true);
$j(document).ready(function(){
//console.log("jQuery has loaded");
//console.log("attempting to load country list via AJAX call now");
$j.ajax({
url: 'http://www.topplaces.co.za/templates/seb_one/positions/search_establishments_filter/search/db.php?q=countries&rand='+Math.random(),
success: function(data){
//console.log("Successfully got country list, going to populate the dropdown now");
if(data.length){
$j("#country").children("option:not(:first)").remove();
$j("#country").attr("disabled", false);
$j.each(data, function(resultIndex, result){
var o = new Option();
$j(o).html(result.country).val(result.country);
$j("#country").append(o);
})
//console.log("Country list should be populated now?");
}
},
error: function (xhr, ajaxOptions, thrownError){
//console.log(xhr.responseText);
console.log(thrownError);
},
dataType: 'json',
cache: false
})
$j("#country").live('change', function(){
var id = $j(this).val();
if(id == ""){
$j("#province").attr("disabled", "disabled");
$j("#town").attr("disabled", "disabled");
return false;
}
$j.ajax({
url: 'http://www.topplaces.co.za/templates/seb_one/positions/search_establishments_filter/search/db.php?q=provinces&c='+id+'&rand='+Math.random(),
success: function(data){
if(data.length){
$j("#province").children("option:not(:first)").remove();
$j("#province").attr("disabled", false);
$j.each(data, function(resultIndex, result){
var o = new Option();
$j(o).html(result.province).val(result.province);
$j("#province").append(o);
})
}
},
dataType: 'json',
cache: false
})
});
$j("#province").live('change', function(){
var id = $j(this).val();
if(id == ""){
$j("#town").attr("disabled", "disabled");
return false;
}
$j.ajax({
url: 'http://www.topplaces.co.za/templates/seb_one/positions/search_establishments_filter/search/db.php?q=towns&p='+id+'&rand='+Math.random(),
success: function(data){
if(data.length){
$j("#town").children("option:not(:first)").remove();
$j("#town").attr("disabled", false);
$j.each(data, function(resultIndex, result){
var o = new Option();
$j(o).html(result.town).val(result.town);
$j("#town").append(o);
})
}
},
dataType: 'json',
cache: false
})
});
})
I have commented out the Consol.log commands for the pure fact that the client was receiving error messages on IE as there is no console.
EDIT: I failed to mention that this a same domain request and therefore obeys the Same Origin Policy
The full site is here: http://www.topplaces.co.za/
On the right is a dynamic select group that starts with country and initiates AJAX calls until a Province is selected. The issue, a lot of people say that Country is no loading for them...
Kind regards,
Simon
Check if your server application always returns valid JSON object, otherwise it will not be accepted because you set dataType: 'json'. In this case, error function will be executed instead of success.
Remove dataType parameter and see what happens, try to parse incoming data with $.parseJSON() - it will throw an exception if you JSON is invalid.
I tried your site but no province is loading. The Json is empty. I tried accesing the php directly and it returns empty as well. Did you check your script?
URL Called
http://www.topplaces.co.za/templates/seb_one/positions/search_establishments_filter/search/db.php?q=provinces&c=Zambia&rand=0.12686952343210578&_=1335360594228
This are the params is see:
q:provinces
c:Zambia
rand:0.12686952343210578
_:1335360594228
Json Result:
[]
It's really random so I bet it's the php script not returning the json.
I also experienced this browser issue with json returned from an ajax call. The problem was that I had to look at different parts of the returned data in Firefox compared to IE. For Firefox, data.text was undefined so I had to use data.documentElement.firstChild to find the json:
var list = typeof data.text === 'undefined' ? jQuery.parseJSON(jQuery(data.documentElement.firstChild).text()) : jQuery.parseJSON(data.text);

why Ajax get Request failed

The response of my request is a java script code. When I put the url in browser, I can see the whole generated java script code on the page. Format of url passed to $.ajax is as below:
http://localhost:8080/vi-api/viapi?action=tag&projectId=45&tagId=345
When I put the above URL I can see the request is successful. Now, I am using below Ajax request for this url using jQuery.
var finalUrl = "http://localhost:8080/vi-api/viapi?action=tag&projectId=45&tagId=345";
var req = $.ajax({
type:"GET",
url:finalUrl,
type:"script",
data:"",
success: function(html){
alert('Requese sucessful.');
},
complete:function(jqXHR, textStatus) {
alert("request complete "+textStatus);
},
error: function(xhr, textStatus, errorThrown){
alert('request failed->'+textStatus);
}
});
Question 1:This gives the alert "request failed error'. Why this is so ?
Question 2:Is there any way to return success/failure code in above process?
In:
$.ajax({
type:"GET",
url:finalUrl,
type:"script",
(...)
You have two times the 'type' key in your object. So I think only the second one is taken ('script'). Obviously 'script' is not a valid HTTP method (as HEAD,GET,PUT,POST, etc). The keyword your were looking at for 'script' is maybe dataType which may be one of xml, json, jsonp, text, script, or html.
Do not forget to look at jsonp, it's usually a nice way to return a script content and to call it.
I am not sure why, but I can give your some tips how to debug or find out issues:
1) install fiddler to look at HTTP request.
2) type:"script", why the type is script? try to use "text/html".
3) use complete(jqXHR, textStatus) you can look at HTTP status. more info about $.ajax
var finalUrl=http://localhost:8080/vi-api/viapi?action=tag&projectId=45&tagId=345;
is pretty invalid javascript. You probably meant passing the url as a string:
var finalUrl = 'http://localhost:8080/vi-api/viapi?action=tag&projectId=45&tagId=345';

How to get controller/model/store/view in Ajax callback

folks,
I am working on a project using EXTJS MVC framework for backend development.
Now I am in trouble to get controller/model/store in the Ajax callback
Here is the snippet of my code. I am in the controller to call Ajax.
Ext.Ajax.request({
url: 'http://localhost:8080/gdltest/gdl_service.cgi',
jsonData: jRequest,
method: 'POST',
success: function (response,options) {
var jsonData = Ext.JSON.decode(response.responseText);
var jData = jsonData.results.data;
When i get the data from the response, I want to get the controller/model/store to do more actions, but i don't know how to get them :(
Thank you very much for your help :)
What you've done in the success function is correct. Please check the reponse that you're getting back from the server. Also, is the url correct? Usually the relative path to the resource is given, not the absolute path, as you've given here. Is the request reaching the server? If it is I think there is an issue with the data which is being sent back. You should also use the safe option during development. The safe option throws an error if the Json returned from the server isn't in the proper format. From the docs:
decode( String json, [Boolean safe] )
safe : Whether to return null or throw an exception if the JSON is
invalid.
EDIT: If you want to use the this operator inside the success callback then specify the scope config. Example below:
Ext.Ajax.request({
url: 'http://localhost:8080/gdltest/gdl_service.cgi',
jsonData: jRequest,
method: 'POST',
success: function (response,options) {
var jsonData = Ext.JSON.decode(response.responseText);
var jData = jsonData.results.data;
},
scope : this //this will be the object form which the Ajax.request is called, and not Ajax.request itself or you can specify any other object you desire.

Ajax(jQuery) strange file post problem

I have a problem posting file via ajax jQuery function. I have something like this:
$('#my_form').submit(function() {
var serialized = $(this).formSerialize();
var sUrl = "xxx";
$.ajax({
url: sUrl,
type: "POST",
data: serialized,
success: function(data) {
$(".main_container").html(data);
}
})
return false; // THIS return statment blocks sending file content
});
When I remove return false statement everything is okey, server side gets the file content and etc, but when it's there (i monitor with firebug) that this posting sends only file name. What can be wrong?
P.S. - I need this return false statement, because I want to manipulate return data myself.
First stop — the manual.
Data from file select elements is not serialized.
From http://api.jquery.com/serialize/
You can't read local files with JS, so you can't submit them using XMLHttpRequest.
jQuery - receiving the $_FILES array using $.post lists a number of alternative approaches.

Resources