简体   繁体   中英

Array not acting as expected in jQuery

I'm doing jQuery Ajax with PHP, and after jQuery passes some $_POST data to PHP, PHP validates those data, and prepares an array with all the errors, and once all validation is done, the count of error is found, and if it is greater than 0, the array is encoded in json and it is printed on the screen. jQuery then grabs those data with 'success:' and it does it, but it doesn't act as expected.

PHP file validating:

<?php
$messages = array();

if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['subject']) && isset($_POST['message'])) {
    if(empty($_POST['name'])) {
        $messages[] = "Please fill in the Name field.";
    }
    if(empty($_POST['email'])) {
        $messages[] = "Please fill in the Email field.";
    }
    if(empty($_POST['subject'])) {
        $messages[] = "Please fill in the Subject field.";
    }
    if(empty($POST['message'])) {
        $messages[] = "Please write your message in the Message field!";
    }

    if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        $messages[] = "Invalid email entered!";
    }

    if(strlen($_POST['name']) > 30 || strlen($_POST['name']) < 3) {
        $messages[] = "Your name cannot be less than 3 characters or more than 30 characters.";
    }
    if(strlen($_POST['email']) > 30 || strlen($_POST['email']) < 3) {
        $messages[] = "Your email cannot be less than 3 characters or more than 30 characters.";
    }
    if(strlen($_POST['subject']) > 30 || strlen($_POST['subject']) < 3) {
        $messages[] = "The subject cannot be less than 3 characters or more than 30 characters.";
    }
    if(strlen($_POST['message']) > 2000 || strlen($_POST['message']) < 40) {
        $messages[] = "Your message cannot be less than 40 characters or more than 2000 characters.";
    }

    if(count($messages) > 0) {
        $messages['elements'] = count($messages);
        echo json_encode($messages);
    } else {

    }
}

jQuery code:

$(document).ready( function() {
    $(document).on('click', '.contact_submit', function() {
        var name = $('input#name').val();
        var email = $('input#email').val();
        var subject = $('input#subject').val();
        var message = $('input#message').val();

        var Data = "name=" + name + "&email=" + email + "&subject=" + subject + "&message=" + message;

        $.ajax({
            type: "POST",
            url: "portal/_inc/frontend/form.php",
            data: Data,
            success: function(messages) {

                var Count = messages.length;
                $('.messages').empty();
                for(var i = 0; i < Count; i++) {
                    $('.messages').append('<li class"error">' + messages[i] + '</li>\n');
                }
            }
        });
        return false;
    });
});

All works fine, but my output is in 'char' format like one character at a time. Click here for a screen shot.

It's because your response is a string, and you're iterating over a string.

This PHP code:

echo json_encode($messages);

encodes an object/array into a JSON string.

And this JS code:

var Count = messages.length;

will just return the length of the whole string, not the number of individual objects within the returned JSON.


The simplest way to fix it is to parse the JSON in your success callback:

var messageObject = JSON.parse(messages);

and now the variable messageObject will have the data in the format you expected.

Add dataType:'JSON' to your ajax request:

 $.ajax({
        dataType:'JSON',
        type: "POST",
        url: "portal/_inc/frontend/form.php",
        data: Data,
        .....

and add

 header('Content-type: application/json; charset=utf-8');

to your php so that the javascript knows how to handle the response

EDIT

the problem is that the json response is an object, not array, which does not have a .length property.

you'd be better to do it like this:

success: function(messages) {
      $('.messages').empty();
      $.each(messages,function(){
           $('.messages').append('<li class"error">' + this + '</li>\n');
               });
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM