Reputation: 15
I have a php page called by an ajax function which inserts my form into the database. But what I'd like to do now is to set some conditions to say "if any of the fields are empty, kill the process and return an error message to the ajax that it didn't work, please fill in all the fields".
I've began with it here, but I don't know how to put it... PHP code:
$name1 = $_POST['name'];
$artist1 = $_POST['artist'];
$url1 = $_POST['url'];
$lyrics1 = $_POST['lyrics'];
if (empty($name1){
echo 'Please fill all the fields.';
};
if (empty($artist1){
echo 'Please fill all the fields.';
};
if (empty($url1){
echo 'Please fill all the fields.';
};
$stmt = $mysqli->prepare("INSERT INTO song VALUES (?)");
$stmt->bind_param('ssssi', $name, $artist, $url, $lyrics, $_SESSION['user_id']); // bind $sample to the parameter
// escape the POST data for added protection
$name = isset($_POST['name'])
? $mysqli->real_escape_string($_POST['name'])
: '';
$artist = isset($_POST['artist'])
? $mysqli->real_escape_string($_POST['artist'])
: '';
$url = isset($_POST['url'])
? $mysqli->real_escape_string($_POST['url'])
: '';
$lyrics = isset($_POST['lyrics'])
? $mysqli->real_escape_string($_POST['lyrics'])
: '';
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
// this is the id of the form
$("#add_form").submit(function() {
var url = "includes/addtrack.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#add_form").serialize(), // serializes the form's elements.
success: function(data)
{
//alert(data); // show response from the php script.
$.ajax({ //Get the name of the artist
url: "includes/getsongs.php",
type: "POST",
data: {id: <?php echo $_SESSION["user_id"]; ?>},
success: function(data) {
//called when successful
console.log("The data is:");
console.log(data);
$(".yoursongs").html(data); //Update
},
error: function(e) {
//called when there is an error
console.log(e.message);
}
});
} error: function(e) {
//called when there is an error
console.log(e.message);
}
});
return false; // avoid to execute the actual submit of the form.
});
Upvotes: 0
Views: 476
Reputation: 1724
One of the best practice to do it is to make your PHP script output JSON with according headers. And make your Javascript check for the response.
Instead of using echo or print, create a function that returns a JSON object and HTTP headers:
function json_response($data, $http_status=200) {
header('Content-Type: application/json');
http_response_code($http_status);
print json_encode($data);
}
// [...]
if (empty($name1)) json_response(array(
'message' => 'Please fill all the fields'
), 400);
// [...]
On the javascript side, the error callback is called when the HTTP status is not 200:
// [...]
error: function(xhr) { {
console.log(xhr.responseJSON.message);
}
// [...]
Upvotes: 0
Reputation: 1430
I think best way to use json and add status type on result array, something like this:
if (empty($name1)){
$result['error'][] = 'Please fill all the fields.';
};
if (empty($artist1)){
$result['error'][] = 'Please fill all the fields.';
};
if (empty($url1)){
$result['error'][] = 'Please fill all the fields.';
};
if(!empty($result['error']))
die(json_decode($result));
$stmt = $mysqli->prepare("INSERT INTO song VALUES (?)");
$stmt->bind_param('ssssi', $name, $artist, $url, $lyrics, $_SESSION['user_id']); // bind $sample to the parameter
// escape the POST data for added protection
$name = isset($_POST['name'])
? $mysqli->real_escape_string($_POST['name'])
: '';
$artist = isset($_POST['artist'])
? $mysqli->real_escape_string($_POST['artist'])
: '';
$url = isset($_POST['url'])
? $mysqli->real_escape_string($_POST['url'])
: '';
$lyrics = isset($_POST['lyrics'])
? $mysqli->real_escape_string($_POST['lyrics'])
: '';
/* execute prepared statement */
$stmt->execute();
$result['success'] = sprintf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();
die(json_decode($result));
?>
// this is the id of the form
$("#add_form").submit(function() {
var url = "includes/addtrack.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $("#add_form").serialize(), // serializes the form's elements.
success: function(data)
{
if(data.success){
//alert(data); // show response from the php script.
$.ajax({ //Get the name of the artist
url: "includes/getsongs.php",
type: "POST",
data: {id: <?php echo $_SESSION["user_id"]; ?>},
success: function(data) {
//called when successful
console.log("The data is:");
console.log(data);
$(".yoursongs").html(data); //Update
},
error: function(e) {
//called when there is an error
console.log(e.message);
}
});
} else {
//called when there is an error
console.log(data.error);
}
} error: function(e) {
//called when there is an error
console.log(e.message);
}
});
return false; // avoid to execute the actual submit of the form.
});
Upvotes: 1