在AJAX中提交表单后显示用户的所有错误

I have a form. If something is wrong then error message is shown. Currently it is only showing one error message, even though I am pushing the error messages into an array in PHP and json encoding the array.

What I would basically like to do is this:

$errors = []; // Array creation
if (strlen($username) < 5) { 
    // Add this error to our list
    $errors[] = 'Username not valid.';
} 

if ($password != $passwordRetype) {
    // Add this error to our list
    $errors[] = 'Password does not match our records.';
}

// Repeat this process for other errors
// Then handle your list of errors
foreach ($errors as $error) {
    echo "Error Found: $error<br>";
}   

but only in ajax and php.

Currently I have this (a lot of code so skipping some parts):

 $.ajax({
     url: $form.attr('action'),
     data: formData,
     cache: false,
     contentType: false,
     processData: false,
     type: 'POST',
     success: function(data) {
         console.log(data);
         if (data.status == 'success') {
          console.log("success");
         } else if (data.status == 'not_image') {
          console.log("this is not an image");
         } else if (data.status == 'image_exists') {
          console.log("this image exists");
         }
     });
 });

This is the PHP

$errors_query = array();

            if (!empty($images)) {
                $uploadOk = 0;
                $errors++; 
                $errors_query["status"] = 'image_exists';


            }elseif(!in_array($file_type, $allowed)){
                $uploadOk = 0;
                $errors++; 
                $errors_query["status"] = 'not_image';

            }else{
                $uploadOk = 1;
                $errors_query["status"] = 'success';

            }
    if($errors > 0){
        echo json_encode($errors_query);
        exit();
    }else{
        echo json_encode($errors_query);
        exit();
    }

It works and shows only one response message, even if both data statuses "image_exists" and "not_image" are present. How can I show all the error messages for the user?

It is very simple

Just do like this

PHP Code

       $errors_query = array();


        if (!empty($images)) {

            $errors_query['msg'][] = 'Sorry Image not exists';
            $errors_query['status'] = FALSE;


        } elseif (!in_array($file_type, $allowed)) {

            $errors_query['msg'][] = 'not_image';
            $errors_query['msg'][] = 'msg2';
            $errors_query['msg'][] = 'msg3';
            $errors_query['status'] = FALSE;

        } else {

            $errors_query['msg'][] = 'success';
            $errors_query['status'] = TRUE;

        }


         echo json_encode($errors_query);

jQuery Code

 $.ajax({
             url: 'http://localhost/welcome/raja',
             cache: false,
             contentType: false,
             processData: false,
             type: 'GET',
             success: function(data) {
             var data = JSON.parse(data);
                 if (data.status === true) {

                  console.log("success");

                 } else {

                $.each(data.msg, function( index, value ) {
              console.log( index + ": " + value );
               });


                 }
             },
         });

It is working example i have already tested .Happy Work ............ :)

What I roughly understood (correct me if I'm wrong) is that

  1. Your PHP code creates an array for errors and loops through some if-else statements to check for errors for the uploaded file and add the errors to the array under the key "status"
  2. Encode into JSON and pass it to your AJAX code
  3. Your AJAX code will then return the error message based on the return JSON

I found some problems with your code:

  1. When you use if-else for your error checking in your PHP file, once the first error has been logged, the other errors will not be checked. This is because as the first if has been accessed, the subsequent if-else and else statements will be skipped. Hence, if the file is determined to exist, your code will not check if it's not an image.
  2. The AJAX has the same fundamental problem as point 1. Once one error has been printed, it will not print out the rest, hence your issue of only showing 1 error message.
  3. If you use the same key in the array, the older errors will be overwritten by the new ones.

To rectify, you can do the following:

  1. Add each error message as an individual element in an subarray of your original array, such as $errors_query[errors][]. This will allow you to use the other elements - like $errors_query[status] - to populate your status. Take a look at the array_push function on how to add an element to the end of an array. The plus of such method is you don't have to worry how many error messages you'll have - just keeping adding to the end of the array.
  2. Your AJAX code should then loop through the subarray that you have created in step 1 ("errors" here) and print them out accordingly.

Unfortunately I don't have a production software in the computer I'm using now, so I can't write a working code for you to copy, but hopefully this allows you to approach a direction.

Actually Your ajax jquery code has some problem,You included extra " ); " in the closing of success function part.

$.ajax({
     url: $form.attr('action'),
     data: formData,
     cache: false,
     contentType: false,
     processData: false,
     type: 'POST',
     success: function(data) {
         console.log(data);
         if (data.status == 'success') {
          console.log("success");
         } else if (data.status == 'not_image') {
          console.log("this is not an image");
         } else if (data.status == 'image_exists') {
          console.log("this image exists");
         }
     });
 });

If you check the result in the browser console,then you can see mentioned JavaScript error.

$.ajax({
             url: $form.attr('action'),
             data: formData,
             cache: false,
             contentType: false,
             processData: false,
             type: 'POST',
             dataType :"json",
             success: function(data) {
                 console.log(data.status);
                 var ajaxResult = data.status;
                 if (ajaxResult.indexOf("success") != -1) {
                  console.log("success");
                }
                if (ajaxResult.indexOf("not_image") != -1 ) {
                  console.log("this is not an image");
                }
                if (ajaxResult.indexOf("image_exists") != -1) {
                  console.log("this image exists");
                 }
             }
         });

PHP code is below.

<?php
header("Content-Type:text/json; charset=UTF-8");
$errors_query = array();
$flag1 =0 ;
$allowed = array("png","jpg","jpeg"); // Give the correct values based on your requirement
$images=""; // Assign the correct value based on your program
$file_type= ""; // Assign the correct value
$errors=0;

if (!empty($images)) {
    $uploadOk = 0;
    $errors++;
    $errors_query["status"][] = 'image_exists';
  $flag1 =1;
}

if (!in_array($file_type, $allowed)) {
    $uploadOk = 0;
    $errors++;
    $errors_query["status"][] = 'not_image';
  $flag1 =1;
}

if($flag1 == 0 ) {
    $uploadOk               = 1;
    $errors_query["status"][] = 'success';

}
if ($errors > 0) {
    echo json_encode($errors_query);
    exit();
} else {
    echo json_encode($errors_query);
    exit();
}
?>