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?
-
possible duplicate: stackoverflow.com/questions/8567114/…ilpaijin– ilpaijin2014年03月29日 11:41:05 +00:00Commented Mar 29, 2014 at 11:41
-
What happens when you run that code? What does the JavaScript console say? What does the Net tab of your browser's developer tools say?Quentin– Quentin2014年03月30日 20:56:06 +00:00Commented Mar 30, 2014 at 20:56
-
possible duplicate of Ajax request to external url using javascriptQuentin– Quentin2014年03月30日 20:56:50 +00:00Commented Mar 30, 2014 at 20:56
-
You appear to have asked about seven variations of this question over the last couple of days. Most of them don't have accepted answers. If you aren't getting suitable answers to your questions, then edit them to add more information, don't ask variations of them.Quentin– Quentin2014年03月30日 20:58:09 +00:00Commented Mar 30, 2014 at 20:58
1 Answer 1
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