Refreshing data in a div with ajax - ajax

I'm developing a Phonegap based app which shows some data that is stored in a remote server. How can I make it refresh data every certain time in case an error happened and it didn't get the data the first time?
this is the list.js
$(document).ready(function(){
var output = $('#vehiculosOutput');
$.ajax({
url: 'http://www.periodicosonofertas.com/mobile/conexVehiculos.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var landmark = '<li>'+item.name + '<p></p>'
+ '<p><font style="white-space:normal; font-size: small" >'+item.descripcion+'</p>' + '<p>'+item.contacto+'</p>' + '<p>'+item.telefono+'</p>' + '<p>'+item.correo+'</p><p>'+status+'</p></li>';
output.append(landmark);
});
},
error: function(){
output.text('Error');
//setTimeout(func.updateStatus, 1000);
}
});
});

You can use long polling for this. In case if you haven't heard about it, this is a good place to start.
If you need to resend the request only in error case, the following snippet would work.
(function poll(delay){
setTimeout(function(){
$.ajax({
url: "http://127.0.0.1:8000/time/",
success: function(data){
$('#requiredDivId').text(data.value);
},
error: function(data){
//Recursive **Poll**
poll(30000);
},
dataType: "json"
});
}, delay);
})(0);

If you want to go with specific feature you mentioned in your comment then there is a function named network.isReachable(You can find more details here) in phonegap. You can put that function to check whether connection is on or not within settimeout function and if its true then you can run function to send data to server.
I hope it'll help you

Related

Variable loses some value when used in Ajax API Call

I have an issue that causes my variable “tempid” to lose some of its values when put into the second API call. As you can see from my image, if I log the variable to console (console.log(tempid)) it shows just fine. However, as soon as I place it in an API call it has some of the value but not all. Could you please help me by explaining why this would happen?
[console example][1]
$(document).ready(function() {
$.ajax({
url: "/api/Template/GetTemplates?classId=7ac62bd4-8fce-a150-3b40-16a39a61383d",
async:true,
dataType: 'json',
success: function(data) {
$(data).each(function (data) {
if (this.Name === "Name of Template"){
var tempid = this.Id
console.log (tempid)
var tempurl = "/api/V3/Projection/CreateProjectionByTemplate?id=" + tempid + "&createdById=703853d4-ffc4-fce3-3034-0b838d40c385"
$.ajax({
url: tempurl,
async: false,
dataType: 'json',
success: function(data) {
}
});
}
});
}
});
})
[1]: https://i.stack.imgur.com/gyesK.png
I found the answer, the console is just showing a shortened version of the URL and happened to cut off part of the tempid. Thank you

JQuery Ajax call often not working on Safari 6

My Ajax call is really simple as below:
function ajax(reqUrl, params , callback) {
console.log("Request URL "+reqUrl);
var cond;
cond = $.ajax({
type: 'post',
url: reqUrl,
data: params,
error:function(){ alert("some error occurred") },
success: callback
});
console.log("Server response "+cond.readyState);
}
// Call it as
var url = "/getResult";
var params = {};
params.param1 = "test1";
params.param2 = "test2";
ajax(url, params, function(returnCallback) {
console.log(returnCallback);
alert("Success");
});
That works fine in most cases. But sometimes (about 1 times in 3) it doesn't return anything to callback.
I found many questions and answers for Not working ajax in Safari but fine in chrome and FireFox. My problem is different from them, because it's fine most of the time (I don't mean it was not fine usually because when I refresh my browser, that may cause my ajax call to work).
My main question is why does my ajax call sometimes fail? I don't get any errors on my JS console. When this situation, I refresh my browser to get my ajax call to. Any Ideas?
Update:
I found that sometimes my ajax call method didn't call out because console.log("Request URL "+reqUrl); did not execute. When I don't want to refresh my browser, I clicked many times on my page's link to produce result. will something late to execute?
Finally, I found error .. Safari doesn't reload my JavaScript files again even disable Cache. So I put all of my JS code into:
$(document).ready(function(){
// start load my js functions
init();
});
to reload my JS files when my page was ready. Cheer !
I also met this problem.
When I moved all code into $(function() {}), it worked.
After that, I found I had defined a variable named key, which caused the problem.
Just rename it, all things will be running.
This seems to be a Safari issue. In this post there is a suggestion to add a beforeSend to your ajax-request.
In your case:
cond = $.ajax({
type: 'post',
url: reqUrl,
data: params,
beforeSend: function (event, files, index, xhr, handler, callBack) {
$.ajax({
async: false,
url: 'closeconnection.php' // add path
});
},
error:function(){ alert("some error occurred") },
success: callback
});
Please Test below Code. it is working fine.
$.ajax({
type: "POST",
url:'#Url.Action("getResult","Controller")',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data) {
alert("here" + data.toString());
});
This is use for MVC application.
$.ajax({
type: "POST",
url:'getResult',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("here" + data.toString());
});
For Asp.net Application :
$.ajax({
type: "POST",
url:'getResult',
data: "{userName :'" + userName + "',password :'" + password + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("here" + data.toString());
});
if u have still the issue than please post ur complete code here. i will test and reply soon

