5

I've been trying to figure this out for hours, though I'm too uneducated in web development to understand. Heres the case:

Another website has a script that they obtain information from the following way:

    var url = "numbers.php";
parameters = "scoreid=" + document.getElementById('whatscore').value;
parameters += "&num=" + document.getElementById('num1b1').value;

xmlhttp2=GetXmlHttpObject();
if (xmlhttp2==null) {
    alert ("Your browser does not support XMLHTTP!");
    return;
}

xmlhttp2.onreadystatechange = function() {
    if (xmlhttp2.readyState==4) {
        scorespot.innerHTML=xmlhttp2.responseText;              // load 
        setScores(document.getElementById('gradelvl').value);   // set 
        document.getElementById('submitscorebtn').style.display="none";
    }
}
xmlhttp2.open("POST",url,true);
xmlhttp2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp2.setRequestHeader("Content-length", parameters.length);
xmlhttp2.setRequestHeader("Connection", "close");
xmlhttp2.send(parameters);

I've attempted to do the same thing, though when I attempt it I get the cross-origin error. I know their are ways to do it with jsonp and other things, though I have no clue where to start at all for this.

When I attempt to directly request information from their page, the numbers.php page, such as example.com/numbers.php?scoreid=131&num=41 . I always get returned with "Error: incorrect parameter syntax".

Can anybody please tell me how I would fix this in my case? I only know PHP and Javascript well, I'm very uneducated with Ajax and other things or external libraries.

I appreciate all help whatsoever! NOTICE: I DO NOT HAVE ACCESS TO THE WEBSERVER.

Andre
  • 778
  • 1
  • 5
  • 23

4 Answers4

6

If you do not have access to your server configuration, and if you do not control the external php script (assuming it's not set up to serve as a reverse proxy), then you absolutely cannot use a standalone javascript solution for this.

Rather, you would have to make the external request from your own local php script. Then you would call your local php script from Ajax, and this will work since you are accessing a local file, and thus not violating CORS.

Here is an example of an Ajax call thru a local PHP script.

Imagine a scenario where you allow users to lookup an album name. The user enters the name of the song, and the artist. You make a request to a 3rd party api, and return the response back to the user via a JavaScript alert notification. For this example, assume the user enters 'Black' and 'Pearl Jam' as the song and artist names

Ajax POST to Local PHP Script with HTML Example:

<html>
  <head>
  <!-- Load jQuery Library from Google -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
  </head>        

  <body>
    <h1> Ajax to local PHP Script Example: </h1>

    <form id="getArtist">
      Artist: <input type="text" placeholder="Pearl Jam">
      Song: <input type="text" placeholder="Black">
      <input type="submit" value="Click Here to Active Ajax Call">
    </form>

  </body>
</html>

<script type='text/javascript'>
$("#getArtist").submit(function(event) { //Listen to when the Submit is pressed
    event.preventDefault();  //Stop the submit from actually performing a submit
    $.post("local_script.php", { song: "Black", artist: "Pearl Jam", dataType: "json"}) //prepare and execute post
        .done(function(response) { //Once we receive response from PHP script
            //Do something with the response:
            alert("The album name is: " +response);
            //Look into JSON.parse and JSON.stringify for accessing data 
         });
    });
</script>

PHP GET

<?php
$url = 'http://api.music.com/album';

$song = urlencode($_GET['song']));    //Need to url encode
$artist = urlencode($_GET['artist']); //Need to url encode

$response = file_get_contents($url .'?song=' .$song .'&artist=' .$artist);
    //**The url looks like http://api.music.com/album?song=Black&artist=Pearl+Jam

//** For purposes of this demo, we will manually assume the JSON response from the API:
$response = '{ "album": "Ten" }'; //(Raw JSON returned by API)
echo $response; //Return the response back to AJAX, assuming it is already returned as JSON. Else encode it json_encode($response)

PHP POST (using curl)

<?php
$url = 'http://api.music.com/album';

$song = urlencode($_GET['song']));    //Need to url encode  
$artist = urlencode($_GET['artist']); //Need to url encode

//$headers = array("Key: " ."Value","Key: " ."Value", //Set any headers, if required.

$post = 'song=' .$song .'&artist=' .$artist; //Prepare Post parameters

/* Configure Curl */
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);    
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  //Allow music api to send response
curl_setopt($ch, CURLOPT_POST, 1);            //Signifyd that we are doing a POST request
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
//curl_setopt($curl, CURLOPT_HTTPHEADER, $header); //Only if you need to send headers


/* Get Response */
$response = curl_exec($ch);

//** For purposes of this demo, we will manually assume the JSON response from the API:
$response = '{ "album": "Ten" }'; //(Raw JSON returned by API)

echo $response; //Send response back to Ajax, assuming it was already returned in JSON. Else encode it.

Further reading on Ajax requests:
https://api.jquery.com/jquery.get/
https://api.jquery.com/jquery.post/

  • So I attempted what you did, though I'm getting "SyntaxError: missing ) after argument list", on the $.get line of Ajax, do you know why this is occuring? – Andre Apr 24 '15 at 03:43
  • Sorry, wrote this on the fly. Fixed syntax error, try again please. –  Apr 24 '15 at 03:58
  • @RobinMullins I still can't get this to work, would you mind adding me on Skype? Trust me when I say you can 100% turn this request down – Andre Apr 24 '15 at 04:17
  • Lol thanks, I know I can turn it down. I don't skype, but I can invite you to a chat. Also, I am about to make another revision, and include an html sample of how to call this function. –  Apr 24 '15 at 04:29
  • @RobinMullins Thanks, looking forward to the revision :)! – Andre Apr 24 '15 at 04:41
  • Made the revision, and confirmed tested. Make sure your `local_script.php` is in the same directory as the html/js file. If you still have issues, ping me and we can move to chat. –  Apr 24 '15 at 04:57
  • @RobinMullins , Ping...? Not sure how this works.. Would you please join the chat room http://www.disposablechat.com/chat/Test?password= . I'll wait :) – Andre Apr 24 '15 at 05:08
  • @RobinMullins I believe the chat has expired, if you can message me somehow here or post it that would be great as to how you to there :)! – Andre Apr 24 '15 at 05:46
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/76205/discussion-between-master-and-rob-mullins). – Andre Apr 24 '15 at 18:50
2

This may prove useful: How do I send a cross-domain POST request via JavaScript?

Also, if you do not need to use POST you could use jsonp (no CORS setup required)

Community
  • 1
  • 1
alexreardon
  • 606
  • 5
  • 12
0

Your easiest solution here is to enable CORS, assuming you control the page you're trying to access, which you can do in a number of different ways as detailed by that site. This error will also go away if you try and make your AJAX request from the same host as the page your Javascript code is running on--same host in this case means from the same domain (including the same subdomain).

moberemk
  • 1,597
  • 1
  • 18
  • 39
0

There is NO WAY (using XMLHttpRequest), If you have no control to the remote server

CORS introduces a standard mechanism that can be used by all browsers for implementing cross-domain requests. The spec defines a set of headers that allow the browser and server to communicate about which requests are (and are not) allowed

Cross-site HTTP requests initiated from within scripts have been subject to well-known restrictions, for well-understood security reasons. For example HTTP Requests made using the XMLHttpRequest object were subject to the same-origin policy. In particular, this meant that a web application using XMLHttpRequest could only make HTTP requests to the domain it was loaded from, and not to other domains.

That's the rule. Even you may find a way to bypass that, it will be fixed some day, simply because that's a violation of the rule

miken32
  • 42,008
  • 16
  • 111
  • 154
Shiji.J
  • 1,561
  • 2
  • 17
  • 31
  • 1
    Of course there is a way. I know of one it's just difficult, I could always use the actual website and modify it's javascript and execute it there. I've done it through chromes debuggers tools. I can probably do it in an iframe, I guess I have to take that route. – Andre Apr 24 '15 at 01:55
  • Actually, I misread the question. @Shiji.Jiang is correct... apologies for the downvote. If you cannot access the server configuration to where your javascript is hosted, and if you do not control the 3rd party API, you absolutely cannot use a complete javascript for this. You CAN however, create a local php script to make the request, and call this local php file from your javascript (since it won't violate CORS!) –  Apr 24 '15 at 02:33
  • It's unclear if the OP can use local php or not. If he/she can, then OP can use the method in my answer. –  Apr 24 '15 at 03:14