Sending a form in a JSON object via AJAX to PHP server
Coffeescript
#
# * Function: Sends via AJAX the form data in a JSON object
#
sendForm = () ->
formData = $("form").serializeObject()
$.ajax
url: "libs/process.php"
type: "POST"
data: JSON.stringify(formData)
cache: false
success: (response) ->
# Do something...
error: ->
# Do something else...
return
Notice: serializeObject()
is a very useful function that you can find here.
PHP (process.php)
// Receives the JSON object from AJAX call
$json_data = file_get_contents("php://input");
// Checks if it's empty or not
if( !empty($json_data) ){
// Decodes the JSON object to an Array
$data = json_decode($json_data, true);
// Now you can access to your single datas as a normal array.
// For example: if in your form you had a field with name="city" you can print it like so:
echo $data["city"];
} else {
echo "Empty JSON object, something's wrong!";
}