Jquery ajax not execute success - javascript

Am sending requesty by ajax to insert data in database. After success submiting my button message was not changed. On press i fire message Please wait... when success is fired set new html value Done. Records in db is success created but button text to Done was not changed.
My script:
var Friend = {
// Add new friend
add: function() {
var btn = $(".btn-add-friend");
btn.click(function() {
$(this).html("Please wait...");
$.ajax({
type: "post",
url: baseurl + "/FriendRequest/send",
data: {
friend: $(this).data('friend')
},
success: function(xhr, status) {
$(this).html("Done"); // Not wortk
alert("done"); // <-- Work
},
error: function(response, s, e) {
alert(response.responseText);
},
complete: function () {
//. the some from success
}
});
});
},
// Initialise
init: function() {
Friend.add();
}
};
Html:
<button type="button" id="item-<?=$person->account_id;?>" class="btn btn-xs btn-add-friend has-spinner" data-friend="<?= $person->account_id;?>"><i class="fa fa-plus-circle"></i> Add Friend</button>
When i click on button text was changet to Please wait.. but after success not changed to Done and alert is successful executed.
looks like it is not part of DOM after click! ALso i try with on() the some result i get.

this inside the ajax function callbacks is .... the ajax call, not the clicked element.
You have to replace it with it
add: function() {
var btn = $(".btn-add-friend");
btn.click(function() {
var self = $(this);
self.html("Please wait...");
$.ajax({
type: "post",
url: baseurl + "/FriendRequest/send",
data: {
friend: self.data('friend')
},
success: function(xhr, status) {
self.html("Done");
},

To use this, you need additional attribute. Add the following with url
context:this
So, the updated code will be
$.ajax({
type: "post",
url: baseurl + "/FriendRequest/send",
context:this,
data: {
friend: $(this).data('friend')
},
success: function(xhr, status) {
$(this).html("Done"); // Will work
alert("done"); // <-- Work
},
error: function(response, s, e) {
alert(response.responseText);
},
complete: function () {
//. the some from success
}
});

Inside the callback, this refers to the jqXHR object of the Ajax call, not the element. so try to assign it to a variable before ajax request, then use this variale inside success function:
//Before ajax request
var _this = $(this);
//Inside success function
_this.html("Done");
Hope this helps.

Related

abort or readyState is undefined with Ajax

i got that error with bellow code;
Uncaught TypeError: Cannot read property 'readyState' of undefined
And when i try delete the readyState for see the whats happend that i got that error;
TypeError: Cannot read property 'abort' of undefined
get: function () {
var ajaxReq = $.ajax({
type: 'GET',
url: data.url,
dataType: "json",
success: function (response, status) {
callback(response);
},
beforeSend: function () {
if (ajaxReq != 'ToCancelPrevReq' && ajaxReq.readyState < 4) {
ajaxReq.abort();
}
}
});
}
That function working with keypress;
keypress: function () {
setTimeout(function () {
if ($(OnePageCheckout.Selector.CardNumber).val().length == 7) {
$(".payment-installment-container").removeClass("d-none");
InvUtility.Loader.Open();
var model = {
value: $(OnePageCheckout.Selector.CardNumber).val()
}
OnePageCheckout.OnCardNumberUpdate.event(model);
}
}, 1000)
OnePageCheckout.OnCardNumberUpdate.init();
},
The keypress is send request so many times and i want to sure that the sucsess process working just one time
You should declare ajaxReq before you call $.ajax(). Then just check if it's not empty before trying to use it, rather than using a special value like ToCancelPrevReq.
And once you get a successful response, you can reset it so the next keypress can make the AJAX request again.
var ajaxReq;
...
if (ajaxReq && ajaxReq.readyState < 4) {
ajaxReq.abort();
}
$.ajax({
type: 'GET',
url: data.url,
dataType: "json",
success: function(response, status) {
ajaxReq = null;
callback(response);
}
});
this code solved my problem
I defined the variable outside of the get function. If I define it inside the GET function, it is taken as a new transaction because it is emptied every time. So defining it outside of the relevant function gave the correct result
var jqxhr = {abort: function () {}};
get: function(){
jqxhr.abort();
var ajaxReq = $.ajax({
type: 'GET',
url: data.url,
dataType: "json",
success: function (response, status) {
callback(response);
}
});
}

jQuery AJAX function on success not working

Having an issue. I have two different buttons included with each image displayed. One is remove, the other is assign as "main".
Remove works. It hides the image, deletes the file, and the MySQL row.
Assign Main sort of works. It updates the row in the database changing "main" value to 1, as it should, however, it should also alert(), but it does not.
<script>
$(document).ready(function() {
$(".remove_image").click(function() {
var image_id = $(this).attr('id');
$.ajax({
type:"post",
url:"imagecontrol.php",
data: { image_id:image_id,
image_remove:1},
success: function(response) {
$('#image_'+image_id).fadeOut(400);
showUploader();
}
})
})
});
$(document).ready(function() {
$(".assign_main").click(function() {
var assign_this_id = $(this).attr('id');
$.ajax({
type:"post",
url:"imagecontrol.php",
data: { assign_this_id:assign_this_id,
image_assign:1},
success: function(response) {
alert("Success");
}
})
})
});
</script>
The success method is only called when a HTTP 200 or HTTP 304 is returned, therefore you may need to double check to see if this is actually the case.
This can be done in the ‘Inspector’ panel in most modern web browsers, usually under the ‘Network’ tab.
You can also add a error: function() {} event handler to catch any HTTP 4xx / 5xx codes.
Try and alert the error which for sure is there:
$(document).ready(function() {
$(".assign_main").click(function() {
var assign_this_id = $(this).attr('id');
$.ajax({
type:"post",
url:"imagecontrol.php",
data: { assign_this_id:assign_this_id,
image_assign:1},
success: function(response) {
alert("Success");
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + " " + errorThrown);
}
})
})
});
This will show you if there is something wrong in your PHP code
Use done() instead of it :
$.ajax({
type: "post",
url: "imagecontrol.php",
data: {
image_id: image_id,
image_remove: 1
}
}).done(function(response) {
$('#image_' + image_id).fadeOut(400);
showUploader();
);

Calling Ajax request function in href

I have an href in an html page and i have an AJAX request in a method in a javascript file.
When clicking on href i want to call the JS function and I am treating the response to add it to the second html page which will appear
function miniReport(){
alert('TEST');
var client_account_number = localStorage.getItem("numb");
var request = $.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {client_language: client_language, PIN_code:pin,client_phone:number}
});
request.done(function(msg) {
//alert(JSON.stringify(msg));
});
if (msg.ws_resultat.result_ok==true)
{
alert('success!');
window.open("account_details.html");
}
request.error(function(jqXHR, textStatus)
{
//MESSAGE
});
}
I tried with , and also to write the function with $('#idOfHref').click(function(){}); not working.
All I can see is the alert TEST and then nothing happens. I checked several posts here but nothing works for me.
Function can be corrected as,
function miniReport(){
alert('TEST');
var client_account_number = localStorage.getItem("numb");
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {"client_language": client_language, "PIN_code":pin,"client_phone":number},
success : function(msg) {
//alert(JSON.stringify(msg));
if (msg.ws_resultat.result_ok == true)
{
alert('success!');
window.open("account_details.html");
}
},
error: function(jqXHR, textStatus)
{
alert('Error Occured'); //MESSAGE
}
}
});
1. No need to assign ajax call to a variable,
2. Your further work should be in Success part of AJAX request, as shown above.
It's a bad practice use an onclick() so the proper way to do this is:
Fiddle
$(document).ready(function(){
$('#mylink').on('click', function(){
alert('onclick is working.');
miniReport(); //Your function
});
});
function miniReport(){
var client_account_number = localStorage.getItem('numb');
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data: {
'client_language': client_language,
'PIN_code': pin,
'client_phone': number
},
success: function(msg){
if (msg.ws_resultat.result_ok==true)
{
alert('success!');
window.open("account_details.html");
}
},
error: function(jqXHR, textStatus)
{
//Manage your error.
}
});
}
Also you have some mistakes in your ajax request. So I hope it's helps.
Rectified version of your code with document .ready
$(document).ready(function(){
$("#hrefid").click(function(){ // your anchor tag id if not assign any id
var client_account_number = localStorage.getItem("numb");
$.ajax({
url: server_url + '/ws_report',
timeout:30000,
type: "POST",
data:{"client_language":client_language,"PIN_code":pin,"client_phone":number},
success : function(msg) {
if (msg.ws_resultat.result_ok == true)
{
window.open("account_details.html");
}
else
{
alert('some thing went wrong, plz try again');
}
}
}
});
});

trigger a javascript function before on any AJAX call

Here, I have a function which needs to be called before any AJAX call present in the .NET project.
Currently, I have to call checkConnection on every button click which is going to invoke AJAX method, if net connection is there, proceeds to actual AJAX call!
Anyhow, I want to avoid this way and the checkConnection function should be called automatically before any AJAX call on the form.
In short, I want to make function behave like an event which will be triggered before any AJAX call
Adding sample, which makes AJAX call on button click; Of course, after checking internet availability...
//check internet availability
function checkConnection() {
//stuff here to check internet then, set return value in the variable
return Retval;
}
//Ajax call
function SaveData() {
var YearData = {
"holiday_date": D.getElementById('txtYears').value
};
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
And below is current way to call function:
<form onsubmit="return Save();">
<input type="text" id="txtYears" /><br />
<input type="submit" id="btnSave" onclick="return checkConnection();" value="Save" />
<script>
function Save() {
if (confirm('Are you sure?')) {
SaveData();
}
else {
return false;
}
}
</script>
</form>
You cannot implicitly call a function without actually writing a call even once(!) in JavaScript.
So, better to call it in actual AJAX and for that you can use beforeSend property of ajaxRequest like following, hence there will be no need to call checkConnection() seperately:
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
beforeSend: function() {
if(!checkConnection())
return false;
},
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
It reduces the call that you have made onsubmit() of form tag!
UPDATE:
to register a global function before every AJAX request use:
$(document).ajaxSend(function() {
if(!checkConnection())
return false;
});
The best way is to use a publish-subsribe pattern to add any extra functions to be called on pre-determined times (either before or after ajax for example).
jQuery already supports custom publish-subsrcibe
For this specific example just do this:
//Ajax call
function SaveData(element) {
var doAjax = true;
var YearData = {
"holiday_date": D.getElementById('txtYears').value
};
if (element === myForm)
{
doAjax = checkConnection();
}
if ( doAjax )
{
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
else
{
// display a message
}
}
Hope i understand correctly what you mean.
UPDATE:
in the if you can do an additional check if the function is called from the form or a field (for example add an argument SaveData(element))
If you use the saveData in html, do this: "saveData(this)", maybe you should post your html as well
You can use:
$(document)
.ajaxStart(function () {
alert("ajax start");
})
.ajaxComplete(function () {
alert("ajax complete");
})
That's it!!
use
beforeSend: function () {
},
ajax method

Jquery Ajax beforeSend and success,error & complete

I have a problem with multiple ajax functions where the beforeSend of the second ajax post is executed before the complete function of the first ajax.
The loading class I am adding to the placeholder before sending is working for the first ajax call. However soon after the first ajax request completes the class is removed and never appends again on the second and further calls (remember recursive calls).
While debugging it shows that the beforeSend function of the second ajax call is called first and the complete function of the first ajax call is called later. Which is obvious, because the return data inserted in the page from the first ajax call starts the second call.
In short it's mixed up. Is there any way this can be sorted out?
The function code is as follows
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function() {
// setting a timeout
$(placeholder).addClass('loading');
},
success: function(data) {
if (append) {
$(placeholder).append(data);
} else {
$(placeholder).html(data);
}
},
error: function(xhr) { // if error occured
alert("Error occured.please try again");
$(placeholder).append(xhr.statusText + xhr.responseText);
$(placeholder).removeClass('loading');
},
complete: function() {
$(placeholder).removeClass('loading');
},
dataType: 'html'
});
}
And the data contains the following snippet of javascript/jquery which checks and starts another ajax request.
<script type="text/javascript">//<!--
$(document).ready(function() {
$('#restart').val(-1)
$('#ajaxSubmit').click();
});
//--></script>
Maybe you can try the following :
var i = 0;
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
type: 'POST',
url: url,
data: data,
beforeSend: function() {
// setting a timeout
$(placeholder).addClass('loading');
i++;
},
success: function(data) {
if (append) {
$(placeholder).append(data);
} else {
$(placeholder).html(data);
}
},
error: function(xhr) { // if error occured
alert("Error occured.please try again");
$(placeholder).append(xhr.statusText + xhr.responseText);
$(placeholder).removeClass('loading');
},
complete: function() {
i--;
if (i <= 0) {
$(placeholder).removeClass('loading');
}
},
dataType: 'html'
});
}
This way, if the beforeSend statement is called before the complete statement i will be greater than 0 so it will not remove the class. Then only the last call will be able to remove it.
I cannot test it, let me know if it works or not.
It's actually much easier with jQuery's promise API:
$.ajax(
type: "GET",
url: requestURL,
).then((success) =>
console.dir(success)
).failure((failureResponse) =>
console.dir(failureResponse)
)
Alternatively, you can pass in of bind functions to each result callback; the order of parameters is: (success, failure). So long as you specify a function with at least 1 parameter, you get access to the response. So, for example, if you wanted to check the response text, you could simply do:
$.ajax(
type: "GET",
url: #get("url") + "logout",
beforeSend: (xhr) -> xhr.setRequestHeader("token", currentToken)
).failure((response) -> console.log "Request was unauthorized" if response.status is 401

Categories

Resources