how can I cancel an Ajax request? [duplicate] - javascript

This question already has answers here:
Abort Ajax requests using jQuery
(18 answers)
How to cancel/abort jQuery AJAX request?
(8 answers)
Closed 8 years ago.
In phonegap how to cancel an ajax request in program, I would like to set cancel button for control the request when it's too slow
$.ajax({
type: "GET",
url: url,
success: function(m) {
alert( "success");
}
});

hi it's similar as Abort Ajax requests using jQuery,anyway This can help you
var ab = $.ajax({ type: "GET", url: url, success: function(m) { alert( "success"); } });
//kill the request
ab.abort()

Store the promise interface returned from ajax request in a global variable and abort it on cancel click
var result = $.ajax({ type: "GET", url: url, success: function(m) { alert( "success"); } });
$('#cancel').click(function() {
result.abort();
});

var request= $.ajax({ type: "GET", url: url, success: function(m) { alert( "success"); } });
$('#cancel').click(function() {
request.abort();
});
this will abort the request from the client(browser) side but note : if the server has already received the request, it may continue processing the request (depending on the platform of the server) even though the browser is no longer listening for a response. There is no reliable way to make the web server stop processing a request that is in progress.

Related

is that possible to make ajax call to external web page?

is it possible to call a page of another website from an ajax call ?
my guess is that is possible since connection is not denied , but i can't figure out how to make my ajax call works , I am calling a list of TV Channels of a website , but I am getting no results , would you please see if my script contains any errors
function showValues(){
var myUrl="http://www.nilesat.com.eg/en/Home/ChannelList";
var all = 1;
$.ajax({
url: myUrl+"&callback=?",
data: "channelType="+all,
type: 'POST',
success: function(data) {
$('#showdata').html(data);
},
error: function(e) {
alert('Error: '+data);
}
});
}
showValues();
html div for results
<div id="showdata" name ="showdata">
</div>
Ajax calls are not valid across different domains.you can use JSONP. JQuery-ajax-cross-domain is a similar question that may give you some insight. Also, you need to ensure thatJSONP has to also be implemented in the domain that you are getting the data from.
Here is an example for jquery ajax(), but you may want to look into $.getJSON():
$.ajax({
url: 'http://yourUrl?callback=?',
dataType: 'jsonp',
success: processJSON
});
Another option is CORS (Cross Origin Resource Sharing), however, this requires that the other server to enable CORS which most likely will not happen in this case.
You can try this :
function showValues(){
var myUrl="http://www.nilesat.com.eg/en/Home/ChannelList";
var all = 1;
$.ajax({
url: myUrl,
data: channelType="+all,
type: 'POST',
success: function (data) {
//do something
},
error: function(e) {
alert('Error: '+e);
}
});
}

jquery ajax post sends me to action page and wont show result data

I have the following script for making Ajax/Jquery post request.
The script works (I get correct response on back-end).
But I cant seem to make any alerts, so I think there is some problem with the success function.
Do you guys see any obvious mistakes?
The browser gets the correct responses (Inspect webpage in chrome).
<script>
$(document).ready(function() {
var frm = $('#registerform');
frm.submit(function(x) {
x.preventDefault();
$.ajax({
type: 'POST',
url: 'http://localhost:8080/api/v1/register',
data: frm.serialize(),
crossDomain: true,
success: function(data){
if(data == 200){
alert("successfully registered");
$('#alert').append("successfully registered");
}
if (data == 400){
alert("email or password empty");
}
if(data == 403){
alert("passwords do not match");
}
}
});
});
});
</script>
You are trying to compare your data that you are getting back from your request with HTTP status codes. So, what you need do is put in some additional parameters in your success function. Here is a nice Fiddle that I seen on another stackoverflow question that might help you out. http://jsfiddle.net/magicaj/55HQq/3/.
$.ajax({
url: "/echo/xml/",
type: "POST",
data: {
//Set an empty response to see the error
xml: "<response></response>"
},
dataType:"text xml",
success: function(xml, textStatus, xhr) {
console.log(arguments);
console.log(xhr.status);
}
});
The xhr.status is what you will need to compare against instead of your data.
When playing with console.log i found out that sending res.sendStatus(200) from the backend results in the client (browser) getting the response "OK". So when changing to res.json on the server it works...

How to connect to the Parse Javascript API? (502 error)

