handling server response AJAX - javascript

In the process of working on a simple project (or at least I thought to be simple) Where a user clicks a button, and a random saying generated from php appears in the above textbox. I do not have access to the php file so I can't see the code and feel a bit lost. The problem I'm having I believe, is an error in the way Im handling the response from the server (the handleServerResponse function). Any advice would be appreciated.
In an attempt to debug, I've seen this message: (I've changed the url)
XMLHttpRequest cannot load http:somephp.php. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'null' is therefore not allowed access.
the code thus far:
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
}else{
try{
xmlHttp = new XMLHttpRequest();
}catch(e){
xmlHttp = false;
}
}
if(!xmlHttp)
alert("Error 1");
else
return xmlHttp;
}
$("#BtnReset").click(function () {
$("#TBSaying").val("");
})
$("#BtnGetSaying").click(function () {
process();
})
function process(){
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
xmlHttp.open("GET", "http://somephp.php", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout('process()', 1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data
$("#TBSaying").val(message);
}else{
alert('error 2');
}
}
}
Read through the JQuery documentation and started fresh, uploaded it to the same server in which the php resides and it works. here is the final code: Thanks to all that advised!
$("#BtnReset").click(function () {
$("#TBSaying").val("");
})
$("#BtnGetSaying").click(function () {
process();
})
function process(){
// AJAX Code To Submit Form.
$.get("http://somephp.php",function(data){
$("#TBSaying").val(data);
});
}

Ajax calls from a browser are restricted by what is called "same origin restrictions". Basically this means that, by default, you can only make an Ajax call back to the same server that the web page came from. That means you cannot make a regular Ajax call to a server on another domain, port or protocol.
You can read about the same origin policy here.
There are a three ways around this restriction, but all require cooperation from a server.
CORS. The server you are making the request from puts headers in its responses that tell the browser whether a cross origin request is allowed or even what domains it is allowed from. This gives the browser permission to complete Ajax calls that are not from the same origin.
JSONP. You can read more about JSONP here. Basically, you request a script from the target server and the script is coded in such a way that it will provide you the answer you want (usually in the JSON data format).
Server proxy. You find or code a server proxy that will request the data from the other server for you. Because server to server communication is not limited by the same origin restrictions, you can sometimes find another server that allows cross-origin requests to it that will then get the data for you and then return it to you.

Your javascript seems horrible, but alas, wrong
"Access-Control-Allow-Origin" is a server-sided (php?) bug, sorry.
tell the server guys to add something like
header("Access-Control-Allow-Origin: *");
to see if your javascript is correct ^^
on a sidenote,
alert("Error 1"); should probably use console.log or throw new Error() instead..
why have xmlHttp as a global, can just use process(e){ var xhr=e.target;...} instead
don't do this setTimeout('process()', 1000); , do setTimeout(process, 1000);

Related

Getting HTML Source Code via XMLHttpRequest [JavaScript]

XMLHttpRequest works for first url but it doesn't work for second url.I think this function doesn't work for dynamic web pages.I also tried ajax to get html source but it didn't work too.What can I do?How can I change this code to work for second url?
<script language="Javascript" type="text/javascript">
function getSource(url)
{
var req = new XMLHttpRequest();
req.open(
"GET",
url,
true);
req.onreadystatechange = statusListener;
req.send(null);
function statusListener()
{
if (req.readyState == 4)
{
if (req.status == 200)
{
var doc=req.responseText;
alert(doc);
}
}
}
}
url1 = "https://pages.github.com/";
url2 = "https://stackoverflow.com/";
// This code WORKS
getSource(url1);
// This code DON'T WORK
getSource(url2);
</script>
I ran your code in a JSFiddle, and I got an error message saying it is a CORS issue. You can view these error messages by opening the Javascript console in your browser of choice.
CORS (Cross-Origin Resources Sharing) issues arise when you don't have the sufficient permission to access resources between different domains. Each web server has policies set up that determine the rules for accessing these files, and Stack Overflow's security settings are set up to disallow that kind of access to their site. You can read more about CORS here.

How get JSON data from external URL

I would like to be able to read information from a small page.
I have the address of a JSON service that displays the following information:
And I wish I could keep the number that appears.
I tested this example and work correctly, however when I try with my URL nothing happens. I do not know if I am to understand the problem correctly, but I wish someone could please help me.
If have any questions, I try to explain as best as possible.
I ask now apologize for the inconvenience.
The code that I used
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
getJSON('http://MYADDRESS/json.do?_ULN[1]').then(function(data) {
alert('Your Json result is: ' + data.result); //you can comment this, i used it to debug
result.innerText = data.result; //display the result in an HTML element
}, function(status) { //error detection....
alert('Something went wrong.');
});
You can't for security reasons. See the same origin policy for JavaScript.
There are some workarounds that exploit browser bugs or corner cases, but using them is not recommended.
The best approach is having a server-side proxy that receives Ajax requests, and in turn, sends HTTP requests to other servers. This should be carefully implemented by sanitizing input and whitelisting the types of requests that are sent, and the servers that are contacted.
Your problem exist because of the browser Same-origin policy.
One solution to your problem is to use the method JSON-P or CORS. The method is well explained here : http://json-p.org/ and here : http://www.sitepoint.com/jsonp-examples/.

