Issue with jQuery ajax post - javascript

This is a followup to this question. Since the problem that I'm now facing is different from that, I thought I'll pose a new question.
I'm having an issue with the following code where in, the request is getting POSTed to the server, but whatever response the server has sent is not visible on the browser (in the form of an alert here).
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#login').delegate('input#submit','click',function(){
var request = $.ajax({
type: "POST",
url: "login",
data: {userid: $("#userid").val(), password:$("#password").val()},
datatype: "xml",
cache: false,
success: function(xml){alert(xml);}
});
});
});
</script>
I can see that this request is going to the server - can see it in the logs. But I don't see the server's response in the browser. Here's the server's response:
<result><url>landing-page</url></result>
Not sure what am I doing wrong, but this seems to be simple stuff that I should get it working without issue. Tried Firebug, but no luck. Any idea as to where am I going wrong here or on how to debug this issue further.
Thanks

Either change your "success" callback to a "complete" callback, or add a complete callback. My guess is that it isn't detecting a "success" even though the response is being successfully retrieved. If it fires the "complete" callback, then you can try and fix your webservice to provide a successful response.

Related

AJAX call error - status of 400 (Bad Request)

I'm trying to use the BloomAPI to retrieve Doctor's NPI number by querying with their first and last name. I'm using Jquery Ajax to make a get request for the JSON data.
I am able to get the JSON data when I do CURL in the terminal: curl -X GET 'http://www.bloomapi.com/api/search?offset=0&key1=last_name&op1=eq&value1=LIN&key2=first_name&op2=eq&value2=JOHN'
For the purpose below - I just hardcoded in the params into the URL.
I get a "Failed to load resource: the server responded with a status of 400 (Bad Request" Error. Any idea what I might be doing wrong?
$.ajax({
type: 'GET',
url: 'http://www.bloomapi.com/api/search?offset=0&key1=last_name&op1=eq&value1=LIN&key2=first_name&op2=eq&value2=JOHN',
dataType: 'jsonp'
}).done(function(server_data) {
console.log(server_data)
}).fail(console.log("failed"));
This was a weird one... your code is actually basically correct, however, it appears bloomapi does not support disabling caching in the way jquery does it.
When you make the jquery call you have, the actual url becomes something like this:
http://www.bloomapi.com/api/search?offset=0&key1=last_name&op1=eq&value1=LIN&key2=first_name&op2=eq&value2=JOHN&callback=jQuery111207365460020955652_1428455335256&_=1428455335257
The callback is a jsonp construct, and the _ is a way of breaking caching. However, bloomapi appears to not like this:
jQuery111207365460020955652_1428455335256({"name":"ParameterError","message":"_ are unknown parameters","parameters":{"_":"is an unknown parameter"}});
To get around this, you can disable cache busting like so:
$.ajax({
type: 'GET',
url: 'http://www.bloomapi.com/api/search?offset=0&key1=last_name&op1=eq&value1=LIN&key2=first_name&op2=eq&value2=JOHN',
dataType: 'jsonp',
cache: true
}).done(function(server_data) {
console.log(server_data)
}).fail(function() { console.log("failed") });
You will have to be careful of how else you break the cache if that's an issue; the api provider may be able to provide feedback on how to do this.
In the future, you can easily check the errors you are receiving/what you are sending using a web debugger; I used Fiddler to figure this out.

execute a PHP script from Ajax without expecting an answer (and no daemons)

I hope you can help me with this issue:
My sistem runs over Zend Framework, I have installed jQuery in it's latest version. I have an input that receives a file and it makes an Ajax call when changes, and I want that call made in the background, without expecting any response (because that script will send an email when finished). My ajax call is like this:
var formData = new FormData();
formData.append('file', $(this).get(0).files[0]);
$.ajax({
url: 'uploadaddresses.php',
type: 'POST',
data: formData,
dataType: 'json',
async:true,
processData: false,
contentType: false,
beforeSend: function(){
bootbox.alert("You've made your petition correctly. When finished, an email will be sent to you.")
},
error: function(err) {}
});
return false;
Although, the call waits for a response (even FireBug shows me that uploadaddresses.php is still executing...). What i'm doing wrong? How should I do it best? I want to avoid using daemons and system calls, because system restrictions...
Thank you very much in advance :)
If you're wanting uploadaddresses.php to return an HTTP response immediately but continue processing, take a look at pcntl_fork in PHP.
Here's the main doc page: http://php.net/manual/en/function.pcntl-fork.php
Here's a good example that you might want to follow: http://php.net/manual/en/function.pcntl-fork.php#94338
Create a success method for the ajax call and have something like this:
console.log("Done");
This way you know if is complete and successful but only if you are looking at the dev tools. Unless you specify output it should not continue to run after the call has been made. Maybe you have an error in your PHP code?
EDIT: If you can't get this resolved you may want to post your PHP page as well.

Ajax call keeps getting blocked by browser

