Reputation: 3166
I am trying to send a post data using a proxy script to perform cross-domain ajax.
var data = "url=http://www.fhm.com.ph/templates/100sexiestwomen2013/ajax/set.php&id=13&index=0&action=add";
$.ajax({
url: "proxy.php",
data: data,
type: "POST",
success: function(data, textStatus, jqXHR) {
console.log('Success ' + data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('Error ' + jqXHR);
}
});
Then I tried to parse the data to use as the url and parameters in my proxy script.
<?php
//set POST variables
$url = $_POST['url'];
unset($_POST['url']);
$fields_string = "";
//url-ify the data for the POST
foreach($_POST as $key=>$value) {
$fields_string .= $key.'='.$value.'&';
}
$fields_string = rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
But it turns out it doesn't post the data correctly.
Try using postman, a chrome extension POSTMAN. And give the proper key-value pairs as seen in the data
.
It'll give you null
on first submit and selected
on second.
What am I missing out.
EDIT
<?php
//set POST variables
$url = $_POST['url'];
// unset($_POST['url']);
// $fields_string = "";
// //url-ify the data for the POST
// foreach($_POST as $key=>$value) {
// $fields_string .= $key.'='.$value.'&';
// }
// $fields_string = rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$_POST);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
As shown in the edit, i remove my manual build, instead I used the POST array.
Upvotes: 1
Views: 5348
Reputation: 97707
You have to properly encode your data
var data = "url=" + encodeURIComponent("http://www.fhm.com.ph/templates/100sexiestwomen2013/ajax/set.php")+"&id=13&index=0&action=add";
Since you url parameter contains characters that has special meaning in urls.
Upvotes: 1
Reputation: 781721
Use an object in your Javascript for the data
, so that jQuery will encode it properly:
var data = {
url: "http://www.fhm.com.ph/templates/100sexiestwomen2013/ajax/set.php&id=13",
index: 0,
action: "add"
};
And in the PHP, use an array for CURLOPT_POSTFIELDS
:
curl_setopt($ch,CURLOPT_POSTFIELDS,$_POST);
PHP will encode this properly.
Upvotes: 2