Gettign values from jquery ajax sucess using jason - javascript

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

Related

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.

ASP.NET execute WebMethod with Jquery/AJAX

I have one WebMethod that will execute some DB search and return it's data in some HTML template. I need to execute this method using jquery to populate an area of the website but the problem is that my website URL/URI is dynamic.
My URL is http://site/school-name/home. The school-name will always change to indicate wich school i'm accessing.
I have accomplished so far:
$.ajax({
type: "POST",
url: "/Default.aspx/BuscaEquipe",
data: { 'pIndex': pIndex, 'pLimite': 4, 'pUnidadeCE': codigoEmitente },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert(response.d);
},
failure: function(response) {
alert(response.d);
}
});
and the WebMethod:
public static string BuscaEquipe(int pIndex, int pLimite, int pUnidadeCE)
{
var objEquipe = new Equipe { EquipeUnidadeCE = pUnidadeCE, EquipeAtivo = 1 };
var CaminhoImagem = Configuracoes.CaminhoVirtual + "Controles/Redimensiona.ashx?img=" + Configuracoes.CaminhoVirtual + "images/equipe/" + pUnidadeCE + "/";
if (!objEquipe.Listar(objEquipe)) return "";
var depoimentos = objEquipe.lstEquipe.Skip(pIndex).Take(pLimite);
var objJson = new JavaScriptSerializer().Serialize(depoimentos.Aggregate("", (current, equipe) =>
current + ("<div class='col-lg-3 col-md-3 col-sm-3'><img src='" + CaminhoImagem + equipe.EquipeImagem + "&w=400&h=400' alt='" + equipe.EquipeNome + "' class='img-circle img_perfil'><div class='nome_perfil text-center'>" + equipe.EquipeNome + "</div></div>")));
return objJson;
}
Using like this i get a 401 Not Authorized and if i try to use my full URL http://site/school-name/Default.aspx/BuscaEquipe i get a 404.
P.S. I have already used this same method in another project and it worked fine but i can't figure out what's wrong in this one, i think it might be related to the URl but i'm not sure.
the problem is with your URL
Use the ResolveClientUrl() method
<%= ResolveUrl("~/Default.aspx/BuscaEquipe") %>
And you must Have [WebMethod] attribute before your static server function
[WebMethod]
public static string BuscaEquipe(int pIndex, int pLimite, int pUnidadeCE)
{
//Code
}
Your data:
var requestData= JSON.stringify({
pIndex: pIndex,
pLimite: 4,
pUnidadeCE: codigoEmitente
})
and then
data:requestData

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

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.

Parsing json synchronously from url in javascript

I'm trying to get title of a youtube video. So i'm using jQuery to parse json. But it works asynchronously, so the answer comes after the page loaded. The result is:
http://www.youtube.com/watch?v=Ym0hZG-zNOk (undefined)
How can i fix it?
Thanks.
http://jsfiddle.net/3vQht/
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
var link = "http://www.youtube.com/watch?v=Ym0hZG-zNOk";
var videoID = link.substring(link.indexOf("=") + 1, link.length);
document.writeln("<a target='_blank' href='" + link + "'>" + link.bold() + "</a> (" + name(videoID) + ")<br>");
function name(value) {
var source = "http://gdata.youtube.com/feeds/api/videos/" + value + "?v=2&prettyprint=true&alt=jsonc&callback=?";
var fin;
$.getJSON(source, function(json) {
fin = json.data.title;
console.log(fin);
});
return fin;
}
</script>
</head>
<body>
</body>
</html>
Hy,
here is the solution :)
<script type="text/javascript">
function name(value) {
var source = "http://gdata.youtube.com/feeds/api/videos/" + value + "?v=2&prettyprint=true&alt=jsonc";
$.ajax({
type: 'GET',
url: source,
contentType: "application/json",
dataType: 'json',
success: function (json) {
alert("here is the title: "+json.data.title+" .Use it how you want!");
},
error: function (e) {
alert("error");
}
});
}
$(document).ready(function() {
var link = "http://www.youtube.com/watch?v=Ym0hZG-zNOk";
var videoID = link.substring(link.indexOf("=") + 1, link.length);
name(videoID);
});
</script>
If you want to get your data sync just use this version:
$.ajax({
type: 'GET',
url: source,
async: false,
contentType: "application/json",
dataType: 'json',
success: function (json) {
alert("here is the title: "+json.data.title+" .Use it how you want!");
},
error: function (e) {
alert("error");
}
});
}
getJSON is asynchronous, so when the return fin; is reached, the data hasn't been fetched yet.
Everything that depends on the JSON MUST be inside the success callback.
If you prefere, you can also fetch your data synchronously. Check the jQuery.ajax() documentation for the async parameter.
EDIT: Just figured that you're loading your data using JSONP and that it's not possible to do that synchronously. You need to use asynchronous callbacks instead.
I haven't played with their api, but a quick look at
https://developers.google.com/youtube/2.0/developers_guide_json
indicates that they support jsonp callbacks so that you can prepend a script that does sends the data to a callback function (just add &callback=yourFunction to the end of the url)
function prependScriptFromUrl(s){
var a=document.createElement("script");
var b=document.getElementsByTagName('head')[0];
a.src=s;
b.insertBefore(a,b.firstChild)
}

Categories

Resources