I'm trying to read a html file using jQuery.get() without success.
I've put a breakpoint on 'var x = 1' but the execution does not reach that point.
The javascript function is:
function do_about()
{
$.get('mytest/index.html', function(data) {
var x = 1;
}).error(function() { alert("error"); });
};
The alert("error") is raised, however (as I am "dummy" in javascript) I don't know how to catch the error message correctly. The jQuery.get() documentation says:
If a request with jQuery.get() returns an error code, it will fail silently unless the script has also called the global .ajaxError() method or. As of jQuery 1.5, the .error() method of the jqXHR object returned by jQuery.get() is also available for error handling.
There is no remote web server, it is local.My Apache (on Ubuntu 11.04) is running and the file /etc/apache2/sites-available/default there is the following entry for the desired file:
Alias /mytest /home/miro/mytest
<Directory "/home/miro/mytest">
AllowOverride All
Allow from all
</Directory>
In Firefox if I call the url http://localhost/mytest/index.html the page will be displayed without problem.
The mytest/index.html is:
<html><body><h1>Test page</h1></body></html>
I tried $.get('http://localhost/mytest/index.html', function(data) {....
and it did not work.
Does anyone have any idea how to solve this?
Is there any other way to read a html using just javascript (no jQuery)? I just want to get some tag values from that html ?
Looks like it could be a path issue try setting your path relative to the domain root like so:
$.get('/mytest/index.html', function(data) {
var x = 1;
});
Can you console log the errors you receive? so we know if its a server issue or some redirects.
error(jqXHR, textStatus, errorThrown)
http://api.jquery.com/jQuery.ajax/
Related
After refering this stack link Ajax response not calling success:function() when using jQuery 1.8.3 am wondering why if I uncomment the datatype line the success function is not invoked.I can understand that dataType =JSON is not calling success function.Could some one help me out ?
function doAjaxCall(methodType,Url,params,requestType,callBackFunction)
{
if(validate.variable(Url) && validate.variable(params))
{
$.ajax({
type : methodType,
url : Url,
// dataType : 'JSON', //if i uncomment i am not getting the response under success
data : params,
success : function(data)
{
console.log(data);
callBackFunction(data);
}
});
}
}
function callBackFunctiontest(data)
{
console.log('callBackFunctiontest : ' +data);
}
doAjaxCall('GET','/getData?accountNumber=9840100672&oid=d11c9f66-4c55-4855-a99e-580ba8ef8d61','noparams','application/JSON',callBackFunctiontest);
If it's not passing in success function, put an error function. This way you'll be able to see the error and understand what's going on.
You can also open the developer console and have a look at the 'network' panel.
Assuming you're calling callBackFunctiontest which should then be calling doAjaxCall.
You're trying to use data when there is no variable named data in scope. It will throw an undefined exception and doAjaxCall will not get executed. So your AJAX request will never get sent.
Try getting rid of the console.log('callBackFunctionTest : ' +data);, or pass it a value for data.
I am using Express JS web framework and NodeJS, both latest versions - 4.x.x.
Issue #1 - Not all of my POST ajax calls were being sent to my NodeJS server code.
How I found this is by trying to POST using Postman. All POSTMAN call requests were received by the server code but not the Express client requests. I checked by printing the console.log server debug statements to compare the findings between POSTMAN & Express Client.
Issue #2 - I was never receiving any response message from the server even though the server responded with a status 200 OK.
For both the issues, I made a few changes, which I believe will help others.
In the ajax call, I added e.preventDefault(); where 'e' is the event which is triggered via #click/#onclick.
Within ajax function call, I added the parameter dataType: 'json'.
In the NodeJS server code, index.js, I replaced res.send(req.body.search_data); with res.json(req.body.search_data);
P.S. - e.preventDefault() was actually built for a different purpose but it helped because it prevents a link from following the URL which is what solved the above issues.
I am experimenting with a cross-domain call from Javascript, using the DOJO library. The web service I am calling returns JSON.
I am using "dojo.io.script.get" for this purpose.
The web service does not establish any particular query string parameter for the callbackParamName so I'm using ar arbitrary name such as "callback".
DOJO will inject back the SCRIPT tag with the result as seen below (extracted from Firebug):
<script id="dojo_request_script0" type="text/javascript" src="http://localhost:8281/services/TestGeocodeWorldLocator.TestGeocodeWorldLocatorHttpSoap12Endpoint?format=json&callback=dojo.io.script.jsonp_dojoIoScript1._jsonpCallback" async="" charset="utf-8">
{"GeocodeAddressResponse":{"Result":{"PropertyArray":{"PropertySetProperty":[{"Key":"Shape","Value":{"X":"-8841758.9684124179","Y":"5474103.2948672064","SpatialReference":{"WKT":"PROJCS[\"WGS_1984_Web_Mercator_Auxiliary_Sphere\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Mercator_Auxiliary_Sphere\"],PARAMETER[\"False_Easting\",0.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",0.0],PARAMETER[\"Standard_Parallel_1\",0.0],PARAMETER[\"Auxiliary_Sphere_Type\",0.0],UNIT[\"Meter\",1.0],AUTHORITY[\"EPSG\",3857]]","XOrigin":"-20037700","YOrigin":"-30241100","XYScale":"10000","ZOrigin":"-100000","ZScale":"10000","MOrigin":"-100000","MScale":"10000","XYTolerance":"0.001","ZTolerance":"0.001","MTolerance":"0.001","HighPrecision":"true","WKID":"3857"}}},{"Key":"Status","Value":"M"},{"Key":"Score","Value":"100"},{"Key":"Match_addr","Value":"1145 Nicholson Rd, Newmarket, ON, L3y"},{"Key":"PreType","Value":""},{"Key":"City","Value":"NEWMARKET"},{"Key":"Addr_type","Value":"StreetAddress"},{"Key":"X","Value":"-79.426873000000001"},{"Key":"Y","Value":"44.055940999999997"},{"Key":"Side","Value":"R"},{"Key":"House","Value":"1145"},{"Key":"PreDir","Value":""},{"Key":"StreetName","Value":"NICHOLSON"},{"Key":"SufType","Value":"RD"},{"Key":"SufDir","Value":""},{"Key":"Province","Value":"ON"},{"Key":"Postal","Value":"L3Y"},{"Key":"Disp_Lon","Value":""},{"Key":"Disp_Lat","Value":""},{"Key":"Loc_name","Value":"CAN_Streets"}]}}}}
</script>
The problem is that the browser (IE or Firefox) complains about 'Syntax Error - Expected ";"'. Basically it does not like the colons ":" in the JSON response injected in the SCRIPT tag.
Codewise, Javascript crashes at this line:
load: function(response, ioArgs)
I am thinking it may have something to do with the callbackParamName...but the server does not require any specific name.
Can someone please suggest how can I solve this problem?
This is the code I am using:
<head>
<script type="text/javascript" src='dojo-release-1.8.0-src/dojo/dojo.js' data-dojo-config='parseOnLoad: true, isDebug:true'></script>
<script type="text/javascript">
dojo.require("dojo.io.script");
function DOJOtoWS() {
var targetNode = dojo.byId("results");
var jsonpArgs = {
url: "http://localhost:8281/services/TestGeocodeWorldLocator.TestGeocodeWorldLocatorHttpEndpoint",
callbackParamName: "callback",
content: {format : "json"},
load: function(response, ioArgs){
console.log(response);
return response;
// Set the data from the search into the viewbox in nicely formatted JSON
targetNode.innerHTML = "<pre>" + dojo.fromJson(response) + "</pre>";
},
error: function(response, ioArgs){
targetNode.innerHTML = "An unexpected error occurred: " + response;
console.log("error");
console.log(response);
return response;
}
};
dojo.io.script.get(jsonpArgs);
}
dojo.ready(DOJOtoWS);
What you are describing sounds like JSONP. Thus the server needs to send data in JSONP format, not JSON.
There is a syntax error in the script injected by Dojo because dojo.script.io is expecting the server to return results in this format:
callback({"GeocodeAddressResponse": "blah blah blah"});
Explanation: Internally Dojo constructs a function named "callback" so it can execute the JSONP sent from the server. This function processes the data and sends it to your load function. Verify by trying a server that sends data back in JSONP format like this example does (http://ajax.googleapis.com/ajax/services/search/web).
Workarounds:
If you can't control the format returned by the cross-domain server, you will have to either set up a cross-domain proxy on the same-origin server or configure your browser to allow cross-domain AJAX calls.
You may also want to investigate Cross-Origin Resource Sharing (CORS) which is a new, safer standard meant to replace JSONP.
I'm using jQuery.getJSON() on a URL (different domain) which may not exist. Is there a way for me to catch the error "Failed to load resource"? It seems that try/catch doesn't work because of the asynchronous nature of this call.
I can't use jQuery.ajax()'s "error:" either. From the documetation:
Note: This handler is not called for cross-domain script and JSONP requests.
If you have an idea of the worst case delay of a successful result returning from the remote service, you can use a timeout mechanism to determine if there was an error or not.
var cbSuccess = false;
$.ajax({
url: 'http://example.com/.../service.php?callback=?',
type: 'get',
dataType: 'json',
success: function(data) {
cbSuccess = true;
}
});
setTimeout(function(){
if(!cbSuccess) { alert("failed"); }
}, 2000); // assuming 2sec is the max wait time for results
This works:
j.ajaxSetup({
"error":function(xhr, ajaxOptions, thrownError) {
console.log(thrownError);
}});
Deferred objects (new in jQuery 1.5) sound like exactly what you're looking for:
jQuery.Deferred, introduced in version 1.5, is a chainable utility object that can register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.
http://api.jquery.com/category/deferred-object/
EDIT:
The following code works fine for me:
function jsonError(){
$("#test").text("error");
}
$.getJSON("json.php",function(data){
$("#test").text(data.a);
}).fail(jsonError);
json.php looks like this:
print '{"a":"1"}';
The error function fires for me if the path to json.php is incorrect or if the JSON is malformed. For example:
print '{xxx"a":"1"}';
What your complaining about is a client-side error saying that you tried to download a resource from the server.
This is build into the browser and it allows your browser to tell the client or the developers that the downloading of a resource from the internet failed. This has nothing to do with JavaScript and is a more low level error thrown on the HTTP that is caught by the browser.
If you want any hope of catching it your going to need to drop 3rd party ajax libraries and deal with the XMLHTTPRequest object on a much lower level, even then I doubt you can do anything about it.
Basically when you see this error then find out what object your trying to get that doesn't exist or couldn't be accessed. Then either stop accessing it or make it accessible.
I'm trying to grab a songkick json feed using the below:
var jsonpArgs = {
url: obj.url,
load: function(data) {
console.log(dojo.fromJson(data));
},
error: function(error) {
new ErrorDialog({ title: 'Error', content: error });
}
};
dojo.io.script.get(jsonpArgs);
It loads the data fine, but it returns:
Resource interpreted as script but
transferred with MIME type
application/json. Uncaught
SyntaxError: Unexpected token :
This unexpected token coming from the contents of the file (line 1):
{ "resultsPage":
I'm guessing it's because the content coming back isn't be interpreted as json properly but I don't know what I'm doing wrong. I have tried specifying the callback parameter but it does nothing (not jsonp?).
Any ideas?
It looks like the feed does not support JSONP responses. Looking at their modest documentation I don't see how to specify a callback (the crucial part of JSONP). So obviously you are getting an error — JSONP uses <script> to retrieve the data, yet the data is of wrong type.
Another thing is you have to specify jsonp parameter, which is callback parameter. But it looks like a moot point, because I don't see your feed service supporting it.
So you best bet is to do a server-side call to this service using a proxy or something similar. This way you avoid cross-platform problems and can deal with JSON or XML directly.
The following javascript code gives me ">success-<", i.e. empty data. Pasting the url in my browser gives me the expected content.
$.get("http://company.tld/wiki/api.php?action=query&titles=Page%20Title&format=xml&prop=revisions&rvprop=content", function (data, status) {
alert(">" + status + "-" + data + "<");
});
It's a MediaWiki wiki. Here's the MediaWiki API specification: http://www.mediawiki.org/wiki/API:Query
Why am I not getting any data?
You might breach the ajax cross domain policy there.
Is that domain you try to access yours? better said, the one from your script?
From my experience, if you try to access data from a foreign domain, the success handler will fire regardless. But as you describe, with no data at all.
If data is an object you will receive the close results. Try use typeof data in the alert.
UPDATED:
To jAndy: In the documentation of jQuery.ajax we can read following (see http://docs.jquery.com/Ajax_Events):
success (Local Event).
This event is only called if the request was successful (no errors from the server, no errors with the data).
I just tried execute the following code
try {
$.ajax({url:"http://en.wikipedia.org/w/api.php?action=query&titles=jQuery&format=xml&prop=revisions&rvprop=content",
success: function (data, status, x) {
alert ("ok");
},
error: function (data, status, x) {
alert ("not ok");
},
dataType:"xml"});
} catch (e) {
alert ("exception");
};
where I try to use a crossdomain call. In IE I can see "exception" alert. In Chrome and Firefox: "not ok". The function success will NOT be called in case of error.
So the data from server are really an empty string ("") for the url of Tobbe.
To Tobbe: you should add the last parameter "xml" probably.