How to Send POST Requests with PHP cURL and jQuery AJAX Form
This guide shows how to use PHP's cURL functions to post data to a URL and how to submit a form via jQuery Form's ajaxSubmit, including CORS header setup for cross‑origin requests, with complete code examples for both server‑side and client‑side implementations.
1. Using PHP cURL
The following function builds a query string from an associative array, initializes a cURL session, sets the necessary options, executes the request, and returns the response.
function curlPost($url, $params)
{
$postData = '';
foreach ($params as $k => $v) {
$postData .= $k . '=' . $v . '&';
}
rtrim($postData, '&');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POST, count($postData));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
echo curlPost("http://test.com", array('name' => "tank"));Previously many people used cURL to fetch email address books, but this method is no longer allowed by some services.
2. Submitting a Form with jQuery Form and AJAX
First, download jquery.form.js. Then use the following JavaScript to intercept the form submission and send it via AJAX.
$('#testform').submit(function() {
$(this).ajaxSubmit({
type: 'post', // submission method
dataType: "json", // expected response type
url: 'your url', // target URL
success: function(data) {
// handle returned data (usually JSON)
alert('Submission successful!');
}
});
$(this).resetForm(); // reset the form after submission
return false; // prevent default form submission
});On the server side, set the appropriate CORS headers if the request comes from a different origin.
header("Access-Control-Allow-Origin: *"); // allow all origins
// or restrict to a specific domain
header("Access-Control-Allow-Origin: http://www.test.com");Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
