Reputation: 15
I have a client view that calls a PHP file via AJAX to update the database behind a form. The view is basic CRUD operations, and consists mostly of a Form and a set of inputs:
HTML
<div class="item-details">
<form id="item-info-form">
<input type="hidden" name="id" value="1" />
<input type="text" name="name" size="50" value="Item 1" />
<input type="text" id="start_date" name="start_date" value="2012-01-13" />
<input type="text" id="end_date" name="end_date" value="2014-02-03" />
<input type="text" name="location" size="50" value="Home" />
<select name="item_type">
<option value="1" selected="selected"> Type 1 </option>
<option value="2"> Type 2 </option>
<option value="3"> Type 3 </option>
</select>
<button id="update-item-info">Save Changes</button>
</form>
Upon Clicking of the button, I call a php script to update the Item in question via AJAX.
Javascript
$('#update-item-info').on('click', function (e)
{
e.preventDefault();
console.log("Updating Item Info...");
$.ajax({
type: "POST",
url: "AJAX/save-item-info.php",
data: $('#item-info-form').serialize(),
dataType: "application/JSON"
}).done(function (data)
{
console.log(data.status);
});
});
The Server PHP that this code gets posted to is:
<?php
include("../db-connection.php");
$mysqli = new mysqli($mysqli_host, $mysqli_user, $mysqli_pass, $db_name);
if ($mysqli->connect_errno)
{
$response_array['status'] = "Connect failed: %s\n" . $mysqli->connect_error;
}
if(!($stmt = $mysqli->prepare("UPDATE items SET name = ?, start_date = ?, end_date = ?, location = ?, exhibit_type = ? WHERE id = ?")))
{
$response_array['status'] = "Prepare Statement failed: " . $mysqli->error . "\n";
}
if (!($stmt->bind_param('sssssi', $_POST['name'], $_POST['start_date'], $_POST['end_date'], $_POST['location'], $_POST['exhibit_type'], $_POST['id'])))
{
$response_array['status'] = "Binding parameters failed: " . $stmt->error . "\n";
}
if (!($stmt->execute()))
{
$response_array['status'] = "Execute failed: " . $stmt->error . "\n";
}
else
{
$response_array['status'] = "Success";
}
$stmt->close();
header('Content-type: application/json');
die(json_encode($response_array));
?>
This does update the database, and if everything goes correctly, firebug tells me that data.status is set to "Success".
BUT if I comment out the database include (to simulate something going horribly wrong), the server code doesn't return anything at all, much less data.status, and I just get a generic 500 error.
Strangest of all, no matter whether the database is updated or not, ajax.done() isn't firing, so I can't see if data.status is ever being set.
Upvotes: 0
Views: 734
Reputation: 22711
dataType (default: Intelligent Guess (xml, json, script, or html))
Use:
dataType: 'json',
http://api.jquery.com/jQuery.ajax/
Also, use
echo json_encode($response_array);
instead of
die(json_encode($response_array));
Upvotes: 1