I started working with Ajax, and I'm listening tutorials on one tutorial i see the code like:
$("button").click(function(){
$.get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
on other cases i see XMLHttPRequest done in javascript can someone tell me the diffrence between two? Beacuse its confusing listening one tutorial that tells you one thing and other second thing
Jquery wraps the use of XMLHttPRequest with his $.get request (etc.)
So bassicly you are using the same method of Ajax.
Related
I am trying to make a get request once the user enters an value and pass that value as parameter however nothing happens. The alert outside theget function works fine. here is my code
$(document).ready(function(){
$( "input[type='text']" ).change(function() {
$.get("http://example.com/get.php?number=1234", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
$("#result").html( data );
});
alert("end of script");
});
});
https://jsfiddle.net/4rrous4y/3/
To send a parameter along to get.php you need to append a query string.
In your $.get after the URL add ?parameter=value and change the values accordingly.
I think you are having a cross origin issue here. Basically if the resource you are trying to load is in a different domain than the origin of the request, it won't let you access to it.
Check the console in Google Chrome, some error should be appearing there.
I am using the following code but it seems to be not working. Sorry for asking this simple question but I want to know why this code is not working
$(document).ready(function(){
$("button").click(function(){
$.get("smiley1.html",function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
<button>Send an HTTP GET request to a page and get the result back</button>
Please help me to solve it. Thanks
Code is fine but, it matter from where you are running it.
If you are trying to run from snippet runner of this page, if will fail because of 2 reasons
it doesn't find $ (i.e. jQuery)
it is trying to do cross domain call, which I believe is not allowed from target page. smiley1.html is not present on stackoverflow.com domain,
you can see error in developers console
If try it in jsfiddle
$(document).ready(function(){
$("button").click(function(){
$.get("x2rmptu3/show/",function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
here is my fiddle http://jsfiddle.net/x2rmptu3/2/
I am making a weather website for my school project using the Wunderground Weather API. This is the code I am using to get the JSON data:
$.getJSON("http://api.wunderground.com/api/<apikey>/conditions/q/" + wlocation + ".json", function(data){
alert(data);
});
The <apikey> is where I put my API key, and the $ character is just a shortcut for JQuery.
When I open this webpage, which is local, not published, no alert pops up and I get the error:
XMLHttpRequest cannot load http://api.wunderground.com/api/<apikey>/conditions/q/<myzipcode>.json. Origin null is not allowed by Access-Control-Allow-Origin.
After doing some research on this error, it sounds like I might have to create a web server. However, for the project, we need to turn it in as a folder of .html and other "web files". Is there another way to do this or do I have to make a web server? This project is due soon, so any help is appreciated!
Yes, you can use JSONP for this.
I'm not sure if Wunderground Weather API have some kind of callbacks in JSON. But if they do even jQuery getJSON support JSONP.
Seems like you run into Same origin policy.
here is a code sample from the link that you provided in your original post (http://www.wunderground.com/weather/api/d/docs?d=resources/code-samples). they use JSONP. yes, as #antyrat said, it is a CORS problem.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/Your_Key/geolookup/conditions/q/IA/Cedar_Rapids.json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
});
</script>
I'm not a very experience programmer and have been learning HTML/CSS/JS on the fly. I've been trying to parse XML using jQuery AJAX methods with absolutely no luck.
Here is my code in use: http://jsfiddle.net/Kb5qj/1/
And here is my code in plain sight:
$(document).ready(function() {
var divid = "#xmlcontent"
function parseXML(xml) {
$(divid).empty();
$(xml).find("CD").each(function() {
var artist = $(this).find("ARTIST").text();
var title = $(this).find("TITLE").text();
$(divid).append("<li>" + artist + " - " + title + "</li>");
});
}
function printError() {
$(divid).html("An error occurred");
}
$.ajax({
type: "GET",
url: "www.w3schools.com/ajax/cd_catalog.xml",
dataType: "xml",
success: parseXML,
error: printError
});
});
I don't know what the problem could be. I have written and re-written and copy/pasted that $.ajax call many many times, but no matter what I do nothing ever happens. Help me please?
like I mentioned it will fail on jsfiddle as they dnt actually send the get request. here is the api on how to achieve the same: http://doc.jsfiddle.net/use/echo.html
If you try the same on your local system it will fail probably cos you are making a cross domain request and your browser natively blocks such requests. That is where jsonp comes it to play its to retrieve json data over cross domains..
You can hack it a little to do the same for js.. here is a SO post about the same: Is there an existing tool for jsonp like fetching of xml in jquery?
With a little bit of fudging, everything in the parsing seems to work fine. Check out this JSFiddle.
You can't use get requests from JSFiddle, but I mocked up the XML into HTML. You may want to try placing your XML document into the DOM to help suss your issue.
So I need to make a a cross domain request where the response is not JSON formatted, so I cannot use .getJSON. .get obviously doesn't work because it is a cross domain request.
I came across this (Read this) when I was googling and it seems it should work for what I want to do (which is do a cross domain call that isn't json formatted using a jquery plug in). My code looks like the following. I know the url works fine because if I paste it into my browser, I can see the response, which according to last.fm documentation
The body of the server response
consists of a series of \n (ASCII 10)
terminated lines. A typical successful
server response will be something like
this:
OK
17E61E13454CDD8B68E8D7DEEEDF6170
http://post.audioscrobbler.com:80/np_1.2
http://post2.audioscrobbler.com:80/protocol_1.2
So I know my URL is fine. Now I am wondering how I get at this information, and why my version of their example does not work.
function performHandshake(sk, token, ts){
var token = md5(apiSecret + ts);
var urlToUse = "http://post.audioscrobbler.com/?hs=true&p=1.2.1&c=tst&v=1.0&u=chamals&t=" + ts + "&a=" + token + "&api_key=" + apiKey + "&sk=" + sk + "&format=xml&callback=cbfunc";
$('#container').load(urlToUse);
$.ajax({
url: urlToUse,
type: 'GET',
success: function(res){
var headline = $(res.responseText).find('a.tst').text();
window.console.log(headline);
}
});
}
Well the page you linked you talks about using YQL and jQuery. It's a very interesting solution. However, your example seems to skip over the YQL part (which is crucial).
var urlToUse = "http://post.audioscrobbler.com/?hs=true&p=1.2.1&c=tst&v=1.0&u=chamals&t=" + ts + "&a=" + token + "&api_key=" + apiKey + "&sk=" + sk + "&format=xml&callback=cbfunc";
var yqlUrl2Use = "http://query.yahooapis.com/v1/public/yql?"+
"q=select%20*%20from%20html%20where%20url%3D%22"+
encodeURIComponent(urlToUse)+
"%22&format=xml'&callback=?"
// this function gets the data from the successful
// JSON-P call
Then you'll have to call the call the new URL as a JSONP req...
$.getJSON(yqlUrl2Use, function(json){
// figure out the format of the answer here...
});
Yeah, cross browser scripting. You can't AJAX anything like that since it violates the same domain policy.
You are going to have to setup a proxy on the same server the JavaScript is running from.
Edit Lookslike you need the $('#container').load(url) bit for that to work.
Go back an reread the linked article carefully.
You need to use $.getJSON rather than $.ajax() to return cross site information.
The var res actually has my information that I needed. I guess their headline = part was specifically for their implementation.
Thanks to those who helped!