Hai,
I am new to this concept.

After clicking the button it has to insert into database and has to refresh the div in jquery ajax.

How to do?

Recommended Answers

All 2 Replies

It's impossible to give you a specific answer without seeing your code. But there are two basic methods. The first is to simply call "location.reload(true)" in JavaScript after your AJAX update. This will cause the page to reload, which isn't very elegant. But if you only want a specific DIV to be redrawn, you'll need to create a specific function in your JavaScript to do it. This may well require rewriting the original code by extracting the section that draws the DIV and making it a separate function.

You use one of jquery ajax methods, i.e. $.ajax(). HTTP method should be POST since you are updating data (see some in-deepth explanation here and some simpler explanation here). You supply the data to be inserted in JSON format.

The $.ajax method is usually called with a click event (e.g. user clicks on a button) and can be coded something like:

$.ajax({
    method: "POST",
    url: "insertscript.php",
    data: { field1: "Value 1", field2: "Value 2" }
})
    .done(function(msg) {
         alert("Data Saved: " + msg);
    });

The url points to the script that will actually do an insert. The data object contains the data for the fields that have to be updated. You will read it from the $_POST global variable in the script that updates the database (it is very important that you sanitize/escape this data before sticking it into the database). The done function will get called once ajax call is finished with success. Instead off alert you can stick some HTML into a div that is meant to display messages or something similar.

The insertscript.php PHP script could be someting like:

<?php
$field1 = some_escape_function($_POST['field1']);
$field2 = some_escape_function($_POST['field2']);
// connect to the database

...
// insert into database
$query = "INSERT INTO mytable (field1, field1) VALUES (' $field1', ' $field2')";
$success = myDatabaseFunctionFor Inserting($query);

// return appropriate message depending on success
// (this message will be caught by $.ajax function in the msg variable above)
if($success) {
    echo "Inserted successfully :-)";
} else {
    echo "Error inserting!";
}

This is just an example using some made up code. You should study links above and AJAX in general. If you google for 'jquery ajax example' you will find many interesting examples like this one. And try with your own code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.