Reputation: 1144
Im trying to do an ajax request to an external url.Right now im doing it in php
as
$data = array(
'TokenID' => $tokenid,
'APIKey' => $api_key,
'EcryptedData' => $encrypted_data,
'TokenScheme' => 4
);
//convert to JSON
$json = json_encode($data);
//curl config
$ch = curl_init("https://testingonetwo.com/rest/");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json', //we are using json in this example, you could use xml as well
'Content-Length: '.strlen($json),
'Accept: application/json') //we are using json in this example, you could use xml as well
);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$outputjson = curl_exec($ch);
Im trying to do the same using javascript.I tried this using jquery,but didnt work out
code for jquery which I tried is
$data = array(
'TokenID' => $tokenid,
'APIKey' => $api_key,
'EcryptedData' => $encrypted_data,
'TokenScheme' => 4);
$json = json_encode($data);
$.ajax({
type: "POST",
url: 'https://testingonetwo.com/rest/',
data: {data:$json},
success: success,
dataType: "json"
});
alert(result);
function success(result) {
alert('done');
}
Im new to both the client side browser scripts.Kindly help me try the above to javascript,which I prefer.Looking forward for some help.
Upvotes: 2
Views: 5297
Reputation: 42736
If the server does not support cors, or does not employ JSONP responses you will need to use a middleman script to get the data.
JS
$.ajax({
type: "POST",
url: 'https://YourOwnDomain.com/myPhpScript.php',
success: success,
dataType: "json"
});
PHP
...
$outputjson = curl_exec($ch);
echo $outputjson;
die;
If they employ jsonp responses you can use jQuery's jsonp abilities to get the data, look at the other domain's documentation on how to call their rest service they should have details about doing a jsonp call if they do allow it. The general code would be something like:
$data = {
'TokenID':$tokenid,
'APIKey':$api_key,
'EcryptedData':$encrypted_data,
'TokenScheme':4};
$.ajax({
type: "POST",
url: 'https://testingonetwo.com/rest/?callback=?',
data: {data:$data},
success: success,
dataType: "jsonp"
});
But as you have what looks like a API key and a TokenID if these are supposed to be secret (ie the end users should not be able to see them) then you shouldnt use the javascript that shows those details, ie use the middleman script.
Upvotes: 5