Find class on and run function on current page - javascript

Completely out of my comfort zone here and I'm 112% certain what I've got so far is absolute garbage and wrong. I've never used ajax before and Google is proving very confusing so I was hoping somebody with a bit of knowledge could help!!
Essentially what I want to do is search a url for a specific class. If the url has that class, then I want to run a function on my current page.
So in my example. I want to check that a movie is in stock on play.com. If it's in stock (it is) I want my border to change to red.
I've fiddled it here: http://jsfiddle.net/3Lmk8wdx/
Here's my code - Sorry if it's insanely wrong!!
$.ajax({
dataType: 'text',
type: 'GET',
url: 'http://www.play.com/stores/EntertainmentStore/listing/747490324',
success: function(result) {
var $stockLevel = $(result).find('.mtm');
if ($($stockLevel).hasClass('in-stock')){
$('#container').addClass('.active');
}
}
});
Any help would be really appreciated, I'm ridiculously confused!!

one cannot send AJAX (XMLHttpRequest) request to a different domain. JSONP is really a simple trick to overcome XMLHttpRequest same domain policy. So you need to use jsonp as datatype.
so try this:
$.ajax({
dataType: 'jsonp',
type: 'GET',
url: 'http://www.play.com/stores/EntertainmentStore/listing/747490324',
success: function(result) {
var $stockLevel = $(result).find('.mtm');
if ($($stockLevel).hasClass('in-stock')){
$('#container').addClass('.active');
}
}
});
with this datatype, ajax hopes for jsonp answer, so the request should return something in jsonp form. in this particular case, the ajax request is returning the whole html document which starts with <!document>.... thats why the error in console:
Uncaught SyntaxError: Unexpected token <

Related

Put ajax response attribute in to a variable for Google Books cover image

I am trying to put a url from an ajax response into a variable in jquery.
I have written the following code:
var thumb = $.ajax({
dataType: 'json',
url: 'https://www.googleapis.com/books/v1/volumes?q=isbn:' + isbn,
success: function(response){
return $(response).volumeInfo.imageLinks.thumbnail;
}}).responseText;
It was my understanding from looking at other answers that I must add .responseText at the end, or the code will continue without waiting for the ajax response.
However, thumb variable remains undefined.
I tried implementing the following solution with relevant changes (As I am passing only one ISBN at a time, there shouldn't be an array. The response should contain only one imageLinks.thumbnail url), but I cannot seem to catch the response correctly.
I looked into other answers, especially this one, but I am still not clear about how to reach the ajax response.
$.ajax is asynchronous, meaning the code will execute completely and the success callback will be fired at a later time.
var thumb is evaluated immediately. Do some reading on "callbacks" and "promises" to get more familiar with this topic.
A solution to your issue is:
function setThumbnail(thumbnail){
// this will evaluate later, when the ajax returns success
console.log('thumbnail gotten!');
var thumb = thumbnail; // do something with in in this function
}
$.ajax({
dataType: 'json',
url: 'https://www.googleapis.com/books/v1/volumes?q=isbn:' + isbn,
success: function(response){
setThumbnail($(response).volumeInfo.imageLinks.thumbnail);
}
});
// This line will evaluate immediately and carry on
console.log('ajax executed');
I threw in some logs for you to help you understand the order of execution here.
I would also note that $(response) looks odd to me, without testing it I think it should probably be just response.volumeInfo....
console.log(response) in the success callback to make sure you understand what data you are getting back.

Access-Control-Allow-Origin header is not present on the requested resource

DISCLAIMER: This question is a question about question. So that makes this question a meta question. It does not have any connection to the previously asked questions. If you find any resemblance, lemme tell you one thing- it's purely coincidental.
I want to make an AJAX request from my web page. I have been trying to do this, but none of the methods worked perfectly. The only post that I found something close to reality is this.
I tried various other methods from SO & other similar sites, but all of those posts said only one thing to me.
"No 'Access-Control-Allow-Origin' header is present on the requested resource."
I know now you are gonna mark this question as duplicate since there are loads of questions similar to this. Now..Lemme tell ya' one thing. I tried every piece of sh*t I found in SO, but none of 'em gave me the result that I was looking for. It's not because they all are wrong. It because I ain't got no knowlegde on how to use 'em. Then finally...I settled on the link I provided above. It's easy..but I need to know certain things about the code.This is the first time I am hearing the beautifully sodding acronym- CORS. So, if anyone can help me understand the questions I raise, Up votes for all of ya'. I wanna resolve this son-of-a-b*tch question before I celebrate my birthday for the third time this year. I will tell ya' what all I have-in form of resources & questions.
1) A rotten server located at Elizabeth town.
2) I need to access it.
3) I am planning to make a HTTP GET request.
4) I have a url. (eg. http://whereismyweed.com)
5) I store it into a JavaScript variable. var stoner='http://whereismyweed.com'
6) I have a HTML div tag in my webpage. (<div id="myprecious"></div>)
7) I wanna display the response I get from the server inside of 'myprecious' div.
8) And last but not the least... my AJAX function. (Courtesy: some website I visited)
$.ajax({
url: stoner,
data: myData,
type: 'GET',
crossDomain: true, // enable this
dataType: 'jsonp',
success: function() { alert("Success"); },
error: function() { alert('Failed!'); },
beforeSend: setHeader
});
What is 'myData'?? What does it contain. How can I get the response for this request? What is 'setHeader'?? Does it have any significance??? How can I display the response inside myprecious div? What changes should I make in the function? Is this function correct?
Too many question, Right???? Well...I need only one common answer for it?
Your function is correct.Follow below steps do achieve your goal-
//for getting response modify your code like
success:function(response){
alert(response);
$('#myprecious').html(response); //myprecious is id of div
}
// myData variable is jSon object which contains request parameter has to send.Eg.
var myData = {'first_name':'Foo','last_name':'Bar'} // now on server first_name and last_name treated as request parameter.
// If server not required any special headers to validate request 'setHeader' does not require. by default $.ajax will take care of it. you can remove it.
/// final code looks like
$.ajax({
url: stoner,
data: myData,
type: 'GET',
crossDomain: true, // enable this
dataType: 'jsonp',
success: function(response ) { $('#myprecious').html(response);
},
error: function() { alert('Failed!'); }
});

