0

I have a very basic form with one input field. I want to submit this form using AJAX and display the response within a div on the page.

Some points. - The response from the API is JSON datatype. - The API is not on the same server as the client making the request.

With my current code, i can see the request is being made but I am not getting anything back. I do see a warning in my debug console but I am not sure how to proceed or how to update my code to make it work.

Warning in debug Console:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.ssllabs.com/api/v2/analyze?&host=www.domain.com. This can be fixed by moving the resource to the same domain or enabling CORS.

-- My HTML --

<body>
  <form id="myAjaxRequestForm">
    <fieldset>
      <legend>Request</legend>
      <p>
        <label for="hostname">Host:</label>
        <input id="hostName" type="text" name="hostName" />
      </p>
      <p>
        <input id="myButton" type="button" value="Submit" />
      </p>
    </fieldset>
  </form>
  <div id="anotherSection">
    <fieldset>
      <legend>Response</legend>
      <div id="ajaxResponse"></div>
    </fieldset>
  </div>
</body>

-- My Jquery with AJAX --

$(document).ready(function() {

  //Stops the submit request
  $("#myAjaxRequestForm").submit(function(e) {
    e.preventDefault();
  });

  //checks for the button click event
  $("#myButton").click(function(e) {

    //get the form data and then serialize that
    dataString = $("#myAjaxRequestForm").serialize();

    //get the form data using another method
    var hostName = $("input#hostName").val();
    dataString = "host=" + hostName;

    //make the AJAX request, dataType is set to json
    //meaning we are expecting JSON data in response from the server
    $.ajax({
      type: "GET",
      url: "https://api.ssllabs.com/api/v2/analyze?",
      data: dataString,
      dataType: "json",

      //if received a response from the server
      success: function(response) {
        $("#ajaxResponse").append("<b>Server Name:</b> " + response.first + "");
        $("#ajaxResponse").append("<b>Port:</b> " + response.second + "");
        $("#ajaxResponse").append("<b>Protocol:</b> " + response.third + "");
      },

    });
  });

});
user3436467
  • 1,763
  • 1
  • 22
  • 35
  • I updated the datatype to "jsonp", re-ran the api call and got this error in the debug console SyntaxError: missing ; before statement analyze:1:7 the file 'analyze' belongs to the api server - does this mean it doesn't support jsonp or is there another error in my code somewhere? – user3436467 Apr 06 '15 at 02:45

2 Answers2

0

Cross-Origin Request Blocked: means you can not call https:// sites from http:// and most browsers disable this.

Solution:

1) Use jsonp instead of json for dataType: "json" if it works, all is fine

2) if jsonp is not supportted, make one php file in your working directory, access API VIA curl. and echo response as json. and then only call that php from your ajax.

UPDATE IF JSON FAILS

