Can't set new value for variable - javascript

I'm possibly missing something that is very obvious, but I'm not getting nowhere with this problem.
I'm simple trying to set a value of a variable after getting the value from a json feed.
I'm using jquery to get a jsonp feed and then store the value in a variable that I can use later, but its not working and the value doesn't get stored. If I console.log the value it returns it.
jQuery(document).ready(function($){
serverip = "<?php echo $_SERVER['SERVER_ADDR']; ?>";
stream_domain = "";
$.ajax({url: 'http://load.cache.is/inspired.php?ip=' + serverip, dataType:'jsonp',
success: function(data){
$.each(data, function(key, val) {
if (key == serverip){
stream_domain = val;
console.log("val: " + val);
}
});
}
});
console.log(stream_domain);
});
Here is the same code on jsfiddle.net

You are making an asynchronous request. So your code which appends the HTML execute before the success does which assigns the variable.
The code following the ajax request executes immidiatly after the request is made.
So if you require the response data then you should move your append code to be executed from the success method similar to this:
if (key == serverip){
stream_domain = val;
console.log("val: " + val);
$("<span>" + val + "</span>").appendTo(".json");
$("<span>" + stream_domain + "</span>").appendTo(".variable");
}
DEMO

The ajax call is asynchronous, so the timeline of the events is :
make ajax call
console.log
ajax call success, variable assign
Wait for the success event before using the variable. Here is your updated jsFiddle where I've added a function called in the success callback function:
function continueWorking(){
console.log(stream_domain);
$("<span>" + stream_domain + "</span>").appendTo(".variable");
}

Related

print alert box in response to a ajax call in yii2

I have this jquery code in my view file
$('#ticket-ticket_impact_id').change(function() {
var priority = $('#ticket-ticket_priority_id :selected').val();
var impact = $('#ticket-ticket_impact_id :selected').val();
if ($('#ticket-ticket_priority_id').val() == '' || $('#ticket-ticket_impact_id').val() == '') {
} else {
$.post('index.php?r=support/ticket/ajax-ticket-sla&ticket_priority_id=' + priority + '&ticket_impact_id=' + impact);
}
})
$('#ticket-ticket_priority_id').change(function() {
var priority = $('#ticket-ticket_priority_id :selected').val();
var impact = $('#ticket-ticket_impact_id :selected').val();
if ($('#ticket-ticket_priority_id').val() == '' || $('#ticket-ticket_impact_id').val() == '') {
} else {
$.post('index.php?r=support/ticket/ajax-ticket-sla&ticket_priority_id=' + priority + '&ticket_impact_id=' + impact);
}
})
from here the value the of priority and impact id is sent to the controller/ajax function
public function actionAjaxTicketSla(){
$ticket_priority_id=$_REQUEST['ticket_priority_id'];
//var_dump($ticket_priority_id);die();
$ticket_impact_id=$_REQUEST['ticket_impact_id'];
if(Sla::find()->where(['ticket_priority_id'=>$ticket_priority_id,'ticket_impact_id'=>$ticket_impact_id])->exists())
{
} else{
echo '<script type="text/javascript">alert("No sla defined!");</script>';
}
}
I am not able to even echo something in response here don't know whats wrong here any help would be appreciated.
response
You are mixing POST , GET and REQUEST
in ajax you use a POST but don't send nothins as POST param
instead you pass param in url as GET params
and in action you look for REQUEST but not for GET (or post)
And you access directly to the $_REQUEST instead of using yii2 method for this
You should rethink you code ..
anyway just as a first step
looking to your ajax call you could use the param you pass as get param
public function actionAjaxTicketSla(){
$request = Yii::$app->request;
$get = $request->get();
$ticket_priority_id=$get['ticket_priority_id'];
//var_dump($ticket_priority_id);die();
$ticket_impact_id=$get['ticket_impact_id'];
if(Sla::find()->where(['ticket_priority_id'=>$ticket_priority_id,'ticket_impact_id'=>$ticket_impact_id])->exists())
{
echo 'OK';
} else{
echo 'No sla defined';
}
}
and in client post
$.post('index.php?r=support/ticket/ajax-ticket-sla&ticket_priority_id=' +
priority + '&ticket_impact_id=' + impact,
function(data){
if (data !='OK') {
alert(data);
}
});
Try Echo in the If condition also and share the "response" (of page) from Network console.
Sending javascript code from the PHP server to js isn't a good practice. What you are doing is essentially making a call to the server and sending it the data and not doing anything with the resposne you've received.
Try to create a proper callback function like shown in this example,
Add a callback function (AJAX is Asynchronous, so your return is being hit before there is any data to return):
function returnData(param) {
console.log(param);
}
Now add that callback function as a parameter to your AJAX function, and lets run it:
function getCartProduct(id, callback){
$.post('sever.php',
function(data){
callback(data);
});
}
getCartProduct(id, returnData);
Also the server's response is treated as a string in javascript. To evaluate it as a javascript syntax, pass the string into the eval() method.
eval('alert("this works");');

