2016-04-25 4 views
0

Я работаю над формой входа в систему, используя AJAX и jQuery, однако форма не отправляет правильный путь: она будет обрабатывать.php вместо того, чтобы возвращать мне сообщение на index.php.AJAX Form не AJAX, отправляющий

index.html

<form id="login" action="process.php" method="POST"> 

    <div id="name-group" class="form-group"> 
     <label for="name">Name</label> 
     <input type="text" class="form-control" name="name" placeholder="JohnDoe"> 
    </div> 

    <div id="email-group" class="form-group"> 
     <label for="email">Email</label> 
     <input type="text" class="form-control" name="email" placeholder="[email protected]"> 
    </div> 

    <button type="submit" class="btn btn-success">Submit <span class="fa fa-arrow-right"></span></button> 

</form> 

Ничего плохого не найдено в форме. По крайней мере, я не мог найти там никаких ошибок.

index.html; это скрипт JS AJAX

$(document).ready(function() { 

    // process the form 
    $('#login').submit(function(event) { 

     // get the form data 
     // there are many ways to get this data using jQuery (you can use the class or id also) 
     var formData = { 
      'name'    : $('input[name=name]').val(), 
      'email'    : $('input[name=email]').val() 
     }; 

$.ajax({ 
    type  : 'POST', // define the type of HTTP verb we want to use (POST for our form) 
    url   : 'process.php', // the url where we want to POST 
    data  : formData, // our data object 
    dataType : 'json' // what type of data do we expect back from the server 
}) 
    // using the done promise callback 
    .done(function(data) { 

     // log data to the console so we can see 
     console.log(data); 

     // here we will handle errors and validation messages 
     if (! data.success) { 

      // handle errors for name --------------- 
      if (data.errors.name) { 
       $('#name-group').addClass('has-error'); // add the error class to show red input 
       $('#name-group').append('<div class="help-block">' + data.errors.name + '</div>'); // add the actual error message under our input 
      } 

      // handle errors for email --------------- 
      if (data.errors.email) { 
       $('#email-group').addClass('has-error'); // add the error class to show red input 
       $('#email-group').append('<div class="help-block">' + data.errors.email + '</div>'); // add the actual error message under our input 
      } 

     } else { 

      $('form').append('<div class="alert alert-success">' + data.message + '</div>'); 
      alert('success'); 

     } 

    }); 

}); 

process.php

<?php 
$errors   = array();  // array to hold validation errors 
$data   = array();  // array to pass back data 

    if (empty($_POST['name'])) 
     $errors['name'] = 'Name is required.'; 

    if (empty($_POST['email'])) 
     $errors['email'] = 'Email is required.'; 

    // if there are any errors in our errors array, return a success boolean of false 
    if (! empty($errors)) { 

     // if there are items in our errors array, return those errors 
     $data['success'] = false; 
     $data['errors'] = $errors; 
    } else { 

     // if there are no errors process our form, then return a message 

     // DO ALL YOUR FORM PROCESSING HERE 
     // THIS CAN BE WHATEVER YOU WANT TO DO (LOGIN, SAVE, UPDATE, WHATEVER) 

     // show a message of success and provide a true success variable 
     $data['success'] = true; 
     $data['message'] = 'Success!'; 
    } 

    // return all our data to an AJAX call 
    echo json_encode($data); 

Я почти потянув меня за волосы, пожалуйста, помогите мне, что происходит не так.

+0

Я предполагаю, что вы включая правильно все файлы JS в индексе. html, правильно? – Erick

+0

@Erick Да, правильно –

ответ

0

вы отправляете форму дважды один один, нажав на кнопку и один представить на функции AJAX - вам необходимо прекратить подачу по умолчанию, так что AJAX функции можно:

редактировать ваши JS включать следующее:

$('#login').submit(function(event) { 
    event.preventDefault(); 
//rest of code 
+0

Как-то не работает для меня, он по-прежнему ставит меня на process.php –

+0

@ J.Doe Проверьте свою консоль Javascript, убедитесь, что она не получает ошибку. – Barmar

+0

@Barmar Этот сценарий для меня непонятен, поэтому я взял более простой скрипт из interwebs, спасибо за вашу помощь –

0

Как вы используете Form Submit события, так что вы можете предотвратить это сформировать перенаправление на другую страницу,

return false 

в конце представить е соборование

как ....

$('#login').submit(function(event) { 
    // your code 
    return false; 
} 

и если до сих пор не работает, то вам, возможно, придется попробовать этот

$(document).on('submit','#login',function(event){ 
    // your code 
    return false; 
}); 
+0

@ Shah Khalid - typo on sumbit :)) – gavgrif

+0

Вторая форма понадобится только в том случае, если форма добавляется в документ динамически. – Barmar

+0

@Barmar извините за орфографию. – shah