user2376259
user2376259

Reputation: 9

Having an Ajax Save button and save in database

I'm currently doing a form whereby customers will have to do the survey form, I'll have a AJAX "Save" button to allow me to save the data into database when the customers did not managed to finish the form itself and then when the customers login again, the form which they did halfway will pop out again and ask them to continue finish the survey form.

Is it possible where AJAX/javascript/jQuery can work with php codes in it (because of the insert query)?

Not very sure with AJAX and all so Thanks for helping!

This is for the "Save" button.

<input type="button" onClick="save();" value="Save">

This is the insert query whereby it will be inserted in database.

    <?php
        include("dbFunctions.php");


        $idQuery = "SELECT id,question,input FROM db_ExtApp1.scFormLayout WHERE surveyID ='$lastID'";
$idResult = sqlsrv_query($conn, $idQuery);

while ($row = sqlsrv_fetch_array($idResult)) {
    $fcID = $row['id'];
    $question = $row['question'];
    $surveyTitle = $_SESSION['surveyTitle'];
    $input = $row['input'];

    if (isset($_POST['qns' . $fcID])) {
    $answer = implode(",", $_POST['qns' . $fcID]);
    $newAns = str_replace($singleQuote,$changeQuote,$answer);
    } else {
        $newAns = '';
    }
    if (isset($_POST['others'.$fcID])) {
    $others = $_POST['others' . $fcID];
    $newOthers = str_replace($singleQuote,$changeQuote,$others);
    }else {
        $newOthers = 'N.A.';
    }

$connectionInfo['ConnectionPooling']=0; // this creates a new connection on the next line...
$newconn = sqlsrv_connect($serverName, $connectionInfo); 
if ($input != 'Normal text line, no input required*') {
    $query = "INSERT INTO db_ExtApp1.scFormResult(surveyID, answer, others, title, question, name)
VALUES ('$lastID','$newAns','$newOthers', '$surveyTitle','$question', '$name')";

    $status = sqlsrv_query($newconn, $query);
} }
    if ($status === false) {
        die(print_r(sqlsrv_errors(), true));
    } 
sqlsrv_close($conn);

Upvotes: 0

Views: 2994

Answers (1)

sravis
sravis

Reputation: 3680

You can use jquery $.ajax() to send data from client side to PHP. (eg)

$.ajax({
url : 'path/to/php/page',
data : { id : '1', name : 'name' },
dataType : 'JSON',
type : 'POST',
cache: false,
success : function(succ) {
alert(succ);
},
error : function(err) {
alert(err);
}
});

Then in PHP page, use $_POST[] to capture data and insert it into database.

$id = $_POST['id'];
$name = $_POST['name'];

Make sure you escape the values and make it safe for sql insert.

Upvotes: 1

Related Questions