Confused with javascript global variable scope and update

I am trying to get a specific piece of data from from a json source. I have declared a global variable and try to update the global variable but it doesn't update correctly. Also, the order in which my debug alerts run is confusing.
<script>
//global variable
var latestDoorStatus = "initialized value"; //set value for debugging purposes
//debug alert which also calls the function
alert("Alert#1: call getDoorStatus = " + getDoorStatus("***********"));
function getDoorStatus(public_key) {
//get data in json form
var cloud_url = 'https://data.sparkfun.com/output/';
// JSONP request
var jsonData = $.ajax({
url: cloud_url + public_key + '.json',
data: {page: 1},
dataType: 'jsonp',
}).done(function (results) {
var latest = results[0];
//debug alert
alert("Alert #2: latestDoorStatus = " + latestDoorStatus);
//update the global variable
latestDoorStatus = latest.doorstatus;
//debug alert
alert("Alert #3: latestDoorStatus = " + latestDoorStatus);
//return the global variable
return latestDoorStatus;
});
alert("Alert #4: latestDoorStatus = " + latestDoorStatus);
}
</script>
When I run this in my browser I get the following behaviors:
First I get alert#4 (supposed to run at END of the script) with the initialized value of the global variable
then I get alert#1 as "undefined". This is supposed to be the result of calling the function getDoorStatus which should return an updated value of latestDoorStatus
then I get alert #2 as the initialized value of latestDoorStatus which makes sense since the global variable has not yet been updated
then I get alert #3 with the correct value of latestDoorStatus
The function is supposed to return the variable latestDoorStatus AFTER alert #3 (i.e. after global variable has been updated correctly) so I don't understand why alert #1 (which is supposed to have the returned value) is coming back undefined and why alert#4 which is supposed to run at the very end of the script is running first.
You are calling $.ajax asynchronously, and passing a callback function to done.
function makeRequest() {
$.ajax({ // An async Ajax call.
url: cloud_url + public_key + '.json',
data: {page: 1},
dataType: 'jsonp',
}).done(function (results) {
// this code is executed only after the request to cloud_url is finished.
console.log("I print second.");
});
console.log("I print first.");
}
The callback is called when the request is finished, and when depends entirely on how long the request to https://data.sparkfun.com/output/ takes. So the code after your Ajax call is executed immediately, we're not waiting for the http request to finish.
Your function getDoorStatus returns nothing, but your callback passed to done does. The thing you need to know is that you can't return anything from asynchronously executed functions. Well, you can return, but there will be nothing there to use the returned value.
So instead, do the things you want to do with the returned data from https://data.sparkfun.com/output/ in the callback passed to done.
function getDoorStatus(public_key) {
//get data in json form
var cloud_url = 'https://data.sparkfun.com/output/';
// JSONP request
var jsonData = $.ajax({
url: cloud_url + public_key + '.json',
data: {page: 1},
dataType: 'jsonp',
}).done(function (results) {
// latestDoorStatus = results[0]; // Not a good practice.
// Instead:
showDoorStatus(results[0]);
});
}
function showDoorStatus(status) {
document.getElementById("door-status").innerText = status;
// Or something like this.
}
getDoorStatus("***********");
And somewhere in your HTML:
<p id="door-status"></p>
.done() will be called after the response of the AJAX request got received!
1) getDoorStatus() is called from inside alert() at top of code => #4 shown. It does not matter that the function is defined below and not above.
2) alert() at top of code is called & getDoorStatus() does not directly return a value => #1 shown with undefined.
3) AJAX response returned, .done() function gets called => #2 and #3 are shown.