Pinterest Ajax Get Pins Invalid Label

var url = "http://pinterestapi.co.uk/" + pinterestUsername + "/pins";
$.ajax({
dataType: "jsonp",
url: url,
success: function (data) {
alert(data)
}
});
firebug "invalid character" error shows
dataType:"json" is not working
Try .getJSON().
var url = "http://pinterestapi.co.uk/"+pinterestUsername+"/pins";
$.getJSON(url, function(data) {
alert(data);
});
Ok, lets try something different...
Assuming you are the user "jwmoz".
var user = "jwmoz";
var url = "http://pinterestapi.co.uk/"+user+"/pins";
$.get(url,
function(data) {
alert(data)
}, "jsonp");
Check out this page jQuery AJAX cross domain, this should give you a rough idea and several userful links to solve your problem.
Ps- sorry for misunderstanding your question first time around! Best of luck!!
Dom

AJAX on click not calling/loading as it should

I have been learning AJAX for the best part of 2 hours, trying to get my head around how to get this to work, it seems it is calling the function as if I put an alert in, it all works fine.
I tried using another method and it seemed to call the function on it's own and it would load what the .php page is echoing.
What am I doing wrong in order for it to not work at all?
<script type="text/javascript">
$('a.fire').click(call_ajax);
function call_ajax() {
$.ajax({
type: "GET",
url: "http://127.0.0.1/onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
}
});
}
</script>
Edit: I have also just tried
$('a.fire').click(function() {
$.ajax({
type: "GET",
url: "http://127.0.0.1/onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
}
});
});
Which also does not work.
EDIT: I have now got code that GET's the php file I wanted, but for some reason does it on it's own
<script type="text/javascript">
function call_ajax() {
$.ajax({
type: "GET",
url: "http://127.0.0.1/onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
}
});
}
<script type="text/javascript">
$(function() {
$(document).ready(function() {
$('a.fire').click(call_ajax());
});
});
The issue with this code is that it fires on it's own
EDIT: Now have new code, that is attempting to fire according to Firebug console but I get the alert ERROR: error, so I don't have a clue what is happening in order for it to fail, I have also tried many different URL's with no working solution
$('a.fire').click(function () {
$.ajax({
type: "GET",
url: "/onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
},
error:function(xhr, text, error){
alert("Error: " + text);
}
});
});
SOLVED: I have now got it to work! For some reason my anchor had a href of "", which would cause it to reload the page and removing my GET from the page
ajax will only work if it's the same domain. This means that if you execute jQuery from domain x to domain y, it won't work. This is for safety-reasons to prevent websites from loading from another website. Does your jQuery-ajax call work if you remove the 127.0.0.1 from your url?
Furthermore I guess you should add the click-function inside your $(document).ready(); function, like this:
$(document).ready(function(){
$('a.fire').click(function() {
$.ajax({
type: "GET",
url: "onlineshop/admin/scripts/test.php",
dataType: "html",
success: function(html){
$("#holder").append(html);
}
});
});
});
for testing purposes, you can also use the complete function inside your ajax and alert your data. firebug can be helpful too to find your problem :)

Jquery: probleme with $.ajax (json datatype)

I have a problem to refresh a bloc in my page.
Here is the request:
> $("#pwd_lost_link").click(function(){
alert('1');
$.ajax({
type : 'POST',
url: 'test.php',
dataType: 'json',
data :{"nom" : "akbar"},
success : function(data){
$("#main_bloc").append(data.msg);
alert('2');
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
alert(errorThrown); }
}); })
and here is the php file
<?php
$return['nom'] = "ffrfrfrfr";
echo json_encode($return)
?>
It doesn't work. It give me a status error ( 0 ) and the page is automatically reloaded
Thanks
Michaël
Confusing question Michael, not sure what you mean by "the page is automatically reloaded" but you should do 2 things:
In the $.ajax() method, make sure your success called back is handling the data correctly. You are looking for data.msg but I don't see where .msg comes from.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
data: {},
dataType: "json",
url: url,
success: function(data) {
// parse data object so you can see what's being returned ex. alert(data) or alert(data[0]) or alert(data.nom)
},
error: function (xhr, status, error) {
// XHR DOM reference: http://www.w3schools.com/dom/dom_http.asp
// check for errors ex. alert(xhr.statusText);
}
});
On the PHP side, you may want to debug there to see what is being received and what you are sending back.
Aside from that using an XHR viewer like Firebug or Chrome's built-in utility (CTRL+SHIFT+I) can be very helpful.
And on a final note, if pwd_lost_link is a link elment a id="pwd_lost_link" href="..." then you will have to stop the browser from following the link before you process the AJAX.
$("#pwd_lost_link").click(function(e) {
e.preventDefault();
alert('1');
$.ajax({
...
});
If you aren't seeing the '1' being alerted then that is definitely your first problem.
You're trying to access data.msg, but your PHP script is only creating data.nom. So data.msg doesn't exist. Try changing data.msg to data.nom and see if this does what you want.

Resources