Retrieve JS function value - javascript

I'm currently trying to retrieve a JS return value and I don't really know the reson why it doesn't work...
Hi hoper my code is the most easiest to read as possible, thanks in advance :
<script type="text/javascript">
function getValLocalSto(key, URL){
console.log(key);
console.log(URL);
var myKey = localStorage.getItem(key);
if(myKey == null){
// getting back JSON data
$.ajax({
url: URL,
dataType: 'json',
async: false,
success: function (json) {
var test;
console.log(JSON.stringify(json)); // the result is a well formed JSON string
localStorage.setItem(key,JSON.stringify(json));
myKey = localStorage.getItem(key);
test =jQuery.parseJSON(myKey);
console.log("My function result : "+test); // the result is a [object Object]
return test;
}
});
}else {
// Other work whatever
}
}
//call my function
console.log("sortie fonction : "+getValLocalSto("testJson", "do/profil")); // the result is "undefined"
var myuResult = getValLocalSto("testJson", "do/profil")); // the result is "undefined"
console.log(ff.prenom);
document.getElementById("myDiv").innerHTML="<div><input disabled='disabled' name='text-basic' id='text-basic' type= 'text' value='Votre nom "+ff.nom+"'/></div>";
document.getElementById("myDiv").innerHTML+="<div> <input disabled='disabled' name='text-basic' id='text-basic' type= 'text' value= 'Votre prenom "+ff.prenom+"'/></div>";
</script>
The solution :
function getValLocalSto(key, URL){
// do my stuff
});
}else {
// Other work whatever
}
return test;
}

Just declare test variable outside the ajax success function in the getValLocalSto outer function taking advantage of the variable scope. Else you would need a callback to return the variable from the ajax success function. Try this:
<script type="text/javascript">
function getValLocalSto(key, URL){
...
if(myKey == null){
// getting back JSON data
var test;
$.ajax({
url: URL,
dataType: 'json',
async: false,
success: function (json) {
console.log(JSON.stringify(json)); // the result is a well formed JSON string
localStorage.setItem(key,JSON.stringify(json));
myKey = localStorage.getItem(key);
test =jQuery.parseJSON(myKey);
console.log("My function result : "+test); // the result is a [object Object]
}
});
return test;
}else {
// Other work whatever
}
}
//call my function
console.log("sortie fonction : "+getValLocalSto("testJson", "do/profil")); // the result is "undefined"
...
</script>

