js passing function name as argument behaving differently with and withour parenthesis - javascript

i have made a wrapper function for $.ajax, i pass url,type,data and success function name as argument to it when i need ajax request
function postdata(url, type, data, succ)
{
console.log(succ);
//alert(succ);
$.ajax({
url: url,
type: type,
dataType: "json",
data: data,
success: succ
});
return false;
}
now 4rth argument is success function's name but behaving differently, one time it is working with name+parenthesis only, not working without parenthesis example
del = function(data) {
alert("executed");
$(":checked").each(function() {
$(this).parent("li").slideUp();
});
$('#myModal').modal('hide');
};
postdata("delete/", "POST",gl_obj,del());
and other time it is working only name without parenthesis, example
temp = function(obj) {
obj = eval("(" + obj + ")");
document.getElementById('temp').innerHTML += "<ul>";
for (i in obj)
{
//document.write(obj[i].name+"<br/>");
document.getElementById('temp').innerHTML += "<li data-id='" + obj[i].id + "' class='mylist'><input type='checkbox' class='checkbx'>" + obj[i].name + "<span class='glyphicon glyphicon-remove to-close'></span></li>";
}
document.getElementById('temp').innerHTML += "</ul>";
};
postdata("get_names/", 'GET', "", temp);
so "die" doesnt works , "diw()" woks and executes the die function, in contrast to it "temp" works fine withour parenthesis, can any one clear this confusion why it is behaving differently? and whats the concept

This is really rather obvious when you look at what the parenthesis does.
functionname is a function, just sitting there doing nothing
functionname() means execute the function
You have written a function that passes along a function as a parameter (a callback). That callback function is then passed to ajax for it to call-back, when required.
You should never execute the callback when you call your method (e.g. del()).
You should always just pass the function (e.g. del). The ajax method will actually call the function you passed when it has completed.
Other problems
I gather the following is the code that will not "work":
del = function(data) {
alert("executed");
$(":checked").each(function() {
$(this).parent("li").slideUp();
});
$('#myModal').modal('hide');
};
postdata("delete/", "POST", gl_obj, del);
Written as shown above, it will "work", but only if the Ajax call succeeds. You might want to add the following for testing purposes:
function postdata(url, type, data, succ, err)
{
console.log(succ);
//alert(succ);
$.ajax({
url: url,
type: type,
dataType: "json",
data: data,
success: succ,
error: err
});
return false;
}
del = function(data) {
alert("executed");
$(":checked").each(function() {
$(this).parent("li").slideUp();
});
$('#myModal').modal('hide');
};
postdata("delete/", "POST", gl_obj, del, function(){alert('Oh crap!');});
Update (again):
Based on the comments and trials of the above code, the delete/ POST call to the server is failing.
Note: you do not need to return anything from your postdata method.
To see the error, change your code to:
function postdata(url, type, data, succ)
{
console.log(succ);
//alert(succ);
$.ajax({
url: url,
type: type,
dataType: "json",
data: data,
success: succ,
error: function( jqXHR, textStatus, errorThrown ){
alert(textStatus + " - " + errorThrown);
}
});
}
postdata("delete/", "POST", gl_obj, del);

the actual problem was of dataType being passed wrong for del callbackfuncion se i modified the potion of code
function postdata(url, type, data, succ,dataType)
{
console.log(succ);
//alert(succ);
$.ajax({
url: url,
type: type,
dataType: dataType,
data: data,
success: succ
});
return false;
}
Now this will be based as blank in case of del and json in case of temp
for del:
postdata("delete/", "POST",gl_obj,del,"");
and for temp
postdata("get_names/", 'GET', "", temp,"json");

Related

Gettign values from jquery ajax sucess using jason

