$.getJSON with in a foreach Loop over all input fields - javascript

i have a quick question. I want to iterate over all checked checkboxes and parse the json files for the checked ones.
Here is my problem: The $().each function is synchronous and the $.getJSON() function is asynchronous. So i know i would have to pause the exectuion of the each() loop until the JSON File is parsed. How can i pause the loop? Or any other ideas solving this problem?
Thank you very much.
$("input:checkbox[name=check]:checked").each(function()
{
$.getJSON( $(this).val(), function( data ) {
//Do smth.
//Pause the each loop?
}).error(function(jqXhr, textStatus, error) {
alert("ERROR: " + textStatus + ", " + error);
});
});
alert("foo"); //<-- gets executed before all json files are parsed.

If you want to make the AJAX request synchronouse, pass async config as false.
$.ajax({
dataType: "json",
url: 'your URL',
async: false,
success: success
});
Documentation

Related

How to run php function after js append

I append a value from my .js file like so
elemscore.append("You Scored: " + score);
I then need to access database records based on the score. How can I achieve this after the append
You can perform an ajax request something like this.
var url = 'http://localhost/phalcon3/blog?month='+pmonth+'&
$.ajax({
type:"POST",
url: url
data: {postVar1:"value",postVar2:"second value"},
success: function(result){
// either do something with whats returned or call another jquery function
console.log(result);
},
error: function(){
// error reporting/handling
}
});

Bing Maps REST - Javascript

I am a beginner with JavaScript and I am facing some issues with parsing JSON and display the data I want to.
When I run the URL manualy in browser I get a correct result back.
The JavaScript code looks like this:
request = "URL"
function CallRestService(request, callback) {
$.ajax({
url: request,
dataType: "jsonp",
jsonp: "jsonp",
success: function (r) {
callback(r);
var results = data.resourceSets;
console.log(r.message);
alert(r.statusText);
},
error: function (e) {
alert("Error" + JSON.stringify(e));
console.log("Error" + e.message);
}
});
}
When I run this code I get no error in the console but I still get an alert via the error function: "status":200,"statusText":"OK"
Why do I get this?
And thats why I cannot get my data displayed, what I am doing wrong?
EDIT
so I was able to make a working code out of it, but I still get messages from SUCCESS and ERROR at the same time and I also get my data back?!
<script>
var request = "URL";
function CallRestService(request, callback) {
$.ajax({
url: request,
dataType: "jsonp",
jsonp: "jsonp",
success: function (r) {
callback(r);
console.log("working" + r.message);
alert(r.statusText);
},
error: function (e) {
alert("Error" + e.message + JSON.stringify(e));
console.log("message: " + e.message);
console.log("readyState: " + e.readyState);
console.log("responseText: "+ e.responseText);
console.log("status: " + e.status);
}
});
}
CallRestService(request, GeocodeCallback);
function GeocodeCallback(results) {
console.log(results.resourceSets[0].resources[0].travelDurationTraffic);
document.getElementById("sec").innerHTML=Math.round((parseFloat(results.resourceSets[0].resources[0].travelDurationTraffic) / 60));
}
</script>
Assuming that you put an actually URL into the request parameter this looks fine. A 200 status means it was successful and this likely called the console from your success function. I know you said you removed it to be sure, but the page could of been cached. If you take a look at the network request you will likely see that it was successful as well. Ifs possible that an error in your success function is occurring and triggering the error function. Have you tried adding break points inside of the two functions?
Here is a blog post that shows how to access the Bing Maps REST services using jQuery and other frameworks: https://blogs.bing.com/maps/2015/03/05/accessing-the-bing-maps-rest-services-from-various-javascript-frameworks/ It looks like your code is very similar.

Make javascript execute linearly

I am building a game. When a piece is moved ('.draggable'), I need make the first ajax call (to move_script.php) which will validate the move and then save it in a database. After that is done, I want to run the second ajax call (to past_moves.php) and query the database and write out the new move.
My problem, is that sometimes the second ajax calls pulls out the results BEFORE the current move is there. I've used microtime(); in the php code to see what is happening, and every time that the most recent result isn't pulled, the second ajax script is completing first. (Most of the time the most recent result comes out, but every so often it won't, it seems to be randomly, every 5 - 15 times or so).
How can I ensure that the second ajax call won't run until the first one is done?
Thank you
code:
<script>
$(function() {
$( ".draggable" ).draggable({
stop: function(event, ui) {
var start = $(this).attr('id')
//ajax call number 1
$.ajax({
type: "POST",
url: "../move_script.php",
data: { start: start }
}).done(function( msg ) {
//alert( "Data Saved: " + msg );
$("#chessboard").html(msg);
});
//ajax call number 2
$.ajax({
type: "POST",
url: "../past_moves.php",
data: {}
}).done(function( moves ) {
$("#past_moves").html( moves );
});
}
});
});
</script>
Nest the ajax calls
//ajax call number 1
$.ajax({
type: "POST",
url: "../move_script.php",
data: { start: start }
}).done(function( msg ) {
//alert( "Data Saved: " + msg );
$("#chessboard").html(msg);
//ajax call number 2
$.ajax({
type: "POST",
url: "../past_moves.php",
data: {}
}).done(function( moves ) {
$("#past_moves").html( moves );
});
});
});
This nesting will force the second call to wait until the first has completed.
Put the second ajax call in the callback of the first ajax call to make sure it only executes after it is complete. Otherwise, since ajax is asynchronous, it starts the request and then keeps going (in this case, starting the second ajax). I'm not familiar with the "done" method - maybe you can put it in that function that you already have. Otherwise, this is the syntax I'm familiar with:
$.ajax({
type: "POST",
url: "../move_script.php",
data: { start: start },
success: function(data){
//data is whatever the ajax returns. is it msg in this case?
//put second ajax call here
},
error: function(jqXHR, textStatus, errorThrown){
//might not need here, but this is example of callback which will be executed instead of success if server returns an error
},
complete: function(jqXHR, textStatus){
//another useful callback to know about - will execute after success or error
}
})
https://api.jquery.com/jQuery.ajax/

