Returning Response in jquery ajax function - javascript

Getting problems in Response.d , based on the result which is returning by the checkusers() function I am saving the values. If the entered name is in already in database it should say "User already exists", if it is not in database it should create a new record.
But I am not getting the correct value from (response), I observed that Console.log(response.d) giving me correct values like 'true' or 'false'. I tried everything I know like-
changing async:"false"
var jqXHR = $.ajax({ and returning jqXHR.responseText
But none of they worked for me . Please help me with this.
submitHandler: function (form) {
var txtName = $("#txtName").val();
var txtEmail = $("#txtEmail").val();
var txtSurName = $("#txtSurName").val();
var txtMobile = $("#txtMobile").val();
var txtAddress = $("#txtAddress").val();
var obj = CheckUser();
if (obj == false) {
$.ajax({
type: "POST",
url: location.pathname + "/saveData",
data: "{Name:'" + txtName + "',SurName:'" + txtSurName + "',Email:'" + txtEmail + "',Mobile:'" + txtMobile + "',Address:'" + txtAddress + "'}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
$(".errMsg ul").remove();
var myObject = eval('(' + response.d + ')');
if (myObject > 0) {
bindData();
$(".errMsg").append("<ul><li>Data saved successfully</li></ul>");
}
else {
$(".errMsg").append("<ul><li>Opppps something went wrong.</li></ul>");
}
$(".errMsg").show("slow");
clear();
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
else {
$(".errMsg").append("<ul><li>User Already Exists </li></ul>");
$(".errMsg").show("slow");
}
}
});
$("#btnSave").click(function () {
$("#form1").submit()
});
});
checkusers function is:
function CheckUser() {
var EmpName = $("#txtName").val();
$.ajax({
type: "POST",
url: location.pathname + "/UserExist",
data: "{Name:'" + EmpName + "'}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
console.log(response.d);
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}

Just because your database returns true or false doesn't mean this also gets returned by your CheckUser().
There are several options here:
Either you make a local variable in your CheckUser, Make your Ajax call synchronous, set the local variable to response.d in the success function and then return that local variable.
Another option is to work with Deferred objects and make your submithandler Ajax call wait for the Checkuser Ajax call to return;
A third option is to call your create ajax call from your success callback in your CheckUser Ajax call if the user isn't created yet.
I would recommend either option 2 or 3, because option 1 is not userfriendly.

Related

JavaScript/jQuery callback using Ajax

I'm having trouble with my functions running before Ajax requests (the first to a local JSON, the second to an online resource) have finished.
In this example I want countTheMovies to run at the end after my application has got all the information it needs and populated the divs. Instead it's running straight away.
I tried to delay it using an if condition, but with no joy. I've also tried with callbacks, but think I must be getting those wrong (I'm assuming callbacks are the answer). I'm aware of timed delays, but because in the actual project I'm sourcing 250+ movies (and because a timed delay seems like cheating) I thought I'd ask here instead.
Can anyone recommend JavaScript or jQuery code to fix this problem?
$(function(){
getMovieList();
});
function getMovieList() {
$.ajax({
url: "movielist.json",
type: "GET",
dataType: "JSON",
success: function(data) {
for (var i = 0; i < data.length; i++) {
var title = data[i].title.toLowerCase().split(" ").join("+");
var year = data[i].year;
i === data.length - 1
? getMovieInfo(title, year, true)
: getMovieInfo(title, year, false);
}
}
});
}
function getMovieInfo(title, year, isLast) {
$.ajax({
url: "https://www.omdbapi.com/?t=" + title + "&y=" + year + "&plot=short&r=json",
type: "GET",
crossDomain: true,
dataType: "JSON",
success: function(val) {
if (!val.Error) {
movie = title.replace(/[^a-z0-9\s]/gi, '');
$("#app").append(
// appending info to divs
);
}
}
});
if (isLast) countTheMovies();
};
function countTheMovies() {
$("#app").append("There are " + $(".movie").length + " movies.");
}
A plunker of my failings: https://plnkr.co/edit/0mhAUtEsaOUWhkZMJqma?p=preview
You've almost got it!
The same way that you call getMovieInfo in the success callback of getMovieList, you should be calling countTheMovies in the success callback of getMovieInfo.
As Jacob said above, move the countTheMovies call inside the AJAX request.
$(function(){
getMovieList();
});
function getMovieList() {
$.ajax({
url: "movielist.json",
type: "GET",
dataType: "JSON",
success: function(data) {
for (var i = 0; i < data.length; i++) {
var title = data[i].title.toLowerCase().split(" ").join("+");
var year = data[i].year;
i === data.length - 1
? getMovieInfo(title, year, true)
: getMovieInfo(title, year, false);
}
}
});
}
function getMovieInfo(title, year, isLast) {
$.ajax({
url: "https://www.omdbapi.com/?t=" + title + "&y=" + year + "&plot=short&r=json",
type: "GET",
crossDomain: true,
dataType: "JSON",
success: function(val) {
if (!val.Error) {
movie = title.replace(/[^a-z0-9\s]/gi, '');
$("#app").append(
// appending info to divs
);
if (isLast) countTheMovies();
}
}
});
};
function countTheMovies() {
$("#app").append("There are " + $(".movie").length + " movies.");
}
Just put your countTheMovies() logic inside of the success callback of the AJAX request in getMovieInfo if you want it to run on success.
You can call your countTheMovies() function from inside the success field of your Ajax call. This way it will make the function call when you intend it to.
Try out this
$(function(){
getMovieList();
});
function getMovieList() {
$.when( $.ajax({
url: "movielist.json",
type: "GET",
dataType: "JSON",
success: function(data) {
for (var i = 0; i < data.length; i++) {
var title = data[i].title.toLowerCase().split(" ").join("+");
var year = data[i].year;
i === data.length - 1
? getMovieInfo(title, year, true)
: getMovieInfo(title, year, false);
}
}
}) ).then(function( data, textStatus, jqXHR ) {
countTheMovies();
});
}
function getMovieInfo(title, year, isLast) {
$.ajax({
url: "https://www.omdbapi.com/?t=" + title + "&y=" + year + "&plot=short&r=json",
type: "GET",
crossDomain: true,
dataType: "JSON",
success: function(val) {
if (!val.Error) {
movie = title.replace(/[^a-z0-9\s]/gi, '');
$("#app").append(
// appending info to divs
);
}
}
});
};
function countTheMovies() {
$("#app").append("There are " + $(".movie").length + " movies.");
}

Getting this in ajax result

im trying to make a script that changes P lines to input fields, let user edit them and then revert back to p lines after a check in an external php document through ajax. However the problem seems to be that I cant use this within the ajax part, it breaks the code. How can I solve that? Do I need to post the HTML?
$(document).ready(function () {
function changeshit(result, that) {
if (result == "success") {
$(that).closest('div').find('input').each(function () {
var el_naam = $(that).attr("name");
var el_id = $(that).attr("id");
var el_content = $(that).attr("value");
$(that).replaceWith("<p name='" + el_naam + "' id='" + el_id + "'>" + el_content + "</p>");
});
$(".editlink").replaceWith("Bewerken");
} else {
alert(result);
}
}
$(".editinv").on('click', 'a', function () {
var editid = $(this).attr("id");
var edit_or_text = $(this).attr("name");
if (edit_or_text == "edit") {
$(this).closest('div').find('p').each(function () {
var el_naam = $(this).attr("name");
var el_id = $(this).attr("id");
var el_content = $(this).text();
$(this).replaceWith("<input type='text' name='" + el_naam + "' id='" + el_id + "' value='" + el_content + "' />");
});
$(".editlink").replaceWith("Klaar");
} else if (edit_or_text == "done") {
var poststring = "";
$(this).closest('div').find('input').each(function () {
var el_naam = $(this).attr("name");
var el_id = $(this).attr("id");
var el_content = $(this).attr("value");
poststring = poststring + '' + el_naam + '=' + el_content + '&';
});
poststring = poststring + 'end=end'
$.ajax({
url: 'http://' + document.domain + '/klanten/updateaddress.php',
type: 'post',
data: poststring,
success: function (result, this) {
changeshit(result, this);
}
});
}
});
});
Yes, the common solutions is declare a var example self = this and use that variable
var self = this;
$.ajax({
url: 'http://'+document.domain+'/klanten/updateaddress.php',
type: 'post',
data: poststring,
success: function(result) {
changeshit(result, self);
}
});
}
In that way, the this context is save in the variable.
Try the following:
Right under $(".editinv").on('click', 'a', function () { add
$(".editinv").on('click', 'a', function () {
var element = this;
And then change this to:
$.ajax({
url: 'http://' + document.domain + '/klanten/updateaddress.php',
type: 'post',
data: poststring,
success: function (result) {
changeshit(result, element);
}
});
That is if I am understanding correctly what you are trying to do
If you simply add:
context: this
to the $.ajax options then the success handler will automatically be called with the correct value of this, so you won't need the that parameter.
You'll then also no longer need the extra function wrapper around the success callback, so you can just use:
$.ajax({
url: 'http://' + document.domain + '/klanten/updateaddress.php',
type: 'post',
data: poststring,
context: this, // propagate "this"
success: changeshit // just pass the func ref
});
There are a few ways you can achieve this
1) If you read the docs (jQuery.ajax) you'll see that you can supply a context to the ajax method
context
Type: PlainObject This object will be made the context of all Ajax-related callbacks. By default, the context is an object that
represents the ajax settings used in the call ($.ajaxSettings merged
with the settings passed to $.ajax).
$.ajax({
url: 'http://'+document.domain+'/klanten/updateaddress.php',
type: 'post',
data: poststring,
context: this,
success: function(result) {
// the context sent above would become the context of this function when called by jquery
changeshit(result, this);
}
});
Using it this way you could even do it like the bellow code
function changeshit (result) {
var $that = $(this);
if (result == "success") {
$that.closest('div')... // cool ha ?
};
$.ajax({
url: 'http://'+document.domain+'/klanten/updateaddress.php',
type: 'post',
data: poststring,
context: this,
success: changeshit
});
2) You can take advantage of closures ( read more here or search google ), so your code would become
var context = this;
$.ajax({
url: 'http://'+document.domain+'/klanten/updateaddress.php',
type: 'post',
data: poststring,
success: function(result) {
// here you can use any variable you declared before the call
changeshit(result, context);
}
});
As a side note, i would recommend you use variable/object caching, so declare var $this = $(this) at the top of the function and use it thruought your function, instead of calling $(this) each time you need it.

Why the text before Ajax call is not display?

function pdfToImgExec(file, IsfirstLogging, folder, round) {
alert(file);
var postString = file + '&' + IsfirstLogging + '&' + folder + '&' + round;
var errorMsg = (folder == 'Incoming' ? '<p>error in incoming folder</p>' : '<p>error in other folder</p>');
$.ajax({
type: "POST",
cache: false,
async: false,
url: "pdfToImgExec.php",
data: {
"data": postString
},
dataType: "html",
beforeSend: function () {
alert(file + 'a');
$('#pdfToImgResult').html('<p>Converting' + file + ', Please wait......</p>');
},
success: function (data) {
if(data == '1') {
$('#pdfToImgResult').html('<p>Complete convert ' + file + '</p>');
} else if(round < 4) {
$('#pdfToImgResult').html('<p>Fail to convert , retry ' + round + ' round <img src="loading.gif" height="20" width="20"/></p>');
round++;
pdfToImgExec(file, 'false', folder, round);
} else {
folder == 'Incoming' ? tempFailIncomingFiles.push(file) : tempFailResultFiles.push(file);
}
},
error: function (x, t, m) {
$('#pdfToImgResult').html(errorMsg);
alert(t);
releaseBtn();
}
});
}
The problem of this ajax call is I can alert the (file + 'a') in the beforeSend function , but the
$('#pdfToImgResult').html('<p>Converting' + file + ', Please wait......</p>');
is not working, it will not display anything but only jumped to the
$('#pdfToImgResult').html('<p>Complete convert ' + file + '</p>');
after the ajax call is finished.
Is it due to async:false? How to fix the problem ? thanks.
It's because you're using async: false,, so the function blocks until the request is complete, preventing a redraw until everything is done.
You seem to be all set up with callbacks, so there doesn't seem to be any reason to make a blocking xhr request. Just remove the async: false,, and you should be all set.
Here's a quick example of how to deal with asynchronous code. I've removed most of your code to keep it brief.
// --------------------------------new parameter-------------v
function pdfToImgExec(file, IsfirstLogging, folder, round, callback) {
// your code...
$.ajax({
type: "POST",
cache: false,
// async: false, // Remove this line!
url: "pdfToImgExec.php",
data: {
"data": postString
},
dataType: "html",
beforeSend: function () {
$('#pdfToImgResult').html('<p>Converting' + file + ', Please wait......</p>');
},
success: function (data) {
// your code...
// Invoke the callback, passing it the data if needed
callback(data)
},
error: function (x, t, m) {
// your code;
}
});
}
When you call pdftoImgExec, pass a function as the last parameter that will be invoked when the response is complete. That function is where your code resumes.
pdfToImgExec(..., ..., ..., ..., function(data) {
// resume your code here.
alert(data);
})

Javascript eval String + variable

I have a piece of javascript code evaluated at runtime, with the <%= %> syntax...
Now, inside the <%= %>, instead of a hard coded string, i'd like to have the value stored in a variable... How can I do this?
This is the function:
function updateDescriptionLabel(msgToParse, dataColumn, TextBoxID) {
var myData = JSON.parse(msgToParse.d);
alert(msgToParse);
alert(dataColumn);
alert(TextBoxID);
// this is the explicit call, it's ok
$('#' + '<%= this.TextBoxDES_MACCHINA.ClientID %>').val($.trim(myData["DescrMacchina"]));
// NOW i want to make the call by using the variable value
var txtDes = TextBoxID;
$('#' + '<%= this.' + txtDes.toString() + '.ClientID %>').val($.trim(myData["DescrMacch"]));
// BUT i get the error: Too many characters in character literal
}
============== EDIT ===============
I have a bunch of TextBoxID that, on lost focus, get a get a value from database, and display it on the appropriate TextBoxDESCRIPTION related to the ID...
But I have to duplicate the code for each TextBox, so I'd like to generalize it...
I post the entire code.
<script language="javascript" type="text/javascript">
/* ==> JSON */
//Ajax Request
function SendAjaxRequest(urlMethod, jsonData, returnFunction) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: urlMethod,
data: jsonData,
dataType: "json",
success: function (msg) {
// Do something interesting here.
if (msg != null) {
returnFunction(msg);
}
},
error: function (xhr, status, error) {
// Boil the ASP.NET AJAX error down to JSON.
var err = eval("(" + xhr.responseText + ")");
// Display the specific error raised by the server
alert(err.Message);
}
});
}
// I'd like to generalize it ...
function SendComplexAjaxRequest(urlMethod, jsonData, returnFunction, dataColumn, TextBoxID) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: urlMethod,
data: jsonData,
dataType: "json",
success: function (msg) {
// Do something interesting here.
if (msg != null) {
returnFunction(msg, dataColumn, TextBoxID);
}
},
error: function (xhr, status, error) {
// Boil the ASP.NET AJAX error down to JSON.
var err = eval("(" + xhr.responseText + ")");
// Display the specific error raised by the server
alert(err.Message);
}
});
}
// ONE function for each textBox
function callUpdateGuastoAttributes(code) {
var urlMethod = '<% = ResolveClientUrl("~/Services/ws_Attributes.asmx/OdLGetMacchinaAttributes") %>';
var jsonData = "{'COD_MACCHINA':'" + code + "'}";
var successFunction = updateLabelsGuastoAttributs;
SendAjaxRequest(urlMethod, jsonData, successFunction);
}
function callUpdateCausaGuastoAttributes(code) {
var urlMethod = '<% = ResolveClientUrl("~/Services/ws_Attributes.asmx/OdLGetMacchinaAttributes") %>';
var jsonData = "{'COD_MACCHINA':'" + code + "'}";
var successFunction = updateLabelsCausaGuastoAttributs;
SendAjaxRequest(urlMethod, jsonData, successFunction);
}
// I can have only one function:
function callUpdateMacchinaAttributes(code) {
var urlMethod = '<% = ResolveClientUrl("~/Services/ws_Attributes.asmx/OdLGetMacchinaAttributes") %>';
var jsonData = "{'COD_MACCHINA':'" + code + "'}";
var successFunction = updateDescriptionLabel;
SendComplexAjaxRequest(urlMethod, jsonData, successFunction, 'DescrMacchina', 'TextBoxDES_MACCHINA');
}
/* <== CALLBACK */
function updateLabelsMacchinaAttributs(msg) {
var myData = JSON.parse(msg.d);
$('#' + '<%= this.TextBoxDES_MACCHINA.ClientID %>').val($.trim(myData["DescrMacchina"]));
}
function updateLabelsGuastoAttributs(msg) {
var myData = JSON.parse(msg.d);
$('#' + '<%= this.TextBoxDES_GUASTO.ClientID %>').val($.trim(myData["description"]));
}
function updateLabelsCausaGuastoAttributs(msg) {
var myData = JSON.parse(msg.d);
$('#' + '<%= this.TextBoxDES_CAUSA_GUASTO.ClientID %>').val($.trim(myData["description"]));
}
// BUT I have to generalize it...
function updateDescriptionLabel(msgToParse, dataColumn, TextBoxID) {
var myData = JSON.parse(msgToParse.d);
alert(msgToParse);
alert(dataColumn);
alert(TextBoxID);
// this is the explicit call
$('#' + '<%= this.TextBoxDES_MACCHINA.ClientID %>').val($.trim(myData["DescrMacchina"]));
// i want to make the call by using the variables values
var dCol = dataColumn;
var txtDes = TextBoxID;
$('#' + '<%= this.' + txtDes.toString() + '.ClientID %>').val($.trim(myData[dCol]));
// i get the error: Too many characters in character literal
}
I propose such solution (depending on your other code...) :
function updateDescriptionLabel(msgToParse, dataColumn, TextBoxID) {
var myData = JSON.parse(msgToParse.d);
alert(msgToParse);
alert(dataColumn);
alert(TextBoxID);
// this is the explicit call, it's ok
$('#' + '<%= this.TextBoxDES_MACCHINA.ClientID %>').val($.trim(myData["DescrMacchina"]));
// NOW i want to make the call by using the variable value
$('#' + TextBoxID).val($.trim(myData["DescrMacch"]));
}
and then when you call this function do this :
updateDescriptionLabel("your message", <yourcolumn>, <%= this.TextBoxDES_MACCHINA.ClientID %>);

