Unable to bind data to textbox in ajax success function - javascript

[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.

Related

Populate Ajax response with clickable elements that fires another Ajax with correct parameters

So i have a function running an Ajax call that receives data and populate that as a table.
The response contains some rows with data and i now want to add a small fontawsome icon that when clicked fires another function with a parameter.
So i have this:
var latestprecasedata = '';
function getPreCaseData() {
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "case.aspx/GetPreCase",
dataType: "json",
success: function (response) {
if (response != null && response.d != null) {
var data = response.d;
data = $.parseJSON(data);
$("#PreCaseTblBody").html("");
for (var i in data) {
$("#PreCaseTblBody").append("<tr><td>" + data[i].pSubject + "</td><td><span class='preplus' id='" + data[i].pID + "'><i class='fa fa-plus'></i></span></td><td>-</td></tr>");
}
if (latestprecasedata !== response.d) {
$("#precasestatus").removeClass("titleupd1").addClass("titleupd2");
latestprecasedata = response.d;
}
else {
$("#precasestatus").removeClass("titleupd2").addClass("titleupd1");
}
}
$("#PreCaseTblBody tr:odd").css('background-color', '#f9f9f9'); //
$("#PreCaseTblBody tr:even").css('background-color', '#f1ffee');
setTimeout(getPreCaseData, 10000);
}
});
}
This works and every 10 seconds data is repopulated. (Maybe not the fastest solution, but it works..)
As you all can se i have a span with class=preplus and id of a unique value coming from my Ajax response. When inspecting the page i can see that every row from my Ajax response have a unique id.
For example two row looks like this:
<tr><td>Cables</td><td><span class="preplus" id="4815269"><i class="fa fa-plus"></i></span></td></tr>
<tr><td>Skrews</td><td><span class="preplus" id="4815269"><i class="fa fa-plus"></i></span></td></tr>
So now i have the data populated with span containing a unique id that i want to pass to another function.
I've tried span, div, buttons but the only one time I actually got a event fire was when i placed my second function inside the
for (var i in data) {
... and i know, that's not right at all because all rows contained the last id obviously...
So my other function resides outside my first function and look like this (I've tried many different methods to get the id of my span but for now, I'm here)
$(".preplus").click(function () {
var qID = $(this).attr('id');
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "case.aspx/UpdateQ",
dataType: "json",
data: "{'qid':'" + qID + "','pm':'plus'}",
success: function (data) {
}
});
return false;
});
Please guide me.

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);
}

make an ajax call in the very first page in JQM

