Reputation: 1100
i have a html page that submits 2 forms(formone & formtwo) via ajax on one button click. formone is submitted to formone.php and if it was succesfully sent formtwo is submitted to formtwo.php. Everything works fine. Except i need to send data via POST to another php script (on another server, but for now i'm testing it on the same server). I tried it with the following code but it wont work (i don't get any errors though).
Curl code i used!
function transferData()
{
//Set up some vars
$url = 'test.php';
$user = 'sampletext';
$pw = 'sampletext';
$fields = array(
'user'=>urlencode($user),
'pw'=>urlencode($pw)
);
// Init. string
$fields_string = '';
// URL-ify stuff
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
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,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
}
This is the code for my ajax form submission:
function submitforms()
{
FormSubmissionOne();
function FormSubmissionOne()
{
//Form 1
var $form = $('#formone');
$.ajax(
{
type: 'POST',
url: $form.attr('action'),
data: $form.serialize(),
success: function (msg)
{
FormSubmissionTwo();
},
error: function(msg)
{
alert(msg);
}
});
}
function FormSubmissionTwo()
{
//Form 2
var $form2 = $('#formtwo');
$.ajax(
{
type: 'POST',
url: $form2.attr('action'),
data: $form2.serialize(),
success: function (msg)
{
alert(msg);
//redirection link
window.location = "test.php";
}
});
}
}
This is test.php (receiving script from curl function)
$one = $_POST['user'];
$two = $_POST['pw'];
echo "results:";
echo $one;
echo "\r\n";
echo $two;
echo "\r\n";
Upvotes: 1
Views: 2004
Reputation: 13128
There are a few issues, firstly, CURLOPT_POST
is for a boolean
not a count.
So change this:
curl_setopt($ch,CURLOPT_POST,count($fields));
to
curl_setopt($ch,CURLOPT_POST, 1); // or true
Secondly, you need to tell CURL that you want the returned data. You do that using CURLOPT_RETURNTRANSFER
So your curl
related code should look like this:
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
//execute post
$result = curl_exec($ch);
print_r($result); // just see if result
//close connection
curl_close($ch);
Upvotes: 3