Ajax call is never success

Iam facnigg and issue with ajax, Im working on a contact form and I have an issue with the ajax call, The call is never succseed, even if the field are all typed correctly. I tried few things but nothing is working Somene can give me an advice..?

Many thanks.

$.ajax({
  url: "assets/contact_form/process-contact.php",
  type: "POST",
  dataType: "html",
  data: userData,

  beforeSend: function () {
    $( sb ).html('Sending...');
  },
  success: function (response) {

    if (response == true) {

      setTimeout(function () {

        window.location = 'index.html';

      }, 1000);

    } else {

      $( sb ).html('Can not send, please try latter'); //IT GOES STRIGHT TO HERE

    }
  }
});

 }

});

here is the php code:

<?php

  $userData['name'] = filter_var(trim($_POST['name']), 
    FILTER_SANITIZE_STRING);
     $userData['email'] = filter_var(trim($_POST['email']), 
   FILTER_VALIDATE_EMAIL);
      $userData['phone'] = filter_var(trim($_POST['phone']), 
  FILTER_SANITIZE_STRING);
 $userData['message'] = filter_var(trim($_POST['message']), 
 FILTER_SANITIZE_STRING);

 if( ! in_array( null, $userData ) ){

$my_email = '[email protected]';


$nameRegx = "/^[' a-z?-?]+(\s[' a-z?-?]+)*$/i";
 $phoneRegx = "/^(?:0(?!(5|7))(?:2|3|4|8|9))(?:-?\d){7}$|^(0(?=5|7)(?:-?\d)
{9})$/";

  if( strlen($userData['name']) > 2 &&  strlen($userData['name']) < 70 && 
 preg_match($nameRegx, $userData['name']) ) {

   if( preg_match($phoneRegx, $userData['phone']) ){

  if( strlen($userData['message']) > 2 ){

      $subject = 'Message from ' . $userData['name'] ;
       $message_phone= $userData['message'].'Phone number: 
    '.$userData['phone'];
      $headers = 'From: ' . $userData['email']. "\r\n";

      mail($my_email, $subject, $message_phone,  $headers);
    // send mail
    // Save data to db (DON'T FORGET TO CLEAN AGAINST SQL INJECTIONS!!!)
    echo true;

          }}}}

Answers:

Answer

This may work.

......
if (response) {

  setTimeout(function () {

    window.location = 'index.html';
.....
Answer

It will be better if you could return an object instead :

echo json_encode(['success' => true]);

Then the check in your success callback will looks like :

if (response.success){
   //Your logic
}

Hope this helps.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.