I'm new to jquery and I can;t find an answer to my simple problem on the web.
I have
$(document).ready(function () {
$.ajax({
type: "POST",
url: "Default.aspx/Getmessage",
data: "{'uid': '" + "XX" + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: OnFailure
});
});
function OnSuccess(data) {
$("#lblMessageReceived").html(data.uid + data.text);
}
function OnFailure() {
alert("Error");
}
Server side I have
Public Class clsResponseData
Public Property uid As String
Public Property text As String = "Hello"
End Class
<System.Web.Services.WebMethod()>
Public Shared Function getMessage(uid As String) As String
Dim rd As New clsResponseData
rd.uid = uid
Return JsonConvert.SerializeObject(rd)
End Function
When I run the code I get
"data" as Object {d: "{"uid":"XX","text":"Hello"}"}
and then
"data.d" as "{"uid":"XX","text":"Hello"}"
but then
"data.d.uid" returns undefined
so how do I reference the value of "uid" and "text"? .
I have tried this code with the Visuals Studio editor and Chrome browser insepction. What else do I need to add?
In case anyone looks for this, i cound the answer is to add an eval() function
function OnSuccess(data) {
eval('var t =' + data.d);
$("#lblMessageReceived").html(t.uid + t.text);
}

How to get variable from one Ajax function to work in another Ajax function

I am attempting use a variable that I create through data being sent from php in one ajax function in a another ajax function. I'm not sure what I am doing wrong. I tried creating making this a global variable by doing var nameOutput and also tried var nameOutput = 0. You will see alert code in the second ajax function. This is outputting nothing. If I remove the .val(), I receive object Object.
The code in question is in the second Ajax function: data: {
'nameOutput': nameOutput.val()
}
Does anyone have any idea what I have to do?
var nameOutput;
$('#shuffle').on('click', function() {
$.ajax({
url: 'php/name-selection.php',
type: 'POST',
success: function(data) {
nameOutput = $('#name-output').html(data);
$(nameOutput).html();
},
complete:function(){
$('#send-info').slideDown(1500);
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
}
});
});
//var datastring1 = $('#name-output').serialize();
$('.check').click(function() {
alert(nameOutput.val());
$.ajax({
url: 'php/name-selection-send.php',
type: 'POST',
data: {
'nameOutput': nameOutput.val()
}
,
success: function(data) {
if (data == 'Error!') {
alert('Unable to submit inquiry!');
alert(data);
} else {
$('#success-sent').html(data);
}
},
complete:function(){
},
error: function(xhr, textStatus, errorThrown) {
alert(textStatus + '|' + errorThrown);
}
});
if you can set inner html of nameOutput using .html('blah') , so you can extract the html again using nameOutput.html() not nameOutput.val();
however I think you have to define the element like this to be a HTML element:
var nameOutput=$('<div></div>');
also in first ajax function,set the html using this:
nameOutput.html(data);
and if there is a real element with ID name-output , and you want the result to be visible, do both of these:
nameOutput.html(data);
$('#name-output').html(data);

Unable to bind data to textbox in ajax success function

[WebMethod]
public static List<SalesInvoiceFinalCalculationEntity> salesInvoiceFinalCalculaiton(string InvoiceNo)
{
List<SalesInvoiceFinalCalculationEntity> list = new List<SalesInvoiceFinalCalculationEntity>();
list = SalesInvoiceManager1.salesInvoiceFinalCalculaiton(InvoiceNo);
return list;
}
Above code returns list of some values which i want to bind to textboxes. I cant understand that why these values are not getting in ajax Success function below:
function salesInvoiceFinalCalculaiton() {
var invoice = {};
var InvoiceNo = $("#txt_InvoiceNo").val();
$.ajax({
async: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/AjaxRequestToServer.aspx/salesInvoiceFinalCalculaiton", //URI
data: "{InvoiceNo:'" + InvoiceNo + "'}",
dataType: "json",
success: function (data) {
//Commented code working Fine
//if (!$.trim(data)) {
// alert("What follows is blank: " + data);
//}
//else {
// alert("What follows is not blank: " + data);
//}
//bootbox.alert("Hi", function (e) { });
//But cannot Bind data in textbox
$('#txtinvoicevalue').val(data.d[0].totalprice);
$('#txtTotalDiscount').val(data.d[0].discountamt);
$('#txtGrandTotal').val(data.d[0].grandtotal);
},
error: function (xhr) {
if (xhr.statusText == "Invalid Request") {
sessionStorage.clear();
}
}
});
}
Here Success function working fine. And Commented code also gives right output. But I cant assign the data to textboxes. Thanks in advance.
try using getElementById instead and see if that helps, also check to see if you can print the values into your debug console.
pressing F12 will usually show you the development console on browsers, check your script errors there.

Returning Response in jquery ajax function

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.

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