I am a bit stuck with an issue.
I am developing a small mobile website. I am trying to call a webservice using an ajax call, but the browser keeps blocking my call. If I start up Chrome using the tags... "--allow-file-access-from-files --disable-web-security​​" Then the call works perfectly. I have no issues whatsoever.
Now my problem is if I host the website, the browser is going to block my ajax call and the user cannot for example login or retrieve information. I present my ajax call below...
$.ajax({
async: true,
beforeSend: function () {
},
complete: function () { },
type: 'POST',
url: 'https://MySecretUrl.com/login?format=json',
contentType: 'application/json',
dataType: 'json',
data: '{"UserId":"mySecretUserId","Password":"mysecretPassowrd"}',
success: function (resultMessage) {
if (resultMessage.WasSuccessful == true) {
alert('YAY');
} else {
alert('Semi Yay');
}
},
error: alert('OOOOPS')
});
Does anybody know a workaround for getting information from the webservice without any browser blocking the ajax call ?
Any suggestions would be greatly appreciated.
Thanks in advance for the help.
EDIT
Hi Guys, Ok so I did some more digging and discovered the following.
When the request is made with browser security, the call changes the POST to a OPTIONS. this is called a preflighted request. One workaround that I have found is if you are making a GET call, then you can use jsonp as your data type. But now my problem is that it is incompatible with POST. Is there any fix that does not require the webservice to be changed ?
Is there any fix that does not require the webservice to be changed ?
No. If changing the webservice isn't an option, your only option is to not use the browser to make this request.
You must either make the server return the data in a format that can be accepted cross-domain, or don't make cross-domain requests with the browser.

Page waits for AJAX before changing location

This question might seem a bit odd, the problem arised when the page went through webtests.
The page uses an AJAX call (async set to true) to gather some data. For some reason it won't swap pages before the AJAX call has returned - consider the following code:
console.log("firing ajax call");
$.ajax({
type: "POST",
url: "requestedService",
data: mode : "requestedMethod",
cache: false,
dataType: "json",
success: function() { console.log("ajax response received") },
error: null,
complete: null,
});
console.log("changing window location");
window.location = "http://www.google.com"
The location only changes after AJAX returns the response. I have tested the call, it is in fact asynchronous, the page isn't blocked. It should just load the new page even if the AJAX call hasn't completed, but doesn't. I can see the page is trying to load, but it only happens once I get the response. Any ideas?
The console output is:
firing ajax call
changing window location
ajax response received
This seems to work fine for me. The location is changed before the code in the async handler executes. Maybe you should post some real code and not a simplified version, so that we can help better.
Here is a demonstration that works as you expect: http://jsfiddle.net/BSg9P/
$(document).ready(function() {
var result;
$("#btn").on('click', function(sender, args) {
setInterval(function() {
result = "some result";
console.log("Just returned a result");
}, 5000);
window.location = "http://www.google.com";
});
});
And here is a screenshot of the result: http://screencast.com/t/VbxMCxxyIbB
I have clicked the button 2 times, and you can see in the JS console that the message about the location change is printed before the result each time. (The error is related to CORS, if it was the same domain, it would navigate).
Bit late but maybe someone else will have the same issue.
This answer by #todd-menier might help: https://stackoverflow.com/questions/941889#answer-970843
So the issue might be server-side. For eg, if you're using PHP sessions by default the user's session will be locked while the server is processing the ajax request, so the next request to the new page won't be able to be processed by the server until the ajax has completed and released the lock. You can release the lock early if your ajax processing code doesn't need it so the next page load can happen simultaneously.

JQuery AJAX JSONP Invalid Label

I know this question has been asked, but I cannot get it working.
I execute the following AJAX request:
function dislikeMeme(memeId) {
$.ajax({
dataType: "jsonp",
url: "http://<url>.com/dislike/" + memeId,
data: {
u: "username",
p: "password"
},
jsonpCallback: 'successCallback'
});
}
function successCallback(data) {
alert("Test"); // Not firing because of previous 'Invalid label' error
};
Looking at firebug I see that the request was successful, but there is an Invalid Label error which fires the Error callback of the request. The response of the request is as follows:
{
"id":6220673,
"myScore":-1,
"msg":"Not loved"
}
I see that the parentheses are causing JavaScript to interpret the response as an object, but I know this is the format I am retrieving, isn't there anyway to parse this before it causes an error?
I also see that the URL of the page returning this information is:
http://<url>.com/dislike/123456?callback=successCallback&u=username&p=password&_123456789
Everything is working perfectly except this Invalid label error. Does anyone have any ideas?
Thanks in advance everyone
A server that can handle JSONP takes the callback paramater (can be different parameter depending on WS) and passes it in the response. So the response from the server should be:
successCallback({
"id":6220673,
"myScore":-1,
"msg":"Not loved"
})
If you don't have control over the server your only route is proxy. See my cross domain answer for information on getting around same origin policy.
What prevents me from using $.ajax to load another domain's html?

Categories