I am building a chatroom-type app using the Parse Javascript API. The task is to get some data from Parse, display it, add user input to the messages, and send it right back to parse.
The problem is I am not being able to see the data from parse, and receive a 502 error. I am a bit newer to javascript, so any advice on how to accomplish this, or any mistakes you may see in my code, would be fantastic. I also commented out my code the best I could. Thanks for the help.
Here is my code;
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages')
//fetches data from parse
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success: console.log("Success"),
function message(a) {
my_messages.append('<ul>' + a +'</ul>'); //adds ul 'text' to messages
};
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
function(message){
window.location.reload(1) //refresh every 3 seconds
});
});
});
</script>
you have syntax error in both of your success functions of $.ajax calls. In the first ajax call you have places console.log, which should be inside the success callback. In the second one u haven't even added success: callback.
Try below updated code
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages');
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success:function message(a) {
console.log("Success")
$.each(a,function(i,item){
my_messages.append('<ul>' + item.username +'</ul>'); //adds ul 'text' to messages
});
}
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
success:function(message){
window.location.reload(1) //refresh every 3 seconds
}
});
});
});

jQuery AJAX sending two requests [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
jQuery AJAX seems to be sending two requests. As I'm using a two-factor authentication method, based on time, the second request is failing hence the original request is "failing".
The first is a post request, that's fine, but then there's a GET request, which isn't fine.
Here's the javascript I'm using to generate the query.
$('#form').live('submit', function(event) {
var target = $('#ajax');
var url = '/ajax/user/authenticateLevel3';
$.ajax({
type: "POST",
url: url,
data: $('#form').serialize(),
dataType: 'json',
success: function(data, status) {
$.getJSON(url, function(data) {
if (!data.resultCode) {
$('#ajax').html($.base64.decode(data.html));
$('#ajax').modal();
} else {
location.reload();
}
});
}
});
event.preventDefault();
});
Any ideas how I can work around this?
That is because you are doing 2 ajax calls (.ajax and .getJSON)
Try doing this instead (using document event delegation instead of .live):
$(document).on('submit', '#form', function(event) {
var target = $('#ajax');
var url = '/ajax/user/authenticateLevel3';
$.ajax({
type: "POST",
url: url,
data: $('#form').serialize(),
dataType: 'json',
success: function(data, status) {
if (!data.resultCode) {
$('#ajax').html($.base64.decode(data.html));
$('#ajax').modal();
} else {
location.reload();
}
}
});
event.preventDefault();
});
You are sending 2 requests. One with .ajax and another with .getJson.
Remove the .getJson request. With no dataType property passed to .ajax, jquery will attempt to guess the response type. You may also specify the dataType as json to force the conversion. The 'data' parameter of the success callback should be converted to a javascript object for both of these options.
getJSON is an AJAX method for retrieving JSON from a server, not for processing the data returned by another ajax method. Just remove it.
$('#form').live('submit', function(event) {
var target = $('#ajax');
var url = '/ajax/user/authenticateLevel3';
$.ajax({
type: "POST",
url: url,
data: $('#form').serialize(),
dataType: 'json',
success: function(data, status) {
if (!data.resultCode) {
$('#ajax').html($.base64.decode(data.html));
$('#ajax').modal();
} else {
location.reload();
}
}
});
event.preventDefault();
});
Since you mentioned you are switching over to .on, the syntax will be like this:
$(parent).on('submit', '#form', function(event) {
/*
* ...
*/
});
where parent is the nearest static parent element of #form.

Why can't I use jQuery to fire an AJAX request from an unload event handler?

I have the following code, intended to log the event when a user closes a chat window:
$(window).unload( function() {
test();
});
function test()
{
alert("Hi");
$.ajax({
type: "POST",
url: baseUrl + 'Index/test',
data: "user_id=" + "Nisanth" + "& chat_id=" + 2,
success: function(msg){
alert(msg);
}
});
alert('Success');
}
Both the "Hi" and "Success" messages alert fine but the alert in the AJAX callback doesn't... The operation I intend to trigger via the AJAX request is also not happening (I'm developing a chat application, and intend to log an entry in the database when the user closes the window).
Because the ajax is asynchronous, the page is unloading before the response is properly sent, effectively terminating the connection. Try setting async:false;, although this will delay unloading the page until after the response is received, which isn't great for user experience if your server is running slow.
$(window).unload( function () {
test();
});
function test()
{
alert("Hi");
$.ajax({
async: false,
type: "POST",
url: baseUrl + 'Index/test',
data: "user_id=" + "Nisanth" + "& chat_id=" + 2,
success: function(msg){
alert(msg);
}
});
alert('Success');
}
the problem is the format of your data. It is converted to a query string, it must be Key/Value pairs something like:
"user_id:value"

Categories