I am trying to show a popup in my first page if a php post returns a json file with data.
I tried with:
$(document).on("pageinit", '#home', function() {
ajax call even with async:false,...
And after that, I fill up the element with some list elements if json has data:
if(userLastPush == 1){
var getPushXdays = '{"day":"4"}';
$.ajax({
type: "POST",
url: urlServer+"getPushXDays.php",
data: getPushXdays,
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
//console.log(response);
html = '';
if(response.message != "empty"){
jQuery.each(response, function(category, val) {
if(val.id_Event == 0){
html +='<li>' + val.message + '</li>';
}else{
html +='<li>' + val.message + '</li>';
}
});
}
$(".popupPush").append(html).listview('refresh');
if(checkPushing == 0){
$("#checkpush").trigger("click");
}
},
error: function(xhr, status, message) {}
});
}
But it just works sometimes. Others, ajax never ends or never shows data. I tried by using a function instead and function is called but no return from ajax. Is there a way to make this getting all data before page is load?

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

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");

Function called by jQuery Form Plugin's beforeSubmit not returning value

The beforeSubmit function in my jQuery Form plugin needs to check whether the selected file already exists on the server. Here's that relevant code:
$('#frmSermonUpload').ajaxForm({
beforeSubmit: function() {
// Reset errors and clear messages
ClearForm(false);
var formValid = true,
fileExists = CheckFileExists();
console.log('beforeSubmit fileExists: ' + fileExists);
if (fileExists === 'true') {
$('#uploadedFile').addClass('inputError');
$('#fileErrorMsg').append(' A file with that name already exists on the server.');
formValid = false;
} else {
if (!ValidateUploadForm()) {
formValid = false;
}
}
console.log('formValid: ' + formValid);
if (!formValid) {
return false;
}
},
...
Here's the CheckFileExists() function:
function CheckFileExists() {
var fileName = $('#uploadedFile').val().replace(/C:\\fakepath\\/i, ''),
dataString;
dataString = 'checkFileExists=' + fileName;
console.log('fileName: ' + fileName);
console.log('dataString: ' + dataString);
$.ajax({
type: 'POST',
url: '../scripts/sermonUpload.php',
data: dataString,
success: function(serverResult) {
console.log('serverResult: ' + serverResult);
if (serverResult === 'existsTrue') {
return 'true';
} else {
return 'false';
}
},
error: function(xhr, status, error) {
alert('An error occurred while attempting to determine if the selected file exists. Please try again.);
}
});
//console.log('Current value of returnResult: ' + returnResult);
//return returnResult;
}
As you can see I'm using console output to check what's going on. In the CheckFileExists() function, fileName and dataString are being reported correctly. On the PHP side, I know that the POST data is getting there due to some logging I've got going on there.
Here's the PHP code that uses the POST data:
if (isset($_POST['checkFileExists']) && $_POST['checkFileExists'] !== '') {
$log->lwrite('**Checking if file exists.**');
$fileToCheck = $targetPath . $_POST['checkFileExists'];
$log->lwrite('file_exists: ' . file_exists($fileToCheck));
if (file_exists($fileToCheck)) {
echo 'existsTrue';
} else {
echo 'existsFalse';
}
}
What's happening is, in the console, the line console.log('beforeSubmit fileExists: ' + fileExists); is returning "undefined" (beforeSubmit fileExists: undefined).
Here's all of the console output for an upload where the file already exists, so the beforeSubmit should be stopped:
fileName: 042913sermon.mp3
dataString; checkFileExists=042913sermon.mp3
beforeSubmit fileExists: undefined
formValid: true
serverResult: existsTrue
It must be significant that the serverResult line is displaying after everything else. Does that have to do with how long the ajax call takes? If so, is there a way to delay the rest of the script until the ajax call is done executing?
UPDATE
As aorlando pointed out, the order of the console output signified that I needed to add async: false to my $.ajax call. After doing so, the console output was correct, but the function CheckFileExists() is still getting reported as undefined in beforeSubmit.
Ok. Now the problem is the scope of return.
If you use "async: false" you can return in this way (not so elegant)
var returnValue='';
$.ajax({
type: 'POST',
url: '../scripts/sermonUpload.php',
data: dataString,
async: false,
success: function(serverResult) {
console.log('serverResult: ' + serverResult);
if (serverResult === 'existsTrue') {
returnValue = 'true';
} else {
returnValue= 'false';
}
},
error: function(xhr, status, error) {
alert('An error occurred while attempting to determine if the selected file exists. Please try again.);
}
});
return returnValue;
You must declare a var returnValue out of the scope of the ajax call. Inside the ajax function you can modify the value of returnValue;
This is a solution which use closure, a quite complex javascript feature. Further read something about scope of a variable in javascript: What is the scope of variables in JavaScript?
This is not a very nice solution; is better if you call a function inside "success" function of ajax call as my previous example.
That's all folks!
You are using an AJAX async call.
Your method CheckFileExists()n return a value before the ajax call complete.
So the simplest solutions is to use:
$.ajax({
type: 'POST',
url: '../scripts/sermonUpload.php',
data: dataString,
async: false ...
if you want to use async call (the default as you can see: http://api.jquery.com/jQuery.ajax/
you must call (for ex.) a postcall function in the success function of the ajax call:
success: function(serverResult) {
console.log('serverResult: ' + serverResult);
if (serverResult === 'existsTrue') {
postFn('true');
} else {
postFn('false');
}
}, ...
Be carefull with the scope of the postFn
funcion postFn(_result){
console.log(_result);
}
I hope to be clear.
That's all folks!

Categories

Resources