how to use returned list in ajax call from controller

i am using ajax call to store the data in to DB and controller is returning the list of commentObject.
how can i access this list in JSP?
my ajax call is:
function StoreCommentAndRefreshCommentList(e) {
var commentData = document.getElementById(ActualCommentTextId).value;
$.ajax({
type : 'POST',
url : 'CommentStoreAndRetrieve',
data : "commentData=" + commentData + "&ImageId=" + commetTextButtonId[1],
success : function(commentList) {
//alert('comments stored successfully');
//alert('comment data is...'+res.CommentDataDoc[0]);
},
error : function(e) {
alert('Error: ' + e);
}
});
}
please let me know how can i access list data here.
function StoreCommentAndRefreshCommentList(e) {
var commentData = document.getElementById(ActualCommentTextId).value;
$.ajax({
type : 'POST',
url : 'CommentStoreAndRetrieve',
data : "commentData=" + commentData + "&ImageId=" + commetTextButtonId[1],
dataType : "xml",
success : function(commentList) {
alert($(commentList).text());
},
error : function(e) {
alert('Error: ' + e);
}
});
}
You can f.e. create <input type='hidden' id='someId'/> in your JSP and then in your success function you can assign data like $("#someId").val(...);
Another idea would be create JS variable inside JSP by putting <script>var myVar = ""</script>. Then in your succes function you can refer to such 'global' variable. Althogh, I believe that usual assignment (myVar = response.yourList) wouldn't work for a response object (which is the case in your problem). The solution would be to create an array var arr = [] and then in for loop you can push some done into it.
I got the solution.
i did used $.each(res, function (key, val) to iterate one by and built the tags dynamically using val field. here key holds the index position and val holds the corresponding object. then i did accessed one by one field by val.filedname(which we did create for pojo).
Thanks everyone.

Javascript Array loses data

I'm having trouble getting my information into an array in an ajax call, if I alert the information right after I insert it into the array it works fine, but if I do it at the end it alerts unidentified. I made sure that books is declared outside so it doesn't interfere.
var books = [];
$.ajax({
url: 'getFolderContents.php',
dataType: 'json',
success: function (data)
{
for(var i=0;i<data.length;i++) {
var amm = 0;
if(data[i].indexOf(".epub") !== -1) {
//$('#bTable').append("<td><a id = '" + data[i] + "' href = 'book.html'><img src = 'book.png' width = '100px'/><br/>" + data[i] + "</a></td>");
books.push(data[i]);
//alert(books[0]) Works if I call it from here, but not at the end.
}
}
},
error: function()
{
alert("error");
}
});
alert(books[0]);
Your
alert(books[0]);
will be executed while the Ajax call is running and therefore will not have any elements at this point of execution yet. Ajax is asynchronous - while you are doing a request to your PHP script your script continues execution.
Put all actions with books in your success function.
Another hint: As of jQuery version 1.8 you cannot longer use the parameter async: false to create a synchronous "A"jax call. You have to use the callback functions. Have a look at the docs for $.ajax
Your array hasn't lost any data; the data hasn't been put in there yet. The 'A' stands for "asynchronous", meaning your success callback hasn't run yet at the time you call the alert.
Put the alert inside your callback instead:
success: function (data)
{
for(var i=0;i<data.length;i++) {
var amm = 0;
if(data[i].indexOf(".epub") !== -1) {
//$('#bTable').append("<td><a id = '" + data[i] + "' href = 'book.html'><img src = 'book.png' width = '100px'/><br/>" + data[i] + "</a></td>");
books.push(data[i]);
//alert(books[0]) Works if I call it from here, but not at the end.
}
}
alert(books[0]);
},
Your alert is executing before the success function is called. Perhaps seeing the same code using a promise will make things clearer.
$.ajax( url: 'getFolderContents.php', dataType: "json" )
//the then function's first argument is the success handler
.then(function( data ) {
for(var i=0;i<data.length;i++) {
var amm = 0;
if(data[i].indexOf(".epub") !== -1) {
//$('#bTable').append("<td><a id = '" + data[i] + "' href = 'book.html'><img src = 'book.png' width = '100px'/><br/>" + data[i] + "</a></td>");
books.push(data[i]);
//alert(books[0]) Works if I call it from here, but not at the end.
}
alert(books[0]
});
});
I always feel this syntax makes async stuff make more sense. Otherwise this code functions exactly like Blazemonger's correct answer.
Your AJAX call is asynchronous, that's why it is undefined.
The alert at the end happens before the ajax success callback, because ajax is asynchronous.

js function calling another js function and returning a value problem

i have this JS function:
function ax_get_new_msg_cnt()
{ var mTimer;
var last_msg_id;
mTimer = setTimeout('ax_get_new_msg_cnt();',30000);
$.getJSON('/apps_dev.php/profile/newMessageCheck', function(data)
{
$('#newMessageDiv').text("You have " + data.msg_cnt + " new ");
last_msg_id = data.msg_id;
});
return last_msg_id;
}
then i have the js function where i call ax_get_new_msg_cnt():
function ax_get_new_msg_details()
{
var mTimer;
mTimer = setTimeout('ax_get_new_msg_details();',30000);
$.getJSON('/apps_dev.php/messagebox/newMessageDetails', function(data)
{
var str='<tr>';
str += "<td class='td_show_contact_item' align='left' id='td_date'>"+data.td_date+'</td>';
str += "<td align='left' id='td_subject'><a href='#' style='color:#ff0000 !important' class='spn_small_red_rbc'>"+data.td_subject+"</a></td>";
str += "<td class='td_show_contact_item' align='left' id='td_from'>"+data.td_from +"</td>";
//str += "<td id='block_url'>"+data.block_url+"</td>";
str +='<tr>';
var tbl = $('#td_date').parents('table');
var msg_id = ax_get_new_msg_cnt();
console.log(msg_id);
if (msg_id == data.td_id)
{
}
else
{
$(tbl).append(str);
}
});
}
in the above function i get msg_id as undefined...
can i do it the way i have it or is there another way please?
only if msg_id != data.td_id i want to do the append
thank you
You need to understand the asynchronous way of programming.
In your first method, when it gets called it starts an async JSON request to the webserver, which will return later in time, but your $.getJSON call return immediately, so your last_msg_id variable will be untouched and this untouched (undefined) variable will be returned by ax_get_new_msg_cnt function.
Later when the webserver returned with the answer and the answer is read by your browser it passes back to your callback function which sets the last_msg_id.
You can write console.log debug messages to see the timings:
if you insert a console.log('JSON start'); to your ax_get_new_msg_details method before the $.getJSON call
then one console.log('Response arrived'); to inside the function(data) part
and an another one right before the end with console.log('JSON request sent');
then, you'll probably see the way of executing.
What ever you want to do with msg_id you need to do it in $.getJSON callback function. You can not return it. The Ajax call is asyncron, so you have to wait till it is finished to get the value.
Because the $.getJSON() method is asynchronous, your ax_get_new_msg_cnt() function will return before the data is received, leaving last_msg_id as undefined.
Moreover, I think that the URL parameter for $.getJSON() should point to a file, not to a folder.
Note: you could improve your code by using the $.ajaxSetup method to set a default timeout for all your jQuery ajax requests.

Categories

Resources