Reputation: 1144
I wanted to perform a POST request to an external url using javascript. Currently I use php server side to sent the request
$data = array(
'TokenExID' => $tokenex_id,
'APIKey' => $api_key,
'EcryptedData' => $encrypted_data,
'TokenScheme' => 4
);
$ch = curl_init("https://api.testone.com/TokenServices.svc/REST/TokenizeFromEncryptedValue");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json', //
'Accept: application/json') //
);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
The same code I wanted to do it in a javascript.
var url = "https://api.testone.com/TokenServices.svc/REST/TokenizeFromEncryptedValue";
var params = "abcd";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
I got this sample code of javascript,but im not sure how to do this.Im new to javascript but couldnt find a way to do it.Can some one help me out?
Upvotes: 1
Views: 580
Reputation: 7187
if you are new to javascript I strongly recommend that you use jQuery, it will ease your work a lot. Search online how to include it in your page, then this is the code.
var data = {
param1: "value1",
param2: "value2"
// add here more params id needed followinf the same model
};
$.ajax({
type: "POST",
url: 'http://www.myrestserver.com/api',
data: data,
success: success
});
function success(result) {
// do something here if the call is successful
alert(result);
}
https://api.jquery.com/jQuery.ajax/
If you want to go further check this: JavaScript post request like a form submit
Hope it helps, Paul
Upvotes: 3