How to ensure that a function is executed completely, before navigating to another page?

I'm removing certain records using a webservice. The jquery ajax request is written in the onclick of a hyperlink. When im executing the script, line by line using firebug, it's getting removed otherwise it's not. Does any one meet any situation like this before? Please help
Code sample:
$(".target").click(function() {
func(); //This function should be executed completely before navigating to another page
});
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
}
//Event that'll be fired on Success
});
}
jQuery ajax functions return deferred objects, thus we return $.ajax. Then you should use deferred.done to execute the callback when the AJAX is fully finished. When the AJAX is done, navigate away using JS instead:
var func = function() {
...
return $.ajax({...}); //return our ajax deferred
}
$(".target").click(function() {
var target = this; //preserve "this" since this in the callback may be different
func().done(function(){ //our done callback executed when ajax is done
window.location.href = target.href; //assuming .target is a link
});
return false; //prevent the natural click action
});
You can use the async: false on the ajax call that is wait there to complete the call.
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
async: false,
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
}
//Event that'll be fired on Success
});
}
Alternative you can make the submit after the request.
$(".target").click(function() {
func(); //This function should be executed completely before navigating to another page
return false;
});
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
async: true,
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
$("#YourFormID").submit();
}
//Event that'll be fired on Success
});
}
Simply move the Event to the "success" handler in your ajax request:
$.ajax({
type: "POST",
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed");
//Event that'll be fired on Success
}
});
Alternatively use jQuery ajax callback methods.

Categories

Resources