2015-11-10 4 views
1

Я пытаюсь загрузить мода «спасибо» при отправке моей формы.Загрузить Modal при отправке формы

У меня есть 3 файла, magic.js (что делает магию JQ), index.html и process.php.

Ниже приведен код для каждого из трех файлов, и я не могу на всю жизнь заставить его работать.

Когда форма отправлена ​​он просто загружает process.php страницы и отображает успех = истина

если я удалить действие = «process.php» из тега формы я просто получить Method Not Allowed ошибку.

index.html:

<html> 
<head> 
    <title>Look I'm AJAXing!</title> 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> <!-- load jquery via CDN --> 
    <script src="magic.js"></script> <!-- load our javascript file --> 
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css"> <!-- load bootstrap via CDN --> 
</head> 
<body> 
<div class="col-sm-6 col-sm-offset-3"> 

    <h1>Processing an AJAX Form</h1> 

    <!-- OUR FORM --> 
    <form action="process.php" method="POST"> 

     <!-- NAME --> 
     <div id="name-group" class="form-group"> 
      <label for="name">Name</label> 
      <input type="text" class="form-control" name="name" placeholder="Henry Pym"> 
      <!-- errors will go here --> 
     </div> 

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

     <!-- SUPERHERO ALIAS --> 
     <div id="superhero-group" class="form-group"> 
      <label for="superheroAlias">Superhero Alias</label> 
      <input type="text" class="form-control" name="superheroAlias" placeholder="Ant Man"> 
      <!-- errors will go here --> 
     </div> 

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

    </form> 

</div> 
<!-- Modal --> 
    <div class="modal fade" id="myModal" role="dialog"> 
    <div class="modal-dialog"> 

     <!-- Modal content--> 
     <div class="modal-content"> 
     <div class="modal-header"> 
      <button type="button" class="close" data-dismiss="modal">&times;</button> 
      <h4 style="color:red;"><span class="glyphicon glyphicon-lock"></span> Login</h4> 
     </div> 
     <div class="modal-body tyModal"> 
      <p> Thank you for your submission!</p> 
     </div> 
     <div class="modal-footer"> 
      <button type="submit" class="btn btn-default btn-default pull-left" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button> 
      <p>Not a member? <a href="#">Sign Up</a></p> 
      <p>Forgot <a href="#">Password?</a></p> 
     </div> 
     </div> 
    </div> 
    </div> 
</body> 
</html> 

magic.js:

$(document).ready(function() { 

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

     $('.form-group').removeClass('has-error'); // remove the error class 
     $('.help-block').remove(); // remove the error text 

     // 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(), 
      'superheroAlias'  : $('input[name=superheroAlias]').val() 
     }; 

     // process the form 
     $.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 
      encode  : true 
      success: function (msg) { 
       $("#thanks").html(msg) 
       $("tyModal").modal('hide'); 
      }, 
      error: function() { 
       alert("failure"); 
      } 
     }) 
      // 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 
        } 

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

       } else { 

        // ALL GOOD! just show the success message! 
        $('form').append('<div class="alert alert-success">' + data.message + '</div>'); 

        // usually after form submission, you'll want to redirect 
        // window.location = '/thank-you'; // redirect a user to another page 

       } 
      }) 

      // using the fail promise callback 
      .fail(function(data) { 

       // show any errors 
       // best to remove for production 
       console.log(data); 
      }); 

     // stop the form from submitting the normal way and refreshing the page 
     event.preventDefault(); 
    }); 

}); 

process.php:

<?php 

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

// validate the variables ====================================================== 
    // if any of these variables don't exist, add an error to our $errors array 

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

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

    if (empty($_POST['superheroAlias'])) 
     $errors['superheroAlias'] = 'Superhero alias is required.'; 

// return a response =========================================================== 

    // 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); 

ответ

2

Вы никогда не создать модальное на форуме представить.

Вы только скрываете успех.

$("tyModal").modal('hide'); 

Вы также не создали модальность на странице, так как myModal является единственным, что существует. Не tyModal.

Другая проблема заключается в том, что #thanks не существует, поэтому вы технически заполняете данные ничем.

success: function(data) { 
    $("#thanks").html(data); 
    jQuery("#myModal").modal('show'); 
} 

Это код, который я использую.

HTML

<!-- data-backdrop="static" --> 
<div class="modal fade" id="myAjaxModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false"> 
    <div class="modal-dialog"> 
     <div class="modal-content" id="myAjaxModalContent"> 
     </div><!-- end modal-content --> 
    </div> 
    <!-- end modal-dialog --> 
</div> 
<!-- end modal --> 

JS

function showModal() { 
    $("#myAjaxModal .modal-content").html('test'); 
    $('#myAjaxModal').modal('show'); 
} 
+0

Я скорректировал «скрыть», чтобы показать и изменить имя на tyModal (мой плохо!), Но он все еще просто отображает страницу process.php при отправке – Luke

+0

Вы также изменили tyModal на myModal. Кроме того, успех ajax работает, вы всегда можете добавить debug, чтобы убедиться, что он работает. –

+0

Да, я переименовал myModal в tyModal на index.html. Когда он отправляет, он загружает process.php и отображает «{« success »: true,« message »:« Success! »}« Консоль Debug показывает «Uncaught SyntaxError: Неожиданный идентификатор» на строке magic.js 25, которая является этой строкой "success: function (data) {" – Luke

-1

Добавьте строку

event.preventDefault(); 

Только после представить события.

Это должно остановить обычный процесс отправки этого действия и позволить AJAX сделать это вместо этого. См. http://www.w3schools.com/jquery/event_preventdefault.asp

Существуют и другие аспекты вашего кода, которые можно было бы очистить, чтобы быть более гибкими для добавления полей формы в будущем.

var formData = { 'name' : $('input[name=name]').val(), 'email' : $('input[name=email]').val(), 'superheroAlias' : $('input[name=superheroAlias]').val() };

Вы могли бы сделать что-то вроде этого

var formData = {}; 
$.each($('form').find('input'),function(i,v){ 
     formData[$(v).attr('name')] = $(v).val(); 
}); 

или посмотреть на .serialize(); ->https://api.jquery.com/serialize/

Я также не уверен, будет ли ваш диалог зарегистрировать даже с моим данным кодом, как код в функции успеха не соответствует HTML, этот вопрос был идентифицирован @Darren Willows

Смежные вопросы