2015-08-16 3 views
0

В настоящее время я сталкиваюсь с проблемой при вызове ajax при попытке отправить форму в базу данных.Невозможно запустить ajax-вызов в готовом документе jQuery

Вот мой код:

<?php 
    include 'dbConnect.php'; 
    include 'session.php'; 
?> 
<form class="form" id="form" action="" method="POST"> 
    <table class = "left"> 
     <tr align="justify"> 
      <td></td> 
     </tr> 
     <tr> 
      <td> 
       <p align="right"> 
        <font size = "4">New Subject Name : <input type = "text" name = "subjectName" id = "subjectName"/> 
        </font> 
       </p> 
      </td> 
     </tr> 
     <tr> 
      <td> 
       <p align="center"> 
        <input type = 'image' name = 'submit' src="images/Submit.gif" value = 'Submit' width='100' height='35'/> 
        </p> 
      </td> 
     </tr> 
    </table> 
</form> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
    </script> 
<script> 

     $(document).ready(function() { 
        // Bind to the submit event of our form 
     $("form#form").submit(function(event){ 

       // Abort any pending request 
       if (request) { 
        request.abort(); 
       } 
       // setup some local variables 
       var $form = $(this); 

       // Let's select and cache all the fields 
       var $inputs = $form.find("input, select, button, textarea"); 

       // Serialize the data in the form 
       var serializedData = $form.serialize(); 

       // Let's disable the inputs for the duration of the Ajax request. 
       // Note: we disable elements AFTER the form data has been serialized. 
       // Disabled form elements will not be serialized. 
       $inputs.prop("disabled", true); 

       // Fire off the request to /form.php 
       request = $.ajax({ 
        url: "subjectItem.php", 
        type: "post", 
        data: serializedData 
       }); 

       // Callback handler that will be called on success 
       request.done(function (response, textStatus, jqXHR){ 
        // Log a message to the console 
        console.log("Hooray, it worked!"); 
       }); 

       // Callback handler that will be called on failure 
       request.fail(function (jqXHR, textStatus, errorThrown){ 
        // Log the error to the console 
        console.error(
         "The following error occurred: "+ 
         textStatus, errorThrown 
        ); 
       }); 

       // Callback handler that will be called regardless 
       // if the request failed or succeeded 
       request.always(function() { 
        // Reenable the inputs 
        $inputs.prop("disabled", false); 
       }); 

       // Prevent default posting of form 
       event.preventDefault(); 
      }); 
     }); 
</script> 

Я не знаю, почему он не делаешь вставить данные в базу данных после того, как пользователь нажмите кнопку отправки. Пожалуйста, укажите мою ошибку, если я сделал что-то неправильно в коде. Благодаря

+0

Проверьте консоль на наличие ошибок. Вы видите результат строк 'console.log'? Выполняется ли ваш PHP? –

+0

На моем console.log нет ошибки. –

+1

У меня возникла бы соблазн разместить эту строку 'event.preventDefault();' непосредственно после этой строки '$ (" form # form "). Submit (function (event) {' Just в случае, если форма выполняет стандартную отправку HTML, а также ваш jQuery ajax call. – RiggsFolly

ответ

0
<script> 
     // setup a global var for all ajax requests 
     $.xhrPool = []; 

     // abort all ajax requests 
     $.xhrPool.abortAll = function() { 
       $(this).each(function(idx, jqXHR) { 
         jqXHR.abort(); 
       }); 
       $.xhrPool.length = 0 
     }; 

     // setup ajax 
     $.ajaxSetup({ 
       beforeSend: function(jqXHR) { 
         $.xhrPool.push(jqXHR); 
       }, 
       complete: function(jqXHR) { 
         var index = $.xhrPool.indexOf(jqXHR); 
         if (index > -1) { 
           $.xhrPool.splice(index, 1); 
         } 
       } 
     }); 

     // make request 
     function sendForm(){ 
       $.xhrPool.abortAll(); 

       // register all inputs 
       var $inputs = $form.find("input, select, button, textarea"); 

       // set up form data 
       var formData = new FormData($('.form')[0]); 

       // set up post url 
       var formUrl = ""; 

       // disable inputs 
       $inputs.prop("disabled", true); 

       //make ajax request 
       $.ajax({ 
         url: formUrl, 
         type: 'POST', 
         data: formData, 
         mimeType: "multipart/form-data", 
         contentType: false, 
         cache: false, 
         processData: false, 
         success: function(data, textStatus, jqXHR){ 
           // handle success 
           console.log("Hooray, it worked!"); 

           // Reenable the inputs 
           $inputs.prop("disabled", false); 
         }, 
         error: function(jqXHR, textStatus, errorThrown){ 
           // handle error 
           console.error("The following error occurred: "+textStatus, errorThrown); 

           // Reenable the inputs 
           $inputs.prop("disabled", false); 
         } 
       }); 
     } 
</script> 

Заменить кнопку отправки с <button type="button" onclick="sendForm();">Submit Form</button></p>

Я надеюсь, что это помогает, не забудьте заполнить formUrl Var