How to send ajax post request on https?

Member

by jasen , in category: PHP General , 4 days ago

How to send ajax post request on https?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , 3 days ago

@jasen 

To send an AJAX POST request on an HTTPS connection, you can use the following example code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
var xhr = new XMLHttpRequest();
var url = "https://example.com/api";
var params = "data=someData";

xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
        console.log(xhr.responseText);
    }
};

xhr.send(params);


In this code snippet, we are creating a new instance of the XMLHttpRequest object and specifying the URL and parameters for the POST request. We then set the request header to specify the content type as application/x-www-form-urlencoded. We add an event listener function to handle the response from the server and finally, we send the POST request with the specified parameters.


Make sure to replace https://example.com/api with the actual URL of the API you want to send the request to, and data=someData with the actual data you want to send in the request body. Remember that the server must support HTTPS connections for this code to work.