Submit a form with ajax
This is a basic operation that you might have to do when upgrading an old web app.
One solution is using jQuery .serialize() function
Method #1: Sent using CGI params key=value pairs:
var $form = this.$("form");
var data = $form.serialize(); // becomes text with proper encoding for CGI params
$.ajax({
method: "POST",
url: "/run.php",
data: data,
success: function (data)
{
var response;
try {
response = JSON.parse(data);
if (response.message !== undefined && response.message.indexOf("Success") >= 0) {
notifier.info_x(response.message);
}
else {
if (response.message !== undefined) {
notifier.error_x(response.message);
}
}
}
catch (e) {
notifier.error_x("Could not parse response");
}
},
error: function ()
{
notifier.error_x("Failed to send request");
}
});
Method #2 Sent using JSON text content (supports better multi-level objects):
var $form = this.$("form");
var json = JSON.stringify({ username: this.get("username"), password: this.get("password") });
$.ajax({
type: "POST",
url: this.url(),
contentType: "application/json",
data: ,
$.ajax({
method: "POST",
url: "/run.php",
data: data,
success: function (data)
{
var response;
try {
response = JSON.parse(data);
if (response.message !== undefined && response.message.indexOf("Success") >= 0) {
notifier.info_x(response.message);
}
else {
if (response.message !== undefined) {
notifier.error_x(response.message);
}
}
}
catch (e) {
notifier.error_x("Could not parse response");
}
},
error: function ()
{
notifier.error_x("Failed to send request");
}
});
If you are using PHP to read the JSON, you can use
if ($_SERVER['REQUEST_METHOD'] === "POST" // to create
|| $_SERVER['REQUEST_METHOD'] === "PUT") // to update
{
$raw_request = file_get_contents('php://input');
$request = json_decode($raw_request);
$requestArray = get_object_vars($request);
}
Recent Comments