How do I update my ajax data? - javascript

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 + "&#8457");
$('.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 + "&#8457");
$('.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 + "&#8457");
$('.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.

Related

Using ajax to post a form to php without refresh

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

Why is my JQuery AJAX function not working properly?

Trying to insert a car image from one of my databases into my webpage
get_new_car_pictures:
$make = $_REQUEST['make'];
$model = $_REQUEST['model'];
$query = "SELECT * FROM database_new WHERE make = $make AND model = $model";
$car = $db->get_row($query);
$img = $car['img_url'];
echo "<img src=".$img." />";
ajax function:
function insertImageAJAX(){
return $.ajax({
type: 'GET',
url: '/ajax/get_new_car_pictures.php',
data: "model=" + params.model + "&make=" + params.make,
success: function(data){
$("#car-image".html(data));
}
}
});
car-image is the div where I want the image to appear
I have tried to follow Ajax tutuorials online but for whatever reason, this is not working...
use concatenation on query and varchar has to be in single quotation
$query = "SELECT * FROM database_new WHERE make = '".$make."' AND model = '".$model."'";
and also fix js
function insertImageAJAX(){
return $.ajax({
type: 'GET',
url: '/ajax/get_new_car_pictures.php',
data: {'model':params.model, 'make': params.make},
success: function(data){
$("#car-image").html(data);
}
}
});
For one thing, you've misplaced a parenthesis:
$("#car-image".html(data));
should be
$("#car-image").html(data);
Try adding an error callback to take a closer look at what's going on.
jQuery Ajax error handling, show custom exception messages
Also, I'd recommend setting the image's src attribute with the response instead of setting its HTML.
Let me know what the error says and we can go from there.

JQuery AJAX function not receiving PHP-returned text

I've been searching for a while for a solution to this problem. I've found many people with the same problem, but not the same solution.
The issue I'm having is that PHP is not returning any data to the AJAX function. The alert spits out data = undefined. As you can see, using return instead of echo is not the problem. I know that the PHP script I call completes correctly because the values are properly inserted into the database. No matter where I place the echo statement, I can't get it to return the value. Am I using the data variable incorrectly? Is returnValue not the proper variable to use? Has any of the functionality I've been trying to use been deprecated? I'm really at a complete loss. I can't see why this is failing.
//AJAX function
$("document").ready(function(){
$("#add_interest_form").submit(function(event) {
event.preventDefault();
$("#output").html("");
var values = $(this).serialize();
$.ajax
({
url: "./php/add_interest.php",
type: "POST",
data: values,
success: function(data) {
alert('data = ' + data.returnValue);
$("#output").html(data.returnValue);
},
error: function() {
alert('failed adding to database. Please try again or contact the Webmaster.');
}
});
});
});
//PHP snippet
echo 'Success!';
Just do alert('data = ' + data); instead of alert('data = ' + data.returnValue);.

Ajax being called twice on setInterval

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

Why do I get undefined when displaying value in a global variable?

I just don't get it, obviously. I've tried setters and getters, self invoking functions, you name it. It's like the click handler is returning a value but there's no way for me to keep it?
This is my code in the first file request.js
var testId = (function (inId) {
var citeId = inId;
return citeId;
})();
function mainAjax() {
return $.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/items?parentId=504108e5e4b07a90c5ec62d4&max=60&offset=0&format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp'
});
}
var promise = mainAjax();
this is the code in my second file requestMain.js,
promise.done(function (json) {
var linkBase = "http://www.sciencebase.gov/catalog/item/";
var link = "";
var itemId = "";
var urlId = "";
$.each(json.items, function(i,item) {
link = linkBase + this.id;
$('#sbItems').append('<li><b>' + this.title + ' - </b>' + this.summary + '</li>');
});
$('#sbItems a').on('click', function (e) {
e.preventDefault();
var str = $(this).attr('id');
if (str.length == 7) {
itemId = str.slice(5,6);
}
else if (str.length == 8) {
itemId = str.slice(5,7);
}
testId = json.items[itemId].id;
alert(testId);
}); // END Click event
}).fail(function() {
alert("Ajax call failed!");
});
This webpage displays a list of links. A link could have some more information that I want displayed on a second webpage or it could have nothing. So when a link is clicked I need to store/save/keep the id from the link so that I can use it in the url to make another ajax request, because until I get the id the ajax request for the next page will have no idea what information to ask for.
For now I'm simply doing this
alert(testId);
But what I'm trying to do is this,
$.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/itemLink/' + testId + '?format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
// Then doing something with json.something
testId would be used in the url and it would change depending on the link that was clicked on the previous page. The ajax call is totally dependent on the click event and is displayed on a separate webpage with new information.
And this would be in my third file requestCitation.js which currently gives me a big undefined when doing
alert(testId);
I think this is a scope issue, but how can I store the value returned from a click??? So that I can then use it globally? It seems like the value disappears outside of the scope as if there was never a click at all even thought I'm storing it in a variable?
the html for the first page has script tags for request.js and requestMain.js and the second page has script tags for request.js and requestCitation.js, so they can both see the variable testId.
Thanks for the help!
Here's the jsfiddle
These are the links and when a link is clicked
Your testId is holding the value retuned by the function you're calling, and since the function returns its argument and you've called it without arguments, it will be undefined:
var testId = (function (inId) {
var citeId = inId;
return citeId; //returns the argument
})(); // called with no argument
I'm not entirely sure what you're trying to do but if you're trying to keep the data returned from the AJAX request as a global variable, I would have thought it was done using something similar to the below.
E.g.
var promise = '';
$.ajax({
type: 'GET',
url: 'https://www.sciencebase.gov/catalog/items?parentId=504108e5e4b07a90c5ec62d4&max=60&offset=0&format=jsonp',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp'
data: '';
success: function(data){
promise = data;
}
});
But as I said I'm not understanding fully so I could be very wrong with my answer.

Categories

Resources