Why isn't this jquery.get function working?

I've been trying to create a small page and all it does is update some values from a source document. The page loads fine, but I don't get the results from the requested source. The .fail function runs, but the textStatus and errorThrown values don't appear in the alert() window that pops up.
I'm very new to javascript and jquery. I'm trying to bash this together with pieces found from the web to figure it out but nothing seems to be working. Mainly, it's the response I think I'm falling down on...
Anyway, here's the code:
<html>
<head>
<title></title>
<script type="text/javascript" src="~/Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
function update() {
$.ajax({
type: "GET",
url: "http://192.168.2.86:15890/linearlist.xml",
dataType: "xml"
}).done(function (res) {
//alert(res);
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("AJAX call failed: " + textStatus + ", " + errorThrown);
});
}
function GetData() {
update();
setTimeout(function () {
GetData();
}, 50);
}
});
</script>
</head>
<body>
<script type="text/javascript">
GetData();
</script>
<div class="result"> result div</div>
</body>
</html>
UPDATE:
I've update my code re: #Ian's answer. It's still not working, sadly. I'm not getting the textStatus or errorThrown results either. I've tried debugging with Internet Explorer through VS2012 but it's not getting me far. If I put the URL into a webpage, I can view the XML document.
$.get does not accept one parameter as an object literal; it accepts several: http://api.jquery.com/jQuery.get/#jQuery-get1
You might be thinking of the $.ajax syntax: http://api.jquery.com/jQuery.ajax/
Anyways, call it like:
$.get("http://192.168.2.86:15890//onair.status.xml", {}, function (res) {
var xml;
var tmp;
if (typeof res == "string") {
tmp = "<root>" + res + "</root>";
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(res);
} else {
xml = res;
}
alert("Success!");
}, "text");
Or use $.ajax:
$.ajax({
type: "GET",
url: "http://192.168.2.86:15890//onair.status.xml",
dataType: "text"
}).done(function (res) {
// Your `success` code
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("AJAX call failed: " + textStatus + ", " + errorThrown);
});
Using the fail method, you can see that an error occurred and some details why.
Depending on what/where http://192.168.2.86:15890 is, you may not be able to make AJAX calls due to the same origin policy - https://developer.mozilla.org/en-US/docs/JavaScript/Same_origin_policy_for_JavaScript
I know you have some logic in your success callback, but I'm pretty sure if you specify the dataType as "text", the res variable will always be a string. So your if/else shouldn't really do much - the else should never execute. Either way, if you're expecting XML, it's probably easier to just specify the dataType as "xml".

check if ajaxcall has been made in ie7

I have an ajax call in my document ready function. But in about 1 out of 10 times in ie7, the ajax function doesnt get called at all.
Is there a way to check if the ajax call has been made, otherwise run it again until it either runs in to the error or success functions? The problem only occurs when i run the page in ietester -> ie7 mode. Thanks
code: http://jsfiddle.net/jxEj5/
You could setup a variable as a monitor, and a timer to issue an ajax call every 5 seconds until the ajaxCall is finished.
The monitor is set through var gotAjax = false and when the Ajax is succeeded, it is set to true gotAjax = true.
Instead of call the $ajax directly, you set a time clock through setTimeout(ajaxCall, 5000). With in the timer, if the ajaxCall is set, you clear the timer through clearTimeout(ajaxCall)
$(function() {
var gotAjax = false;
var ajaxCall = function () {
if (!gotAjax) {
$.ajax({
url: '../SentinelOperationsUI/GenericHandler.ashx',
dataType: 'json',
data: {
'FunctionName': 'GetActivity',
'SearchType': 'Single',
'postedData': JSON.stringify($('#content').data('postedData'))
},
success: function(data) {
gotAjax = true;
$('#content').data('activityKey', data.SENTINEL_OPERATION_ACTIVITY_KEY);
$.ajax({
url: '../SentinelOperationsUI/ajax/activityviews/' + data.ACTIVITY_VIEW,
dataType: 'html',
success: function(data) {
$('#content').hide().html(data).fadeIn(200);
$('#parenttabs, #tabs, #tabs2, #parenttab-1, #parenttab-2').tabs();
}
});
}
});
}
else {
clearTimeout(ajaxCall);
}
};
setTimeout(ajaxCall, 5000);
});
This is an example in jQuery that should help you debug it
If you're not using jQuery, i will need to see your code :)
The error function will occur in case a 404 or similar error occurred, and in case the ajax DID occur but some unexpected response was returned and your javascript bugged, the try .. catch will help you detect the error more easily :)
$.ajax({
url: "file.php",
type : "POST",
contentType : "application/x-www-form-urlencoded",
success: function(response){
try{
// Success code
}catch(e){
// Possibly you have an error in your JS, this should alert it to you
alert(e.message);
}
},
error : function(jqXHR, textStatus, errorThrown){
// Error occured, lets see what's wrong
alert("error " + textStatus + ": " + errorThrown);
}
});

Categories

Resources