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

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

Related

Block Javascript function after 1 call

I am working on a multiple-choice question app and I am a database where I am storing the users answers. I just want to store the first answer they select to store it in the database. After the first selection, they can still click on the other answers to run the checkAnswer() but the storeAnwserStats() should not run. How can I do that?
app.js
function storeAnwserStats(questionId, answerId){
$.ajax({
url : "/store_stats",
type : "POST",
data : JSON.stringify({
question_id: questionId,
answer_id:answerId,
}),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
})
.done(function(data){
console.log("After " +data["correct_answer"]);
});
}
function checkAnswer(divSelected, answerId, questionId, isCorrect){
if(isCorrect == 1){
divSelected.style.backgroundColor = "green";
}
else{
divSelected.style.backgroundColor = "red";
}
storeAnwserStats(questionId, answerId)
}
[1]: https://i.stack.imgur.com/xyZfY.png
You can do multiple things for this.
METHOD 1
Disable the options: After the person has answered you can make the the sibling options disabled.
DOWNSIDE: the person can make the element enabled again by inspecting the element.
METHOD 2
Server side validation: check from server side if the answer has been answered or not on each call.
DOWNSIDE: server calls are increased.
METHOD 3
Remove the onclick along with onClick: After the person has answered you can make the the sibling options disabled AND remove the onClick call from them.
DOWNSIDE: Not sure of any yet.
EDIT 1
Server side validation is still important
Even after you do all those things above if the person really wants to be fishy
they can still send answers to your server by calling the function from console.
suppose in the OnClick function of the option you are calling your storeAnwserStats(), and since they are client side JS files I can easily check it and send the request by going to the console and typing storeAnwserStats(question_id, answer_id) (and question ID can be seen in the network tab)
good luck!

Find class on and run function on current page

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 <

Using multiple ajax calls in one javascript function

Thanks in advance for any help.
Is it bad practice and/or inefficient to use multiple $.ajax calls in one javascript function? I've been working on one and have a simple testing environment set up on my computer (apache server with php/mysql), and I've noticed that the server will crash (and restart) if I have multiple ajax calls.
I have two ajax calls currently: one passes 4 pieces of data to the php file and returns about 3 lines of code (pulling info from my sql database), the other simply gets the total rows from the table I'm working with and assigns that number to a javascript variable.
Is it just that my basic testing setup is too weak, or am I doing something wrong? See below for the two ajax calls I'm using:
$.ajax({
type: "GET",
url: "myURLhere.php",
cache: false,
data: {img : imageNumber, cap : imageNumber, width : dWidth, height : dHeight},
})
.done(function(htmlpic) {
$("#leftOne").html(htmlpic);
});
$.ajax({
type: "GET",
url: "myotherURLhere.php",
cache: false,
success: function(data) {
lastImage = data
}
})
Short answer: two ajax request on a page is absolutely fine.
Longer answer:
You have to find the balance between minimalising the number of ajax calls to the backend reducing the traffic and communication overhead; and still maintaining a maintainable architecture (so do not pass dozens of parameters in one call to retrieve everything - maybe only if you do it in a well designed way to collect every parameter to send)
Also most likely there's something wrong with your backend setup, try looking into webserver logs

Why jQuery ajax added same cookie in my request header multiple times?

I have been trapped in this on for many hours, wondering if you have could help me out or provide me some suggestion?
Long story short,
I have a asp.net web api application, In one of my page, I am trying to load some data from web api and add them into few dropdown lists.
Anyway, I use jQuery ajax when the page loads
$(document).ready(function () {
//Fires when page loads
LoadMachines();
LoadMachieGroups();
LoadPrinterServer();
LoadSavePreference();
});
Each of the functions does the similar job, for example
function LoadMachieGroups() {
console.log("Before group " + document.cookie);
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "/api/Machine/MachineGroups",
//data: "{}",
success: function (response) {
OnMachinesGroupLoadSuccess(response);
}
});
console.log("after group " + document.cookie);
}
The issue is that, we the code runs to the third (LoadPrinterServer) and fourth function (LoadSavePreference). The request header passed the same cookies (DoxMachineId) with different values three times. (Please see the picture), which then cause the trouble in my c# code to find the correct result.
My questions are:
1.) Why could same cookie added in the header multiple times? Is this because of multiple ajax calls?
2.) How to solve the problem? For example: remove the cookies?
Thanks guys in advanced.
Since I stumbled over the same (or pretty similar) problem and could not find a solution elsewhere, here comes my self-found-after-severe-frustration-solution:
When I sent the set-cookie header to the client, I missed to set its path argument to / (the root) on the server side. The client interpreted this as to set the path of the cookie to the parent of the leaf of its current target-path. In my case, that meant /api (since it has been an ajax-call to /api/create).
So, the client ended up with storing one instance of the cookie per path (in my case, for each api-call, there was an instance of the cookie stored at the client-side, as well as one cookie for the root-path that has been set by loading resources).
Whenever the client sent a request to the server later on, it attached all of the cookie-instances (with their respective values) to this request that matched the current target-path (again, in my case, whenever the client requested /api/create it attached the cookie-instance of the path / as well as the instance of the path /api which means the same cookie with two different values).

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/

Categories

Resources