Array does not act as expected in jQuery

I am doing jQuery Ajax with PHP, and after jQuery passes some $ _POST data to PHP, PHP validates that data and prepares an array with all errors, and as soon as the whole check is done, the number of errors is counted, and if it is greater than 0, the array encoded in json and printed to screen. JQuery then grabs that data with "success:" and it does it, but it doesn't act as expected.

PHP file check:

<?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;
    });
});

      

Everything works fine, but my output is in char 'format, like one character at a time. Click here to take a photo.

+3


source to share


2 answers


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 javascript knows how to handle the response



EDIT

the problem is that the json response is an object and not an array which has no property .length

.

you'd better do it like this:

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

      

-1


source


This is because your answer is a string and you are repeating 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 entire string, not the number of distinct objects in the returned JSON.


The easiest way to fix this is to parse the JSON in your callback:

var messageObject = JSON.parse(messages);

      

and now the variable messageObject

will have data in the expected format.

+2


source







All Articles