I have a simple function that uses $.Ajax. It's working fine when I deploy the this page to my online website, but on my dev environment it doesn't work, but there is no error. I tried both $.Ajax and $.Post. both not working, but in the F12 profiler tool i see the traffic.
Any Idea?
Thanks.
<script >
function RunAjax()
{
alert("before post");
$.post("http://myshulmgr.com/GetData.asmx/GetEventMembers", { PID: "32", EventID: "8" },
function (data) {
alert("Data Loaded: " + data);
});
$.ajax({
type: "POST",
url: "http://myshulmgr.com/GetData.asmx/GetEventMembers",
//data: {PID: iPID, EventID: iEventID},
data: "{'PID': '" + 32
+ "','EventID': '" + 8 + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (jsonRes)
{
alert(jsonRes);
},
failure: function (msg)
{
alert(msg);
}
});
}
Look at your browser's error console. There should be an informative message there.
Your dev environment is probably not on the same domain as the endpoint you are calling, so the same-origin policy is preventing your script from retrieving results from it. Since this is supposed to be a dev environment, you should probably set up a copy of the GetData.asmx script in that environment, rather than calling the production endpoints, and reference it as /GetData.asmx (i.e, as a domain-relative path) in your script.
You cannot perform cross-domain request because of same origin policy.
In your console you can see that this is actually the source of your problem:
console says (Aborted), giving a CORS preflight initiatior, i.e you tried to perform an cross-domain request, but it was aborted due to security reasons.
The reason why it works on production and not on dev is because probably your production environment is in the same domain (myshulmgr.com) to which the request is addressed, while dev environment is not.
Related
I am sending username and password as request parameter to the server in AJAX and trying to show the response message. But not able to showing the response message.In fiddler it is showing the response message. But while on the browser screen it is not showing.PLEASE somebody help me out where i am wrong or need to change anything..
I have written like this-
$(document).ready(function () {
$("#btnCity").click(function () {
$.ajax({
type: "POST",
url: "http://test.xyz.com/login",
crossDomain: true,
contentType: "application/json; charset=utf-8",
data: { username: "abc", password: "1234" },
dataType: "JSONP",
jsonpCallback: 'jsonCallback',
async: false,
success: function (resdata) {
alert(resdata);
},
error: function (result, status, err) {
alert(result.responseText);
alert(status.responseText);
alert(err.Message);
}
});
});
});
TL;DR: I guess the problem is on the server side of your code (that we don't know yet).
At first: I don't know why it fails for you. I've taken your code and ran it against a public available JSONP API, that returns the current IP of your system and it worked.
Please try yourself using the URL: http://ip.jsontest.com/.
So most probably, the server doesn't return the right response to the JSONP request. Have a look at the network tab in developer tools. With your current code, the answer of the server should be something like:
jsonCallback({'someResponseKeys': 'someResponseValue'});
Note: The header should contain Content-Type:application/javascript!
BTW, even if this doesn't for now solve your problem - here are some tweaks, I'd like to advice to you:
Don't set async to false, at the documentation of jQuery.ajax() says:
Cross-domain requests and dataType: "jsonp" requests do not support synchronous
operation.
You don't need to set a jsonpCallback, because jQuery will generate and handle (using the success function a random one for you. Quote from the docs:
This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling.
So here comes my code:
$(document).ready(function () {
$("#btnCity").click(function () {
$.ajax({
type: "POST",
url: "http://ip.jsontest.com/",
crossDomain: true,
data: { username: "abc", password: "1234" },
dataType: "JSONP",
success: function (resdata) {
console.log("success", resdata);
},
error: function (result, status, err) {
console.log("error", result.responseText);
console.log("error", status.responseText);
console.log("error", err.Message);
}
});
});
});
A working example can be found here.
Another solution, like Yonatan Ayalon suggested, can be done with a predefined function and then setting the jsonpCallback explicitly to the function that should be called.
if you see the response in Fiddler, it seems that the issue is in the callback function.
you are doing a jsonP call - which means that you need a callback function to "read" the response data.
Do you have a local function that calls "jsonCallback"?
this is a simple jsonP request, which initiates the function "gotBack()" with the response data:
function gotBack(data) {
console.log(data);
}
$.ajax({
url: 'http://test.xyz.com/login' + '?callback=?',
type: "POST",
data: formData,
dataType: "jsonp",
jsonpCallback: "gotBack"
});
You can try with the following methods and close every instance of chrome browser in task manager, then open browser in web security disable mode by the command "chrome.exe --disable-web-security"
success: function (resdata) {
alert(resdata);
alert(JSON.stringify(resdata));
},
And the better option to debug the code using "debugger;"
success: function (resdata) {
debugger;
alert(resdata);
alert(JSON.stringify(resdata));
},
I am developing an app in phonegap 3.1.0-0.15.0 and I am having problems with an ajax call to a remote server.
I have done all the default stuff, like added Internet acces, with-listed the domain, but the ajax still get's the 404 header.
My ajax call:
$.ajax({
url: 'http://my-host/bus/app-ajax',
type: 'GET',
dataType: "json",
data: 'type=data_out',
cache: false,
crossDomain: true,
processData: false,
contentType: false,
success: function(ret_data) {
alert(ret_data);
},
error: function(xhr, textStatus, errorThrown) {
alert("Ajax error(ajax_helper.get_categorys) xhr.status: " + xhr.status);
}
});
My code has an IP address in the "url" variable of the ajax call, I just changed it here for security reasons.
If I copy the content of my www folder to a website that is on the same host as my PHP respond script(browsers don't allow cross domain ajax calls) than it works. On the device that I am testing if I open a browser I can access the domain, and get the json response, but the app just gives me 404 all the time.
Any ideas on what I can still try to make this work?
I recreated the project with the verbose "phonegap create" command, added the same code, and it works. Was probably some problems with the old project, because I updated phonegap in it a few times.
cross domain request issue
my ajax call code actually when i am running given url directly in browser it shows me json data but using ajax call it always shows me ajax error believe me i tried n follow many things no fruitful result from 18 days.
$.ajax({
crossDomain:true,
type: "GET",
url: 'http://taxihub.azurewebsites.net/Mobile/api/json.php?method=getCompanyList',
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: false,
success: function (data) {
console.log(data);
return;
},
error: function (err) {
console.log("AJAX ERROR");
console.log(err.responseText);
}
});
you can also check this link directly u will see json data coming but i found error i dont know why
"http://taxihub.azurewebsites.net/Mobile/api/json.php?method=getCompanyList"
error: OPTIONS http://taxihub.azurewebsites.net/Mobile/api/json.php?method=getCompanyList Origin lhost:809 is not allowed by Access-Control-Allow-Origin.
please help me i am stuck here from 18 days on this issue
Remove the cross-domain and content-type part and it'll work but you'll have to do a little extra string manipulation work to put it in JSON object:
$.ajax({
type: "GET",
url: 'http://taxihub.azurewebsites.net/Mobile/api/json.php?method=getCompanyList',
dataType: "json",
success: function (data) {
console.log(data.result.getCompanyList[0].CompanyID);
return;
},
error: function (err) {
console.log("AJAX ERROR");
console.log(err);
}
});
}
Actually it seems cross-domain doesn't have any effect with or without it. I guess the server you're targeting doesn't have strict cross-domain prevention but doesn't like the JSON content-type. I'd be glad to get a more specific explanation.
EDIT I used JQuery 1.10.2 if it matters
So... i'm making a cross domain (CORS) call. When i initially make it on the page, it works just fine (noting that cross-domain issues aren't really a problem), but when i make another request later to the same server adding a bearer authorization token to the header, it is failing with a 401 Unauthorized.
Also, when i run this code from the same domain, both calls run successfully (identifying that the token is ok...)
Thoughts?
$.ajax({
url: apiPath.userMetaUrl(),
xhrFields: {
withCredentials: true
},
cache: false,
error: function (xhr, ajaxOptions, thrownError) {
console.log("url: " + apiPath.userMetaUrl());
console.log("fn loadUserMetaData xhr.status: " + xhr.status);
console.log("fn loadUserMetaData xhr.responseText: " + xhr.responseText);
console.log("fn loadUserMetaData thrownError: " + thrownError);
},
dataType: "json",
jsonpCallback: "callback",
beforeSend : setHeader,
success: function (data) {
//woohoo!
}
}
function setHeader(xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + authenticatedInfo.access_token);
}
Again, running this code from same domain as apiPath.userMetaURL() works fine. On a different domain, the initial call without adding request header works fine. Access-Control-Allow-Orign has the cross-domain URL added. Access-Control-Allow-Headers has Authorization added.
xhr.status returns 0 and responseText/thrownError are blank.
JSONP != ajax
These requests you are making are simply adding <script> tags to your DOM. It's just wrapped in an ajax syntax for ease of use. You can't modify the request headers in this fashion. You need to create a CORS ajax request, and configure your server to handle them.
Executing jsonp requests on the same domain though... I believe jQuery just uses an xmlHttpRequest though. For cross-domain, it uses <script> tags. This would explain the behavior you are seeing.
Consider the following.
$.ajax({
url: 'http://google.com',
dataType: 'jsonp',
beforeSend: function(xhr) { xhr.setRequestHeader('foo', 'bar'); }
});
Look at your network traffic. It will create the request, but you will not see the foo header.
I would like to call OData .NET web service that authenticates users via basic authentication.
I use following ajax call:
var fullUri = APIUri + "?$format=json";
$.ajax({
url: fullUri,
contentType: "application/json",
dataType: "jsonp",
type: 'GET',
jsonp: '$callback',
beforeSend: function setHeader(xhr) {
xhr.setRequestHeader('Authorization', token);
},
success: callback,
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
},
});
The results are unusable for me:
Calls are blocked because of CORS (until I will paste API url and try to load it in chrome). I tried local html file and html file uploaded to the same domain/port, but authentication fails (according to Chrome console).
Once I enter service URL into chrome address bar, I am asked to provide login name and password by Chrome. If I enter them, they are cached and used even I assign them in beforeSend. How to blocks this behavior?
I've tried a lot of examples how to configure jsonp, headers etc, but did not find working solution yet.
IIS server response header is also configured using "Access-Control-Allow-Origin" value="*".
You can set the HTTP Password and Username in the AJAX Call directly:
$.ajax({
url: fullUri,
contentType: "application/json",
username: <login>,
password: <password>,
...
Use the following to support CORS:
jQuery.support.cors = true;
Regarding the call, are you using HTTPS? Is the certificate valid?