How to have user submit text in form and AJAX it to enter to db and show up on same page?

前端 未结 3 1332
面向向阳花
面向向阳花 2021-01-27 05:58

I want the user to fill it out. Submit it, have it store into the database and then use jquery to have it show up on the same page in front of them. Right now I can get it to se

3条回答
  •  醉酒成梦
    2021-01-27 06:06

    Here is another way, if you use the serialize function built into jquery along with the $.post you won't have to actually write much code.

    html form and html displaying the messages:

    • Some old message
    • Some other old message

    jquery to send the new messages to your server from the client and placing new message into the DOM and resetting the html form

    //bind a click even to the submit
    $('.commentForm input[type=submit]').click(function(){
          $(this).closest('form').find('input[type=submit]').value('Submitting');
          $.post(
           $(this).closest('form').attr('action'),
           $(this).closest('form').serialize(),
           function(responseFromServer){
              //get the message from the html form (don't need to send it back from the server)
              var message = $(this).closest('form').find('textarea');
              $('.messages').append('
  • '+message+'
  • '); //resetting the html form $(this).closest('form').find('textarea').html(''); $(this).closest('form').find('input[type=submit]').value('Submit'); } ); //prevent the form from actually sending in the standard fashion by returning false return false; });

    php

    //get the post variable and make it safe for inputting into the db
    $message = mysql_real_escape_string(html_entities($_POST['story']));
    if(!empty($message)){
       //assuming you have a db connection
       $insert_query = mysql_query("INSERT INTO textwalltable VALUES($message)");
       echo 'message entered';
    } else {
       echo 'no message';
    }
    

提交回复
热议问题