简体   繁体   中英

Submit and fetch data without refreshing the page

I'm new to php and mySQL. I've created a webpage, it's essentially a noticeboard. The page has a form to submit content and the content is shown below instantaneously. The content appears when the submit button is pressed, but now if I wanted to submit content immediately after the form still displays the echo that says submission was successful. Could someone point me in right direction to get the page functioning in a way that users can submit content one after the other without refreshing the page? Any help is greatly appreciated. Apologies for the messy code.

This is my input code:

        if(! $conn ) {
           die('Could not connect: ' . mysql_error());
        }

        if(! get_magic_quotes_gpc() ) {
           $name = addslashes ($_POST['name']);
           $proposal = addslashes ($_POST['proposal']);
        }else {
           $name = $_POST['name'];
           $proposal = $_POST['proposal'];
        }

       $email = $_POST['email'];

        $sql = "INSERT INTO db3". "(name, proposal, email, join_date ) 
            VALUES('$name','$proposal','$email', NOW())";

        mysql_select_db('_db');
        $retval = mysql_query( $sql, $conn );

        if(! $retval ) {
           die('Could not enter data: ' . mysql_error());
        }

       echo "<div class='msg-box' id='msg-box'>Entered data successfully</div>\n";

        mysql_close($conn);

This is my form:

<form name="submission" method = "post" action = "<?php $_PHP_SELF ?>" >

      <fieldset>
         <input name = "name" type = "text" 
                       id = "name" placeholder="Name..." required autocomplete="off">

         <input name = "email" type = "text" 
                       id = "email" placeholder="example@gmail.com..."  autocomplete="off">

         <textarea name = "proposal" type = "textarea" maxlength="1000" 
                       id = "proposal" placeholder="Your proposal goes here..." required autocomplete="off"></textarea>


      </fieldset> 

      <fieldset> 
         <input name = "add" type = "submit" id = "add" value = "Submit"> 
      </fieldset>

 </form>

This is my retrieval code:

  $conn = mysql_connect($dbhost, $dbuser, $dbpass);

  if(! $conn ) {
  die('Could not connect: ' . mysql_error());
  }

   $sql = 'SELECT id, name, proposal FROM db3 ORDER BY ID DESC ';

   mysql_select_db('_db');
   $retval = mysql_query( $sql, $conn );

   if(! $retval ) {
      die('Could not get data: ' . mysql_error());
   }

   while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
     echo 
      "<article>".
      " <div class='id'> ID :{$row['id']} </div>  ".

      " <section> <p> {$row['proposal']} </p></section> ".
        " <section class='name'><h3> {$row['name']} </h3></section> ".
       "</article>"
      ;   

    }


   mysql_close($conn);
   ?>

Use this code:

<script>
submitHandler: function(form) {
            $.ajax({
                url: '',
                type: 'POST',
                data: $("#submission").serialize(),
                success: function() {
                  alert('submitted data: '$("#submission").serialize());
            return false;

                }
            });
        }
    </script>

Please change the form line with this one:

<form name="submission" id="submission" method = "post" action = "<?php $_PHP_SELF ?>" >

You can do this using AJAX

You will use javascript to send the data to a PHP script which will process it. The same script will return the new data that was just submitted so you can display it on the page.

An example would be

HTML

<form id="comment">
  <input type="text" id="userInput" name="comment" placeholder="Tell us what you feel about this" />
  <input type="submit" value="Submit" />
</form>

jQuery

<script>

  $("#comment").on('submit', function(e) {

    // Stop the form from being submitted the standard way
    e.preventDefault();

    // Put the user's input into a variable
    var userInput = $('#userInput').val();

    // Do some validation of the data if needed
    // ...
    // ...



    // Perform AJAX request (a.k.a send the data to the server)
    $.ajax({

      // There are many parameters one can use here
      // Browse the documentation to get familiar with the most useful ones

      url: 'proccess.php',  // The PHP script that will handle the request
      type: 'POST',         // This can be set to GET, but in this case we'd use POST
      data: { comment: userInput }, // "comment" will result in $_POST['comment'], and userInput is the value of it

      // If the script returns a 200 status (meaning the request was successful)
      success: function(data) {

        // The data variable will be the response from the PHP script
        // Depending on what you are going to do with the data returned,
        // you may want to ensure it is returned as valid JSON

      },

      error: function() {

        // The request failed - So something here
        // ...
        // ...

      }

    });

  });

</script>

PHP (process.php)

<?php

  $data = $_POST['comment'];

  // Do all you would normally do when submitting a post
  // ...
  // ...

  // Now, upon successfully storing the data in your database,
  // you can return something to the 'data' variable in the AJAX.success function


?>

Do some research on AJAX and jQuery. It's really fun to work with

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