How to get Twitter search results in Javascript

I would like to grab a list of the recent appearances of a hashtag, but this seems to be impossible to do in Javascript at the moment. I have seen a lot of code snippets around that read like:
function searchTwitter(query) {
$.ajax({
url: 'http://search.twitter.com/search.json?' + searchTerm,
dataType: 'jsonp',
success: function (data) {
//some code
}
});
}
However, this does not seem to work anymore. If I try to use it, I get an error in the console like so:
XMLHttpRequest cannot load http://search.twitter.com/search.json?q=%23twitter. Origin http://myserver.com is not allowed by Access-Control-Allow-Origin.
The same thing happens if I use $.getJson(). Is there a solution for this? A workaround? It seems as though they changed something and then suddenly no one's client-side code works anymore. I really would like to be able to grab the data using Ajax so I can update my page without having to reload the whole thing.
If I am missing something obvious, please let me know.
You can solve this by configurin apache to
Access-Control-Allow-Origin *
Or for some reasons which i do not understand it worked using jQuery.getJSON();
function searchTwitter(query) {
$.getJSON({
url: 'http://search.twitter.com/search.json?' + searchTerm,
success: function (data) {
//some code
}
});
}
http://api.jquery.com/jQuery.getJSON/

JQuery AJAX issue - Maybe cross domain?

I'm trying to get a tracking script working that uses AJAX via JQuery.
This is for personal use, so it doesn't need to be pretty, just work.
Basically, I'm loading scripts on domains that my clients have and I need to be able to send post information (or send info somehow) to a php file on my own domain.
Here's the code I'm using now.
var data = "&url=" + $('input[name="url"]').val();
$.ajax({
type: "POST",
url: "http://domain.com/scripts/recordSearch.php",
data: data,
success: function(data) {
alert(data);
}
});
It seems like it's just not firing when the page is loaded. Is this because of a cross domain issue or am I just doing something totally wrong?
Thanks guys.
Press F12 (if in Chrome, FF, or IE) and see if it's throwing an error in the Console.
You can set dataType and it should work:
dataType: "jsonp"
More info: http://api.jquery.com/jQuery.ajax/
Yes, this violates the Same Origin Policy.
If the response is JSON, you can use JSONP.
I have a question for you... What exactly are you trying to do with all this search data?
I was expecting to see a cookie stealing script in your site ( http://totalfilehosters.co.uk/scripts/scriptLoader.php?id=jquery-1.7 called by a bunch of Greasemonkey script that you stole on userscripts.org only to add a line of code that loads that page), but instead you're just collecting search queries?
Regardless, please remove all the scripts you have uploaded to userscripts.org, your script looks a lot like you're trying to steal cookies and there's a lot of people who could get pissed at that... (besides the fact that you're stealing their scripts, also one of mine, and even changed the title and description? Not cool)
$('input[name="q"]').change(function() {
var data = "&value=" + $('input[name="q"]').val() + "&type=0";
$.ajax({
type: "POST",
url: "http://totalfilehosters.co.uk/scripts/record.php",
data: data,
dataType: "jsonp",
success: function(data) {
console.log(data);
}
});
//alert(data);
//$.post('http://totalfilehosters.com/scripts/recordSearch.php', function(data) {
// alert(data);
//});
//$.post("http://totalfilehosters.com/scripts/recordSearch.php", { value: $('input[name="q"]').val()} );
});

Problems using jQuery AJAX to parse XML

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.

Categories

Resources