0

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 codeconsole shows three objects being created,
however the elements tab in developer tools along with the browser display window shows only one error-boxElements shows only one .

8
  • 1
    Don't print_r your PHP response, but echo it. Your Javascript expects JSON. Commented Jul 19, 2020 at 8:58
  • @Michael I tried but that doesn't help. Commented Jul 19, 2020 at 9:00
  • "Doesn't help" in what way? Commented Jul 19, 2020 at 9:01
  • 1
    Your x is initiating to 0. Use key variable instead of x Commented Jul 19, 2020 at 9:01
  • 1
    @RiteshKhandekar Thank you that indeed solves my problem. Commented Jul 19, 2020 at 9:05

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

Comments

0

This solves my problem:

<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);
            let x = 0;
            if (result.hasOwnProperty('0')) {
                $.each(result['0'], function(key, error) {
                    // Display each error into a modal
                    $("div#ssss").append('<div id="dmessage_' + x + '" class = "modal" style="display:block"><p id = "pmessage_' + x + '">' + error + '</p></div>');
                });
            }
        }
    });
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.