I assume you are using php

  1. Create a php file called api.php in your directory

    <?php
    header( "Content-Type: application/json" );
    //create cURL connection
    $curl_connection =curl_init('https://api.ssllabs.com/api/v2/analyze?host='.$_REQUEST['host']);
    
    ///set options
    curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($curl_connection, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
    curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
    
    
    //perform our request
    $result = curl_exec($curl_connection);
    echo $result;
    //close the connection
    curl_close($curl_connection);
    
    
    ?>
    
  2. Now Make ajax call to api.php from your javascript not https://api.ssllabs.com/api/v2/analyze?

    $.ajax({
      type: "GET",
      url: "yourhost/yourpath/api.php", //change this that suits you
      data: dataString,
      dataType: "json",
      ....
    

Finally populate values like this

    $("#ajaxResponse").append("<b>Server Name:</b> " + response.endpoints[0].serverName+ "");
    $("#ajaxResponse").append("<b>Port:</b> " + response.port+ "");
    $("#ajaxResponse").append("<b>Protocol:</b> " + response.protocol+ "");
Sagar Devkota
  • 1,192
  • 8
  • 13
  • Thanks for your suggestion. I tried your first solution. I updated the datatype to "jsonp", re-ran the api call and got this error in the debug console SyntaxError: missing ; before statement analyze:1:7 the file 'analyze' belongs to the api server - does this mean it doesn't support jsonp or is there another error in my code somewhere? – user3436467 Apr 06 '15 at 02:47
  • please add following line and let me see your output. console.log(result); on the first line inside success fucntion – Sagar Devkota Apr 06 '15 at 02:52
  • sure, i did that. where do i find the console.log output ? – user3436467 Apr 06 '15 at 05:46
  • F12 for chrome and click console tab – Sagar Devkota Apr 06 '15 at 05:53
  • here it is from chrome: analyze?&callback=jQuery111003550140524748713_1428300933030&host=www.verisign.com&_=1428300933031:1 Uncaught SyntaxError: Unexpected token : – user3436467 Apr 06 '15 at 06:16
  • i got closer with your suggested api.php solution: after making a call to api.php - see the div on the html was populated but the values where 'undefined' Server Name: undefined Port: undefined Protocol: undefined in my code I have this but i have a feeling its wrong? $("#ajaxResponse").append("Server Name: " + response.first + ""); what is the correct parameter i should be using here instead of 'response.first' ? – user3436467 Apr 06 '15 at 06:30
  • Yes i have updated how you shoud update div and curl part in php so update once – Sagar Devkota Apr 06 '15 at 06:45
  • works perfectly with that. I tried adding a few more lines to catch more data from the api response but I got 'undefined' on those... response.grade and response.ipAddress I followed your example but trying to understand why they didnt work.. the case sensativity is exactly as how it is in the api response.. – user3436467 Apr 06 '15 at 06:56
  • all good.. as the data was after the first endpoint i had to add in: endpoints[0] so it looks like this: response.endpoints[0].grade thanks for your assistance Sagar! immensely appreciated!! – user3436467 Apr 06 '15 at 07:00
  • please see this image http://prntscr.com/6q622m and do as your needs. your upvote and accepted answer will be appreciated – Sagar Devkota Apr 06 '15 at 07:01
  • sorry, i don't have enough reputation to up vote. I have one final question and I am happy to open a new thread if required. Basically want to know how to add an if statement on one of the callbacks i.e. if (response.endpoints[0].statusMessage == "ready") { do stuff.. } but it doesnt seem to work.. – user3436467 Apr 06 '15 at 08:34
0

Since you're using JSON, you can change the dataType attribute to jsonp, and the request will complete successfully, ignoring Cross-Origin policy.

$.ajax({
  type: "GET",
  url: "https://api.ssllabs.com/api/v2/analyze?",
  data: dataString,
  dataType: "jsonp",
...

Edit: This request successfully circumvents Cross-Origin policy, but it will still cause an Unexpected Token : error. See here for more information on this error. If you have access to the server from which you're requesting data, add the response header Access-Control-Allow-Origin:'*'. See here for more information on CORS headers.

Community
  • 1
  • 1
IronFlare
  • 2,287
  • 2
  • 17
  • 27
  • I updated the datatype to "jsonp", re-ran the api call and the CORS warning is gone but now I get this error in the debug console SyntaxError: missing ; before statement analyze:1:7 the file 'analyze' belongs to the api server - does this mean it doesn't support jsonp or is there another error in my code somewhere? – user3436467 Apr 06 '15 at 02:46
  • Unfortunately, that seems to be a result of the server not supporting JSONP. I determined that from looking on [this post](http://stackoverflow.com/questions/20658674/syntaxerror-missing-before-statement-jquery-jsonp), so it might be a good place to start for answers. Also, [This slideshow](http://www.slideshare.net/SlexAxton/breaking-the-cross-domain-barrier) is an excellent source of information around getting past Cross-Origin policy. – IronFlare Apr 06 '15 at 03:22