I’ve got a php page setup as follows:
<?php
if(isset($_POST['submit'])){
// Validate results and if correct insert into the DB
// Else add the respective errors
$data[0]['error_1'] = 'Error_1_text';
$data[0]['error_2'] = 'Error_2_text';
/*
.
.
.
*/
$data[0]['error_n'] = 'Error_n_text';
print_r(json_encode($data[0]));
}
?>
This is where the following AJAX request sends a POST request. If the entered form is valid it is inserted into DB else if it has any error(s) all the errors are appended to the array index $data[0], and finally the array is json_encoded, and print_r()ed.
<body>
<div class="ssss"></div>
</body>
<script>
$.ajax({
url: "http://localhost/path/to/above/file",
method: "POST",
data: {
submit: 'yes',
form_data_0: 'form_text',
form_data_1: 'form_text',
form_data_2: 'form_text'
},
success: function(data){
// Code to check if errors were present
result = JSON.parse(data);
if (result.hasOwnProperty('0')) {
$.each(result['0'], function(key, error) {
let x = 0;
// Display each error into a modal
$("div#ssss").html('<div id="dmessage_' + x + '" class = "modal" style="display:block"><p id = "pmessage_' + x + '">' + error + '</p></div>');
x++;
});
}
}
});
</script>
On success of the AJAX request, the data is JSON.parse()d and this result is assigned to a variable result. Then we check if there were any errors during the post-processing of the form. using if (result.hasOwnProperty('0')), if so, the aim is to display each error in a <p>error</p> with a dynamic id enveloped in a <div> with a dynamic id.
To achieve this I created a $.each() loop and initiated a variable x = 0. Now we loop over the contents of the $.each() loop, where we intend to display a <div></div> with contents shown in the code along with the error text being sent over by PHP from the back-end and the id being dmessage_ concatenated with the current value of x. Once done, we increment x and loop over again for the next error.
However what happens is, only 1 error-box is displayed, no-matter how many errors are being sent by PHP. I confirmed that by adding the following piece of code inside the if() statement:
let array = [];
$.each(result['0'], function(key, error) {
// Display each error into a modal
});
array[x] = array.push(error);
console.log(array); // Displays all the errors correctly inside the console
Also thing worth noting is that although only one error-box is displayed all are created for each error. I confirmed that by console.log()ging $().html() this piece of code
,
however the elements tab in developer tools along with the browser display window shows only one error-box
.
Advertisement
Answer
I know you got a solution but I will post my answer
1st: echo json_encode
2nd: You return $data[0] from PHP .. that mean the array will looks like
['error_1' => 'Error_1_text' , 'error_2' => 'Error_2_text' , ......]
3rd: On success function You loop through result[0] which will be in this case = 'error_1' => 'Error_1_text'
4th: No need to use x at all you can directly use key
5th: You can directly use dataType: 'json' instead of JSON.parse(data)
6th: change .html( to .append(
Consider all of the above then your code should looks like
php
<?php
if(isset($_POST['submit'])){
// Validate results and if correct insert into the DB
// Else add the respective errors
$data['error']['error_1'] = 'Error_1_text'; // change all `$data[0]` to `$data['error']` it will be much easier
$data['error']['error_2'] = 'Error_2_text';
/*
.
.
.
*/
$data['error']['error_n'] = 'Error_n_text';
echo(json_encode($data)); // <<<< just $data here
}
?>
JS
<body>
<div class="ssss"></div>
</body>
<script>
$.ajax({
url: "http://localhost/path/to/above/file",
method: "POST",
dataType : 'json', //<<<<< here
data: {
submit: 'yes',
form_data_0: 'form_text',
form_data_1: 'form_text',
form_data_2: 'form_text'
},
success: function(data){
// Code to check if errors were present
if (data.error) { //<<<<< here
$.each(data.error, function(key, error) {
// Display each error into a modal
$("div#ssss").append('<div id="dmessage_' + key + '" class = "modal" style="display:block"><p id = "pmessage_' + key + '">' + error + '</p></div>');
});
}else{
$("div#ssss").html('');
}
}
});
</script>