Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add records to mysql database with php form without leaving/refreshing the page

I use this file input.php to add record to database:

$order = "INSERT INTO wp_userdata
            (username, product_name, product_brand)
            VALUES
            ('$_POST[username]',
                        '$_POST[name]',
            '$_POST[brand]')";


$result = mysql_query($order);  
if($result){
    header( 'Location: http://page-with-form.php' ) ;
} else{
    echo("<br>Input data is fail");
}

And my page with form page-with-form.php:

<table border="1">
  <tr>
    <td align="center">Add Products</td>
  </tr>
  <tr>
    <td>
      <table>
        <form method="post" action="input.php">
<input type="hidden" name="username" value="[insert_php]echo $username;[/insert_php]">
        <tr>
          <td>Product Name</td>
          <td><input type="text" name="name" size="50">
          </td>
        </tr>
        <tr>
          <td>Brand</td>
          <td><input type="text" name="brand" size="50">
          </td>
        </tr>
        <tr>
          <td></td>
          <td align="right"><input type="submit" name="submit" value="Send"></td>
        </tr>
</form>
        </table>
      </td>
    </tr>
</table>

Everything works fine: When I click "Send" button, input.php adds record and redirects back to page-with-form.php. You can't even see input.php loading, however you do see the page-with-form.php getting refreshed.

Is there a way to make all the operation without refreshing the page-with-form.php? I think it has to do with Ajax, but maybe there is another way? looking forward for your suggestions!

like image 387
Acidon Avatar asked Feb 13 '23 07:02

Acidon


1 Answers

You want to use AJAX to submit your form,

You can use JQuery to aid in this, the first thing you need to do is make sure your form does not refresh the page, and give your button an ID, this makes it easier to find the button through JQuery

first lets remove that line from your PHP code that causes a server side redirect, and instead have it produce a string stating that the data was saved succesfully, whatever this script prints in the HTTP response will be used by the ajax portion of this project

$order = "INSERT INTO wp_userdata
            (username, product_name, product_brand)
            VALUES
            ('$_POST[username]',
                        '$_POST[name]',
            '$_POST[brand]')";


$result = mysql_query($order);  
if($result){
    echo ("DATA SAVED SUCCESSFULLY");
} else{
    echo("Input data is fail");
}

Then lets modify the HTML to make it easier for Jquery to find the elements we need and output a status (this is not the only way, if you have multiple forms this is not recommended, Jquery has more sophisticated ways of finding form elements http://api.jquery.com/input-selector/ )

I just want to simply illustrate the idea rather then getting too much into Jquery details.

<table border="1">
      <tr>
        <td align="center">Add Products</td>
      </tr>
      <tr>
        <td>
          <table>
            <!-- THIS TELLS THE FORM TO NOT REFRESH THE PAGE -->
            <form onsubmit="return false">
    <input type="hidden" name="username" id="hdn_username" value="[insert_php]echo $username;[/insert_php]">
            <tr>
              <td>Product Name</td>
              <td><input type="text" id="txt_name" name="name" size="50">
              </td>
            </tr>
            <tr>
              <td>Brand</td>
              <td><input type="text" id="txt_brand" name="brand" size="50">
              </td>
            </tr>
            <!-- THIS ROW WILL DISPLAY THE RESULT OF THE LAST ENTRY -->`
            <tr>
                <td></td>
                <td><div id="status_text" /></td>
            </tr>
            <tr>
              <td></td>
              <td align="right">
                <!-- I GAVE THE BUTTON AN ID THAT WILL MAKE IT EASIER TO FIND WITH JQUERY -->
                <input type="submit" id="btn_submit" name="submit" value="Send"></td>
            </tr>
    </form>
            </table>
          </td>
        </tr>
    </table>

now for the Javascript version that will implement AJAX using the help of Jquery

What the Javascript will do is, when you click the button, it will post to your input.php and input PHP will return a result text.

//on the click of the submit button 
$("#btn_submit").click(function(){
 //get the form values
 var username = $('#hdn_username').val();     
 var name = $('#txt_name').val();     
 var brand = $('#txt_brand').val(); 

 //make the postdata
 var postData = 'username='+username+'&name='+name+'&brand='+brand;

 //call your input.php script in the background, when it returns it will call the success function if the request was successful or the error one if there was an issue (like a 404, 500 or any other error status)

 $.ajax({
    url : "input.php",
    type: "POST",
    data : postData,
    success: function(data,status, xhr)
    {
        //if success then just output the text to the status div then clear the form inputs to prepare for new data
        $("#status_text").html(data);
        $('#name').val('');
        $('#brand').val('');
    },
    error: function (jqXHR, status, errorThrown)
    {
        //if fail show error and server status
        $("#status_text").html('there was an error ' + errorThrown + ' with status ' + textStatus);
    }
});

What should happen is, you enter data into your form and you will see a status appear of it being successful or an error, if successful the form will clear for you to add more input.

like image 88
Oluwakayode Dagbo Avatar answered Feb 15 '23 10:02

Oluwakayode Dagbo