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
.
print_ryour PHP response, butechoit. Your Javascript expects JSON.xis initiating to0. Usekeyvariable instead ofx