Home  >  Article  >  Database  >  How to Insert Data into MySQL with PHP and AJAX (jQuery)?

How to Insert Data into MySQL with PHP and AJAX (jQuery)?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-01 12:27:30941browse

How to Insert Data into MySQL with PHP and AJAX (jQuery)?

Inserting Data into MySQL with PHP and AJAX (jQuery)

Many tutorials focus on complex implementations of database interaction, making it challenging to adapt them for specific needs. This article provides a simplified approach to inserting data into a MySQL database using PHP and AJAX (jQuery).

The HTML form consists of a textbox, label, and submit button.

<code class="html"><form method="post" action="process.php" onSubmit="return ajaxSubmit(this);">
    Value: <input type="text" name="my_value" />
    <input type="submit" name="form_submit" value="Go" />
</form></code>

The jQuery script handles the AJAX submission without refreshing the page.

<code class="javascript">var ajaxSubmit = function(formEl) {
    var url = $(formEl).attr('action');
    var data = $(formEl).serializeArray();

    $.ajax({
        url: url,
        data: data,
        dataType: 'json',
        success: function(rsp) {
            if(rsp.success) {
                alert('form has been posted successfully');
            }
        }
    });

    return false;
}</code>

The PHP script, process.php, connects to the database and executes the insert query. It escapes the user input to prevent SQL injections.

<code class="php">$val = mysql_real_escape_string(post('my_value'));
$sql = sprintf("INSERT INTO %s (column_name_goes_here) VALUES '%s';", 'table_name_goes_here', $val);
$result = mysql_query($sql);</code>

The result of the query (success or error) is returned in JSON format. Upon successful insertion, an alert message is displayed on the page.

This simplified approach provides a concise and straightforward way to insert data into a MySQL database using PHP and AJAX (jQuery).

The above is the detailed content of How to Insert Data into MySQL with PHP and AJAX (jQuery)?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn