简体   繁体   中英

Problem using jQuery-AJAX to submit form to PHP and display new content in div without refreshing

I am trying to use jQuery-AJAX to submit the data in my form to my controller (index.php) where it is processed by PHP and inserted via PDO into the database if valid. Once the code is inserted into the database, the div where the form previously existed should be replaced by the contents of another page (newpage.php). The original page should not be refreshed upon submitting of the form, only the div where the form previously existed should be refreshed. There is a particular problem with my code, although I can't seem to find where the issue is at:

Here is my jQuery:

<script type="text/javascript">

    function processForm() {
    var action= $('#action').val();
    var data = $('#data').val();
    var dataString = 'action=' + action + '&data=' + data;

$.ajax ({
    type: "POST",
    url: ".",
    data: dataString,
    success: function(){
            $('#content_main').load('newpage.php');
        }
    });
}
</script>

Here is my HTML: (As a side note, I noticed that when I take the "return false;" out of the HTML, that the form will submit to my database, but the whole page also reloads - and is blank. When I leave the "return false;" in the HTML, the newpage.php loads correctly into the div, but the data does not make it into the database)

<form action="" method="post" onsubmit="processForm();return false;">

    <input type="hidden" name="action" value="action1" />
    <input type="text" name="data" id="data" />

    <input type="submit" value="CONTINUE TO STEP 2" name="submit" />

</form>

Here is my PHP:

<?php
$action = $_POST['action'];

switch ($action) {
    case 'action1':
        $data = $_POST['data'];

        pdo ($data);

    exit;
}
?>

I feel like I am making a silly mistake somewhere, but I just can't put my finger on it. Thanks for any assistance you can provide!

SOLUTION (via Jen):

jQuery:

<script type="text/javascript">
    function processForm() {
        var dataString = $("#yourForm").serialize();

    $.ajax ({
    type: 'POST',
    url: ".",
    data: dataString,
    success: function(){
            $('#content_main').load('newpage.php');
          }
        });
    return false;
    });
</script>

HTML:

<form id="yourForm">

    <input type="hidden" name="action" value="action1" />
    <input type="text" id="data" name="data" />

    <input type="submit" value="CONTINUE TO STEP 2" name="submit" />

</form>

PHP:

<?php
    $action = $_POST['action'];

    switch ($action) {
        case 'action1':
            $data = $_POST['data'];

            pdo ($data);

        exit;
    }
?>

What I learned: Use the.serialize() jQuery method if it is an option, as it will save a bunch of time writing out the var for each form value and.serialize() does not typically make mistakes sending the info to php.

Seems like you need an explanation rather than a fix of code. Here is a brief explanation for the 2 cases:

  1. When you take out return false; the code will treat your form as a normal HTML form that will be submitted to the server via action="" , which leads to nowhere. The Javascript, however, also does its job in this case but because the page is redirected to nowhere, then it turns blank at the end.

  2. When you put return false ; back to the form, the form will catch the event handler and know that this form will be returned FALSE to submit. That's why you can see how your Javascript code does the job. However, one thing you should notice is that your jQuery AJAX function needs to POST (or GET ) to a processing file, not '.'

Considering this reply based on no knowledge of your real situation. You need to look back over your code and see how you can edit it. Would be happy to reply if you have any questions.

Hope this small hint helps (:

Give this a try:

 $("#yourForm").submit(function(){


  // Could use just this line and not vars below      
  //dataString = $("#yourForm").serialize(); 

  // vars are being set by selecting inputs by id but id not set in form fields
  var action= $('#action').val(); // value of id='action' 
  var data = $('#data').val();    // value of id='data'
  var dataString = 'action=' + action + '&data=' + data;
  // dataString = 'action=&data=' so nothing is posted to db
  // because input fields cannot be found by id
  // fix by adding id fields to form fields

   $.ajax ({
   type: "POST",
   url: ".",
   data: dataString,
   success: function(){
        $('#content_main').load('newpage.php');
    }
   });
return false; 
});

And change the form to (I added the id attributes):

<form id="yourForm">
<input type="hidden" id="action" name="action" value="action1" />
<input type="text" id="data" name="data" id="data" />

<input type="submit" value="CONTINUE TO STEP 2" name="submit" />

</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM