check if ajaxcall has been made in ie7 - javascript

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

Related

Calling ajax request continually until a certain search request is found

I am trying to keep sending AJAX GET requests to a certain page that inputs from a cgi script until a specific set of keystrokes shows up.
However, my requests aren't coming up continuously, in fact they aren't even taking place when I am using a function and trying to call the function. I had to use the complete with the success, because for whatever reason, with the success I could not properly store the value retrieved.
Here is what I have:
function posts() {
$.ajax({
type: "GET",
url: 'http://checkvaluestatus.sh',
success: function(data) {
alert(data_response.responseText);
},
complete: function(data_response) {
alert(data_response.responseText);
var viewport = data_response.responseText;
var version = viewport.match(/Release:[^=]*/);
if (version != null) {
console.log(version);
} else {
posts();
}
},
error: function() {
console.log('failed');
posts(); //calling the ajax again.
}
});
Is there not a way to keep sending requests based on a condition being met and having the value still stored?
This is my AJAX call that worked to print the value:
$.ajax({
url: 'http://checkvaluestatus.sh',
type: "GET",
dataType: "json",
success: function(data) {
alert(data_response.responseText);
},
complete: function(data_response) {
alert(data_response.responseText);
var viewport = data_response.responseText;
var version = viewport.match(/Release:[^=]*/);
document.write(version);
},
});
salam,
the value you are looking for in success function is the 'data' ,not "data_response.responseText" because in "success" function data is your response text ,but in the "complete" function "data_response" is a jqXHR object contain more information.
to print your text in success function replace
alert(data_response.responseText);
by
alert(data);
for more details "jquery.ajax"

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.

Eror 500 with ajax and codeigniter

I have a problem with calling ajax on my view on codeigniter website. Ajax is calling method in controller on same project.
I have ajax search, which is work correctly. When I chose one of results, he open a new tab and show me a detail information from database. In some cases when I click on some results(I didn't find rule when it will be happening), ajax return me a 500 error, without go into controller method, but when I refresh the page (F5) he shows me a correct result. Did someone have a same problem, or can help me to fix it?
Here is my ajax call:
<script>
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '<?=site_url('index/ajax_read_details')?>',
dataType: 'json',
cache: false,
async:true,
data: {'param':'<?=$selected?>'},
beforeSend: function (xhr) {
$('#loading').show();
},
success: function (data) {
$('#loading').hide();
var details = '<tr>' +
'<td>'+data['title']+'</td> '+
'<td>'+data['code']+'</td>' +
'</tr>';
$('#data >tbody').append(details);
})
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: '+ errorThrown);
}
});
});
</script>
I know now that he didn't go into controller method "ajax_read_details" in index controller in case when it give me an 500 error.But when I refresh, he go into that method and do it correctly job. In both cases, he send a same values but in first he didn't return values, after refresh page he give me a values :(
Short controller method is:
public function ajax_read_details()
{
$param = $this->input->post('param');
echo json_encode(array('title' => $param, 'code'=>param));
}

Cant seem to set global vars correctly

I am trying to store a token into a global var. When the alert is run it says null, but if I put 2 alerts one after the other the 1st shows null but the second shows the token.
Its like the token is not being set because the 1st alert is run before the ajax request has finished.
Does anyone have any ideas on what I am doing wrong?
var csrf_token = null;
$(document).ready(function(){
get_csrf_token();
alert('token 1 '+csrf_token);
alert('token 2 '+csrf_token);
});
function get_csrf_token()
{
$.ajax({
type: "GET",
url: "http://buscore/index.php/includes/csrf_token/",
dataType: "json",
success: function(resp, status) {
if (resp.status != 'success')
{
alert('Error - Update CSRF Token\n\n' + resp.status);
return;
}
csrf_token = resp.csrf_token;
}
});
}
Thanks
UPDATED
Ok thanks for your help everyone but still dont see how this would work. I use get_csrf_token() like jqgrid to send the token with the request like below. So how do I pass the token to and have it working?
beforeRequest: function (){
get_csrf_token()
//alert(csrf_token);
$("#customer_grid").setPostDataItem('<?php echo $csrf_token_name; ?>', csrf_token);
}
The success callback function runs when the HTTP response arrives.
In your test, the response is arriving between the time that the first alert is displayed and the time you click the button to let the script continue.
Do whatever you need to do with the data in the callback, not as the statement after the one where you initiate the Ajax request.
Example as requested by comment:
$(document).ready(function(){
get_csrf_token();
});
function get_csrf_token()
{
$.ajax({
type: "GET",
url: "http://buscore/index.php/includes/csrf_token/",
dataType: "json",
success: function(resp, status) {
if (resp.status != 'success')
{
alert('Error - Update CSRF Token\n\n' + resp.status);
return;
}
alert('token 1 '+csrf_token);
alert('token 2 '+csrf_token);
}
});
}
The A in AJAX stands for 'asynchronous'. While you are busy clicking on the first alert, the AJAX request is going through and the value is filled. You will need to place all code that needs the variable csrf_token into your callback function. Alternatively, you can look into using jQuery 1.5 or above (if you aren't already). It has so-called Deferred Objects
This API allows you to work with return values that may not be immediately present (such as the return result from an asynchronous Ajax request).
You can also set the async value on your post request tofalse, like this:
$.ajax({
type: "GET",
async: false,
url: "http://buscore/index.php/includes/csrf_token/",
dataType: "json",
success: function(resp, status) {
if (resp.status != 'success')
{
alert('Error - Update CSRF Token\n\n' + resp.status);
return;
}
csrf_token = resp.csrf_token;
}
});
This will make the browser wait for the response before proceeding with the rest of your code. I wouldn't necessarily recommend it, but it should work.
The AJAX request is async. That means the script doesn't wait for it to finish. When the first alert fires the token is not set. But until you hit OK it has time to load and the token will be set.
Here's the order of the operations:
call get_csrf_token
make token request
show alert 1
finish request and set csrf_token
client hits OK on the first alert
show alert 2 (the token variable was set at 4.)

How do I reload the page after all ajax calls complete?

The first time a user is visiting my website, I am pulling a lot of information from various sources using a couple of ajax calls. How do I reload the page once the ajax calls are done?
if(userVisit != 1) {
// First time visitor
populateData();
}
function populateData() {
$.ajax({
url: "server.php",
data: "action=prepare&myid=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
_id = response[json].id;
getInformation(_id);
}
});
}
function getInformation(id) {
$.ajax({
url: "REMOTESERVICE",
data: "action=get&id=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
$.ajax({
url: "server.php",
data: "action=update&myid=" + id + '&data=' + json.data.toString(),
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
}
});
}
});
}
So what the code does is, it gets a list of predefined identifiers for a new user (populateData function) and uses them to get more information from a thirdparty service (getInformation function). This getInformation function queries a third party server and once the server returns some data, it sends that data to my server through another ajax call. Now what I need is a way to figure out when all the ajax calls have been completed so that I can reload the page. Any suggestions?
In your getInformation() call you can call location.reload() in your success callback, like this:
success: function(json) {
if(!json.error) location.reload(true);
}
To wait until any further ajax calls complete, you can use the ajaxStop event, like this:
success: function(json) {
if(json.error) return;
//fire off other ajax calls
$(document).ajaxStop(function() { location.reload(true); });
}
.ajaxStop() works fine to me, page is reloaded after all ajax calls.
You can use as the following example :
$( document ).ajaxStop(function() {
window.location = window.location;
});
How it's works?
A: Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the ajaxStop event.
Hope help y'all, furthermore information, I'm sharing the link of the documentation following.
source: https://api.jquery.com/ajaxstop/
You could just redirect to the same page in the server.php file where the function is defined using a header('Location: html-page');
//document.location.reload(true);
window.location = window.location;
See more at: http://www.dotnetfunda.com/forums/show/17887/issue-in-ie-11-when-i-try-to-refresh-my-parent-page-from-the-popupwind#sthash.gZEB8QV0.dpuf

Categories

Resources