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 + "");
},
});
});
});