HTTPS request in chrome extension

I'm trying to make a chrome extension that requires to do some API calls to my secure server.
I'm testing this locally first, with my own created ssl certificates.
My problem is that when i try to do an API call to my server (https://:9000/api/project) i get an error saying: net::ERR_INSECURE_RESPONSE.
The weird thing is that i can perfectly do that POST call from other REST clients with no problem, so i know the issue is in the code of the chrome extension.
The xhr request is being done in the background.js script like this:
var sendProject = function(projectData) {
var openhuntURL = 'https://<mylocal>:9000/api/project';
xhr.open('POST', openhuntURL, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
callback(true);
}
else {
callback(false);
}
};
xhr.send(projectData);
};
I don't know what i should do to allow the extension to make that request.
By the way, just before that api call i make another api call to another website and it works just fine.
Thanks for your help!
I had the same issue, and comes to know that there is no such way you can override self signed certificate.

Coding with XMLHttpRequest for Safari Extension

In my extension, I create Access Level as "All" as well as I add whitelists as http://*/* too for every domain.
And I have following code in my JS file (which run as end script):
var feedbackmsg = "message goes here";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', 'http://mysitename.com/feedback.php', true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("html=" + feedbackmsg);
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.getAllResponseHeaders());
if (xmlhttp.status == 200) {
alert("send");
} else {
alert("error");
}
}
}
Whenever I run it, I am getting no header respond in alert box as well as error alert message. How can I resolve the problem?
Whether or not it's an extension, XMLHttpRequest (if injected into a page) isn't allowed to access anything outside the page's current domain, I think. The console just says that the request was cancelled. At least, that was the case for me when I tested it just now. (I didn't have any urls in the whitelist or blacklist when I tested, but the Access option was set to "all".)
You can try going to the same domain as the one you want to "call" with the XHR object in your code, and see if it succeeds then. If it does, you'll know it's because the domain of the page and the XHR request must match.
However, it appears you can do cross-site ajax request from the extension's global page (oddly enough). At least it seemed to work for me just now. That's actually a little scary (I'd prefer it to be more difficult to call up a random server from an extension) but it worked.
Don't know if that helps you out, though.

How can I request a url using AJAX

I am quite new in this area.
I need to find out how to make a request to my solr server using Ajax
How can I give a url(my solr server's url) in request
Any body know how to deal with this?
How can i make a request to the below mentioned url
http://mysite:8080/solr/select/?q=%2A%3A%2A&version=2.2&start=0&rows=100&indent=on
See here: Corrected the Code Snippet as below
function getProductIds() {
var xmlhttp;
if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) console.dir(xmlhttp);
else alert('no response');
var ajaxURL = "http://localhost:8080/solr/select/?q=*:*&version=2.2&start=0&rows=100&indent=on";
xmlhttp.open("GET", ajaxURL, true);
xmlhttp.send();
}
This is my code, it always showing "no response"
Thanks.
You will have to prepare the URL before sending in the request first get the URl using javascript and then encode it to ajax format like below
var URL = location.href;
var ajaxURL = encodeURIComponent(URL);
xmlhttp.open("GET",ajaxURL,true);
after reading your question clearly it seemed it is a static URL hence you can do below
var URL = "http://localhost:8080/blah blah blah";
xmlhttp.open("GET",URL,true);
Are you sure it is Get request. because get requests are most of the time cached. also log the response object into Firebug console and inspect the object to know more. Since you get no response that means the server did not send you anything for the request you made.
I'm just now working on XMLHttpRequests to solr as well and I was stuck with what seems like an identical problem. I too am quite new at this. However, the problem for me was that of same origin policy. Firefox seems to give very little feedback when this problem occurs. Chrome at least give you a error message (most of the time?).
In Chrome you can get around this, but only for development purposes, by starting it with the '--disable-web-security' command line option.
I'm yet to find a good workaround for this problem for Solr. In general you avoid the restriction by only using requests with relative paths, but that doesn't seem possible when doing a request to another port.
Ways to circumvent the policy (I haven't had time to study this too much yet)
$.ajax({
url: "url path",
context: document.body
}).done(function(data) {
alert(data);
});
This one also will work.

Categories