I'm doing ajax calls in a specific time interval using javascript setInterval function however the ajax code is being executed twice, so I'm getting the same response twice and I have no idea why this is happening, here's the code:
setInterval(function () {ajaxCall();},15000);
function ajaxCall(){
var uri = "url here";
$.ajax({
type: "GET",
url: uri,
dataType: "jsonp",
success: function(response){
console.log(response);
var txt = $("#textarea");
txt.val( txt.val() + response.user + " (" + response.time + ") > "
+ response.text + '\n');
}
});
}
Any help would be appreciated.
Thanks
Ok so I just figured it out, I had that script inside the html body tag but if I move it inside head tags it stops calling it twice, not sure why this is but it solved the problem.
Sorry for wasting your time for something that simple xD
Related
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.
I am relatively new at AJAX/JSON, So apologies in advance if this turns out to be a bit of stupid question.
To practice my AJAX/JSON skills I am trying to make an weather web application. So I managed to find an api on the openweathermap website.
By using the .ajax() jQuery function I managed to load the data on my page. So I tried to take it to the next level by using an input field to change the location of the weather forecast. This is where I got stuck. I tried variety functions and approaches but I can't wrap my head around it.
This is what I've got right now.
$(document).ready(function(){
var $city = "New York, USA";
var $parameter = "Imperial";
var $urlLocal = "http://api.openweathermap.org/data/2.5/weather?q=" + $city + "&units=" + $parameter + "&APPID=0013269f6f2be27afffaa8b122e8f9f8";
var $input = $('.search'); //input field
$input.blur(function(){
$city = $input.val();
console.log($city);
});
$.ajax({
dataType: "json",
url: $urlLocal,
success: function(data) {
console.log("success", data);
$('.temp').html(data.main.temp + "℉");
$('.location').html(data.name);
}
});
});
I searched for a while on this forum but I couldn't quite find what I'm looking for.
I hope someone can help me!
Thanks!
EDIT
Thanks a lot guys for the great and fast response!!
The easiest way to achieve what you want would be to put the AJAX call inside the blur event you linked to input field.
And you will also need to regenerate the $urlLocal value before doing the AJAX call.
It could be something like that:
$input.blur(function(){
$city = $input.val();
$urlLocal = "http://api.openweathermap.org/data/2.5/weather?q=" + $city + "&units=" + $parameter + "&APPID=0013269f6f2be27afffaa8b122e8f9f8";
$.ajax({
dataType: "json",
url: $urlLocal,
success: function(data) {
console.log("success", data);
$('.temp').html(data.main.temp + "℉");
$('.location').html(data.name);
}
});
});
The reason your code is not working is because you're not calling the ajax in your blur event. the map is loaded in the document.ready event since the ajax function is written in the document.ready event. you need to create it as a function and call it both in the document.ready and the input blur event.
try enclosing your ajax call in a method like this
function LoadMap(){
var $urlLocal = "http://api.openweathermap.org/data/2.5/weather?q=" + $city + "&units=" + $parameter + "&APPID=0013269f6f2be27afffaa8b122e8f9f8";
$.ajax({
dataType: "json",
url: $urlLocal,
success: function(data) {
console.log("success", data);
$('.temp').html(data.main.temp + "℉");
$('.location').html(data.name);
}
});
}
and call this method in the document.ready event as well as the input blur event.
$input.blur(function() {
$city = $input.val();
console.log($city);
LoadMap();
});
here's a working JSFIDDLE for the same.
I have this written up for send a few variables to a php script:
$(function() {
$('a[class="removeUnread"]').click(function(){
var markedtopicid = $(this).attr("id");
var sessionvar = \'', $context['session_var'], '\';
var sessionid = \'', $context['session_id'], '\';
$.ajax({
url: "index.php?action=quickmod;board=', $context['current_board'], '",
type: "POST",
data: sessionvar + "=" + sessionid + "&topics[]=" + markedtopicid + "&qaction=markread",
});
});
});
I think this is the correct way to send post data via ajax, but it doesn't appear to be sending. Was I right to wrap the code in the ready function?
I can tell you right off the bat you should not have a semicolon between quickmod and board in your URL. I'm answering here because i cannot post comments yet. One good tool to use in web development ESPECIALLY with GET and POST requests is googles PostMan app. Its free to use and what it does is it will show you the exact output of any link you send it. So you can try putting the link that you make via javascript into postman and see what errors it spits out.
In this example i'm pretty sure your URL is all kinds of screwed up though. Try this instead...
"index.php?action=quickmod&?board="+$context['current_board']
fyi, i did not test that link so it may not work. If it doesnt work, google some ajax examples and javascript string concatenation. You're string is not suitable for ajax.
is should be like this...
$.ajax({
url :'index.php',
type : 'POST',
data : { sessionvar: sessionid, topics:markedtopicid},
success : function (data) {
},
error : function () {
}
Try handling the error:
$.ajax({
url: "index.php?action=quickmod;board=', $context['current_board'], '",
type: "POST",
data: sessionvar + "=" + sessionid + "&topics[]=" + markedtopicid + "&qaction=markread",
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.responseText);
}
});
Belwo is my function which i want to execute on click event of anchor tag. I have tried two methods but none of them working completely fine.
1st way:
Continue Shopping
In this way my function is not working unless i put event.PreventDefault() within my function. But as i put event.PreventDefault() in my logContinueShopping() function, the function works fine but anchor tag is not working as obvious.
2nd way:
Continue Shopping
In this way, my function is running till ajax request but the success function is not executing i.e it is not setting the cookie and redirection the page to '/'.
function logContinueShopping(){
var action = 'continue_shopping';
// Check if the activity is already logged
var checkCookie = getCookie('continue_shopping');
if(checkCookie == ''){
$.ajax({
type: 'POST',
url: '/ajaxCall/user-activity-ajax.php',
data: {
action:action,
url:url
},
success: function(response)
{
document.cookie = "continue_shopping = " + action + "; path=/";
}
});
}
I would request to please not to provide jQuery solution as i m forced to use javascript here.
Thanks alot.
}
Have you thought about setting the document.location in your success handler? :
$.ajax({
type: 'POST',
url: '/ajaxCall/user-activity-ajax.php',
data: {
action: action,
url: url
},
success: function (response) {
document.cookie = "continue_shopping = " + action + "; path=/";
document.location = '/';
}
});
Try this:
change href="javascript:void(0)"
and user window.location="/" on success of the ajax call to redirect.
I have placed async: false and used the function in below way
Continue Shopping
Thanks for contribution.
I would like to call a function on a php file, which one I call in ajax.
I tried the following code:
$("#jq_entryConfQuickSend").click(function () {
$.ajax({
type: "GET",
context: document.body,
//async:false,
url: RP_ROOT_PATH + "/courriers/entries_courriers/rp_win_courrierEntryConfirmation.php",
data: "id_client=" + RP_CLIENT.rp_clientID,
success: function (responseText) {
//var json = eval("(" + responseText + ")");
$("#response-div").html(responseText);
$(responseText).find("script").each(function (i) {
eval($(this).text());
console.log('result');
});
}
});
});
In $(responseText) seems to be an array (I can see the following e.fn.e.init[58]) in chrome debugger, but when I try to use the find('script') function, it doesn't return anything??
And I have many script tag in these file???
Question: What is e.fn.e.init[]?
How can I call my javascript functions on the file I've just loaded in ajax
Thank you
In the ajax parameters I needed to include :
dataType: "html"
Then it will be possible to call the function from the response