You can pass a callback to AJAX.
Change function definition to:
function getValLocalSto(key, URL, callback){
...
$.ajax({
url: URL,
dataType: 'json',
async: false,
success: callback
});
...
in the code:
getValLocalSto("testJson", "do/profil", function(data) {
localStorage.setItem(key,JSON.stringify(data));
myKey = localStorage.getItem(key);
test = jQuery.parseJSON(myKey);
// here you work with test as you want as a result of getValLocalSto
});

Related

AJAX is not receiving data on success, it shows the result as "undefined"

This is jQuery code snippet is not getting valid data through AJAX and keeps updating data in divs as undefined. I don't know what the problem is.
function success(data) {
alert(data.amount);
$('#summary').html(data.count + "|" + data.amount);
};
$(document).ready(function () {
$("#button1").click(function (evt) {
evt.preventDefault();
var $form = $("#form1");
$.ajax({
type: $form.prop('method'),
url: $form.prop('action'),
data: $form.serialize() ,
datatype: "json",
tradition: true,
success: function(data) {
success(data);
}
});
});
});
If I modify following success function to simply load a new page that shows the correct results that Action returns
function success(data) {
$('#summary').html(data);
};
This is the controller action code snippet that receives the form fields data (id and quantity) from the view and returns count and amount:
public JsonResult AddtoCartDt(string id,string quantity)
{
int id2 = int.Parse(id);
Product pro = Data.Products.Single(c => c.Id == id2);
var cart = ShoppingCart_BusinessLayer.GetCart(this.HttpContext);
int l = int.Parse(quantity);
for (int i = 0; i < l; i++)
{
cart.AddToCart(pro);
}
var Cart = ShoppingCart_BusinessLayer.GetCart(this.HttpContext);
cartSummary summ = new cartSummary()
{
amount = Cart.GetTotal(),
count = Cart.GetCount()
};
return Json(summ, JsonRequestBehavior.AllowGet);
}
Your code looks fine, but you should add some debug statements to check the response.
For starters, you could pass the success method directly as your ajax success handler, and add an error handler to log out any error:
$.ajax({
type: $form.prop('method'),
url: $form.prop('action'),
data: $form.serialize() ,
datatype: "json",
traditional: true,
// no need for the function()...
success: success,
error: console.log
});
// Alternatively, you could chain it:
$.ajax(/*...*/).done(success).fail(console.log);
That will call pass the JSON response as your success method parameter.
Then, try to add a console.log() statement to debug the response in the console:
function success(data) {
console.log(data);
$('#summary').html(data.count + "|" + data.amount);
};
Edit
Check the tradition parameters in your ajax call. In the doc it's called traditional.
Also, check the route name and http method in your controler.
You may want to add something like this in your controller:
[Route("~/myroute"), HttpPost]
public JsonResult AddtoCartDt(string id,string quantity)
{
/*
*/
}

assigning a value from a ajax request in jquery

I have the following piece of jquery code
var test = "test";
$.ajax({
url: root + "/servletPath",
type: "GET",
success: function (text) {
alert(text); // returns the right value
test = text;
},
error: function () {
}
});
// prints "test" and not the value that should be assigned in the success function
alert(test)
You're alerting the variable test before the value has been assigned. $.ajax is asynchronous by default.
Possible Solution:
var test = "test";
$.ajax({
url: root + "/servletPath",
type: "GET",
success: function (text) {
test = text;
alertTest();
},
error: function () {
}
});
function alertTest(){
alert(test);
};
You could also set the async property to false on the $.ajax method, to run the code synchronously.

key in object returning undefind after AJAX call

I am doing an Ajax request on an XML file and mapping the XML into a JavaScript object my problem is that am logging the object and seeing the values I won't but when I try to return the values I keep getting undefined, even that all the code is inside the success callback of the AJAX request, my code is as bellow:
// Errors Object
var ErrorsObject = {};
var ErrorApplet = $('.AppletStyle1 table td');
// Ajax Request
$.ajax({
type: "GET",
url: "ECA_ADMIN_IO.xml",
dataType: "xml",
cache: false,
success: function (xml) {
$(xml).find('EcaAdminBc').each(function () {
var code = $(this).find('code').text();
var msg = $(this).find('msg').text();
ErrorsObject[code] = msg;
});
// Reformat Errors
if(ErrorApplet.length > 0) {
$(ErrorApplet).each(function(){
var Error = $(this).text();
if(Error.indexOf("SBL") >= 0){
var ErrorCode = Error.split('(')[1].replace(")","");
var ErrorText = ErrorsObject[ErrorCode];
// The Log is showing the values correctly but i cant access the object values
console.log(ErrorsObject);
// ErrorText And ErrorCode Are always undefined !!
if(typeof ErrorText != 'undefined'){
$(this).text(ErrorText);
}
}
});
}
}
});
I need additional context, but I guess what the problem is. You are trying to do some thing like this:
var myFunction = function(){
// Error Object
var ErrorsObject = {};
var ErrorApplet = $('.AppletStyle1 table td');
$.ajax(
type: "GET",
url: "ECA_ADMIN_IO.xml",
dataType: "xml",
cache: false,
success: function (xml) {
//using response to fill ErrorsObject
ErrorsObject['Ok'] = 'This key has Value!';
//more awesome code here
//... lets check again:
console.log(ErrorsObject['OK']); //Outputs 'This key has Value!'
}
);
return ErrorsObject;
};
var myAwesomeErrorObject = myFunction();
console.log(myAwesomeErrorObject['OK']); //undefined!
console.log(myAwesomeErrorObject); //Empty object!
The problem is that myFunction finished before the success callback function gets executed (the callback is asynchronous). That is why logging myAwesomeErrorObject['OK'] shows undefined. I guess that you also tried return ErrorsObject inside the success callback, but that won't work either.
In order to fix your code you must either:
Use the ErrorsObject inside the success callback (i.e. don't return it).
Call a second function from inside the success callback, passing it the ErrorsObject.
Pass a calback function to myfunction and execute it from inside the success callback.

return ajax.done data gives error on jquery

I have data in my ajax.done and it bugs on jquery.
i googled on it and cant find anything.
what to do?
function select_aragement(arragament){
var arrst = arragament;
var arrsplit = arrst.split("|");
var periode = arrsplit[0];
var id = arrsplit[1];
var postsjson;
var test= $.ajax({
type: 'POST',
async: true,
url: 'ajax/prijzen.php',
data: { id: id, periode: periode },
dataType: 'json'
}).done(function (vis) {
console.log(vis);
postsjson = $.parseJSON(vis);
});
return postsjson;
}
You shouldn't be attempting to return anything from a callback function because the returned value doesn't go anywhere meaningful. Instead you simply use the response from the AJAX request inside that callback function.
Let's say you have this code:
function bar() {
var myObject = foo();
// do something with myObject
}
function foo() {
var bar; // 1
var xhr = $.ajax({
url: yourUrl,
dataType: 'json',
type: 'post',
data: {
some: 'data'
}
}); // 2
xhr.done(function(yourObject) {
bar = yourObject; // 5
}); // 3
return bar; // 4
}
bar();
The comments inside the foo function indicate the order in which those statements execute. So you declare a variable bar, declare a variable xhr that has a Deferred object, attach a done handler to it with a callback function, return the value of bar, then the value of bar is set (too late - you've already tried to return it).
Inside of your execution of the bar function myObject is going to be undefined, because the value of bar inside the foo function wasn't set before the return statement. What you need to do is simply move the // do something with myObject code to the callback function, and use bar there:
function foo() {
var xhr = $.ajax({
url: yourUrl,
dataType: 'json',
type: 'post',
data: {
some: 'data'
}
}); // 1
xhr.done(function(yourObject) {
var bar = yourObject; // 4
// do something with bar
}); // 2
// 3 - function execution has finished
}
You might want to move the return line inside the done section
}).done(function (vis) {
console.log(vis);
postsjson = $.parseJSON(vis);
return postsjson;
});
but keep in mind that, being an asynchonous call, so will be your return. My advise would be to pass in a callback.
function select_aragement(arragament, callback){
var arrst = arragament;
var arrsplit = arrst.split("|");
var periode = arrsplit[0];
var id = arrsplit[1];
var postsjson;
var test= $.ajax({
type: 'POST',
async: true,
url: 'ajax/prijzen.php',
data: { id: id, periode: periode },
dataType: 'json'
});
test.done(function (vis) {
console.log(vis);
postsjson = $.parseJSON(vis);
callback && callback(postjson);
});
}
And modify your code to use the callback instead of the returned value.
before
var postjson=select_aragement(arragament);
...stuff with postjson...
after
select_aragement(arragament, function(postjson) {
...stuff with postjson...
});
You are trying to make the ajax call fire synchronously, for that you need to make the async property false.
async: false,
The problem :
Look at the following code :
function getValue(){
var value = 0;
setTimeout(function(){
value = 42;
}, 1000);
return value;
}
What is the returned value ?
fiddle
This is your exact same problem with
function select_aragement(arragament){
var postjson;
$.ajax(...).done(function(vis){
postjson = vis;
});
return postjson;
}
A solution :
I imagine you use your function in the following way :
var data = select_aragement(arragament);
// do something with data :
$.each(data, function(){
....
});
You can change select_aragement's code like this :
function select_aragement(arragament){
var arrst = arragament;
var arrsplit = arrst.split("|");
var periode = arrsplit[0];
var id = arrsplit[1];
var test = $.ajax({
type: 'POST',
async: true,
url: 'ajax/prijzen.php',
data: { id: id, periode: periode },
dataType: 'json'
});
// return the promise which wraps the ajax call
return test;
}
and the calling code like this :
// "p" stands for "promise"
var p = function select_aragement(arragament);
p.done(function(data){
// do something with data :
$.each(data, function(){
....
});
});
or without the local variable :
select_aragement(arragament).done(function(data){
// do something with data :
$.each(data, function(){
....
});
});
In this case you can use async/await mixed to .done from jQuery like this:
async function myasyncfunction(myArgs){
var response = [];
var req = $.ajax({
method: "GET",
url: resquestURL,
dataType: "json",
})
await req.done( res => {
//DO some stuff with your data
for (let index = 0; index < res.length; index++) {
const element = res[index];
response .push( "some stuff" + element );
}
})
return response;
}

How can I return a variable from a $.getJSON function

I want to return StudentId to use elsewhere outside of the scope of the $.getJSON()
j.getJSON(url, data, function(result)
{
var studentId = result.Something;
});
//use studentId here
I would imagine this has to do with scoping, but it doesn't seem to work the same way c# does
it doesn't seem to work the same way
c# does
To accomplish scoping similar to C#, disable async operations and set dataType to json:
var mydata = [];
$.ajax({
url: 'data.php',
async: false,
dataType: 'json',
success: function (json) {
mydata = json.whatever;
}
});
alert(mydata); // has value of json.whatever
Yeah, my previous answer does not work because I didn't pay any attention to your code. :)
The problem is that the anonymous function is a callback function - i.e. getJSON is an async operation that will return at some indeterminate point in time, so even if the scope of the variable were outside of that anonymous function (i.e. a closure), it would not have the value you would think it should:
var studentId = null;
j.getJSON(url, data, function(result)
{
studentId = result.Something;
});
// studentId is still null right here, because this line
// executes before the line that sets its value to result.Something
Any code that you want to execute with the value of studentId set by the getJSON call needs to happen either within that callback function or after the callback executes.
Even simpler than all the above. As explained earlier $.getJSON executes async which causes the problem. Instead of refactoring all your code to the $.ajax method just insert the following in the top of your main .js file to disable the async behaviour:
$.ajaxSetup({
async: false
});
good luck!
If you wish delegate to other functions you can also extend jquery with the $.fn. notation like so:
var this.studentId = null;
$.getJSON(url, data,
function(result){
$.fn.delegateJSONResult(result.Something);
}
);
$.fn.delegateJSONResult = function(something){
this.studentId = something;
}
var context;
$.ajax({
url: 'file.json',
async: false,
dataType: 'json',
success: function (json) {
assignVariable(json);
}
});
function assignVariable(data) {
context = data;
}
alert(context);
hmm, if you've serialized an object with the StudentId property then I think that it will be:
var studentId;
function(json) {
if (json.length > 0)
studentId = json[0].StudentId;
}
But if you're just returning the StudentId itself maybe it's:
var studentId;
function(json) {
if (json.length > 0)
studentId = json[0];
}
Edit: Or maybe .length isn't even required (I've only returned generic collections in JSON).
Edit #2, this works, I just tested:
var studentId;
jQuery.getJSON(url, data, function(json) {
if (json)
studentId = json;
});
Edit #3, here's the actual JS I used:
$.ajax({
type: "POST",
url: pageName + "/GetStudentTest",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{id: '" + someId + "'}",
success: function(json) {
alert(json);
}
});
And in the aspx.vb:
<System.Web.Services.WebMethod()> _
<System.Web.Script.Services.ScriptMethod()> _
Public Shared Function GetStudentTest(ByVal id As String) As Integer
Return 42
End Function

Categories

Resources