0

I want to use ajax in order to fadeIn a loader during PHP validation and returning the values from it to show visual effect messages, then fadeOut the loader when it finishes. But I did not managed to get a simple return from PHP validation in the .done function.

Can anyone help me please?

Index

<form action="php/valid.php" method="post" id="contact-form">
    <input id="name-contact" class="uk-input uk-width-1-1 uk-margin-small" type="text" name="name" placeholder="Name"><br>
    <input id="email-contact" class="uk-input uk-width-1-1 uk-margin-small" type="text" name="email" placeholder="Email"><br>
    <textarea id="message-contact" class="uk-input uk-textarea uk-width-1-1 uk-margin-small" name="message" placeholder="Message" style="height:200px"></textarea>
    <button id="contact-btn" class="uk-margin-small uk-button uk-button-secondary uk-width-1-1" type="submit" name="contact-form">Send</button>
</form>

JS

$(function() {
    var     data = {
        name: $('#name-contact').val(),
        email: $('#email-contact').val(),
        message: $('#message-contact').val()
    };
    $('#contact-form').on('submit', function(event) {
        $.ajax({
            url: 'php/valid.php',
            type: 'POST',
            dataType: 'json',
            data: data
        })
        .done(function(data) {
            if (data.status == 'success') {
                    console.log('Success !');
            } else if (data.status == 'error') {
                    console.log('Error !');
            }
        })
        .fail(function(error) {
            console.log(error);
        });
    });
});

PHP file

<?
    header('Content-Type: application/json');
    $error = false;
    $regex_name = '#^[\w\s\p{L}-]{2,30}$#iu';
    $regex_message = '#^[\s\S]{3,800}$#i';
    if (isset($_POST['contact-form'])) {
        $name = $_POST['name'];
        $from = $_POST['email'];
        $message = nl2br($_POST['message']);
        if (!empty($name) && !empty($from) && !empty($message)) {
               if (preg_match($regex_name, $name) && filter_var($from, FILTER_VALIDATE_EMAIL) && preg_match($regex_message, $message)) {
                    $error = array('type' => 'success');
               } else {
                    $error = array('type' => 'error', 'value' => 'There are some errors, please check your informations.');
               }
        } else {
            $error = array('type' => 'error', 'value' => 'Some fields are empty, please check your informations.');
        }
    }
    if (isset($error['type']) && $error['type'] == 'success') {
        $return_status['status'] = 'success';
        echo json_encode($return_status);
    }
    else {
        if (isset($error['type']) && $error['type'] == 'error') {
            $return_status['status'] = 'error';
            echo json_encode($return_status);
        }
     }
?>

Thank you.

9
  • So what happens when you run your code? Checked the console for errors? Done a console.log(data); in the top of your done() callback? Also, you should add a event.preventDefault() right before you do your ajax request (in the callback for your click event) or it will simply do a regular post to the page and your ajax code would never run. Commented Sep 20, 2018 at 21:13
  • 1
    Btw, the data variable will be set on page load. You should probably move that inside the click event or all values will always be empty. Commented Sep 20, 2018 at 21:15
  • @MagnusEriksson l change code as the first answer but still have an object error : Object { readyState: 4, getResponseHeader: ...... Commented Sep 21, 2018 at 6:53
  • readyState: 4 only means that the request is done and doesn't tell us anything else. If you get that in your fail()-callback, then open up the browsers developer tools and go to the "Network"-tab. Make a request and check what the request looks like and what the server returns (the response). Commented Sep 21, 2018 at 7:06
  • I would also recommend using a relative url from the root folder. You do that by starting the url with a slash: url: '/php/valid.php', if the folder php is in your web root. If it's not, just add the complete path from the web root: url: '/path/to/php/valid.php', Commented Sep 21, 2018 at 7:08

2 Answers 2

1

First, you need to call event.preventDefault() to prevent the form from being submitted normally.

Second, you need to get the values of the inputs in the event handler. Your code is setting data when the page is loaded, before the user has filled in the form.

Third, your PHP script checks for the contact-form parameter. This is sent when you submit the form normally, but your AJAX request isn't setting it. You need to add it to data, or remove if (isset($_POST['contact-form'])) from the PHP (if valid.php is never used for anything else, this check is probably not necessary).

$(function() {
  $('#contact-form').on('submit', function(event) {
    event.preventDefault();
    var data = {
      name: $('#name-contact').val(),
      email: $('#email-contact').val(),
      message: $('#message-contact').val(),
      "contact-form": true
    };
    $.ajax({
        url: 'php/valid.php',
        type: 'POST',
        dataType: 'json',
        data: data
      })
      .done(function(data) {
        if (data.status == 'success') {
          console.log('Success !');
        } else if (data.status == 'error') {
          console.log('Error !');
        }
      })
      .fail(function(error) {
        console.log(error);
      });
  });
});

Sign up to request clarification or add additional context in comments.

17 Comments

Thanks for your reply! I still have the same object error : Object { readyState: 4, getResponseHeader: ..... And nothing happens, even not console.log(data). Do you have an idea?
Check the AJAX response in the Network tab, make sure there's nothing extra around the JSON.
Returning SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
All those nested if statements in the PHP are very confusing. Maybe there's a path through them that never echoes any JSON.
What do you see in the Response section of the Network tab?
|
0

Change button type to button:

<button id="contact-btn" class="" type="button" name="contact-form">Send</button>

Change your js code like below :

$(document).ready(function () {
    $('#contact-btn').click(function(event) {
        var data = {
            name: $('#name-contact').val(),
            email: $('#email-contact').val(),
            message: $('#message-contact').val()
        };
        $.ajax({
            url: 'php/valid.php',
            type: 'POST',
            dataType: 'json',
            data: data,
            success: function(response) {
                if (response.status == 'success') {
                        console.log('Success !');
                } else if (response.status == 'error') {
                        console.log('Error !');
                } else
                    console.log("Somthing went wrong....")
            },
            error:function(){
                console.log("error");
              }
        });
    });
});

1 Comment

Thanks for your reply! I still have the same object error : Object { readyState: 4, getResponseHeader: ..... And nothing happens, even not console.log(data). Do you have an idea?

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.