Home C C++ Java Python Perl PHP SQL JavaScript Linux Online Test Forum

Home » Send Popup value to Database using Ajax

Send Popup value to Database using Ajax

This program has two files html & php. html files contains Ajax script which actually calls 'save' function of feedback.php. User can modify this code according to their database names & table

HTML code with button to show Popup


<!-- Save this file as somethign.html -->
<html>
<head>
<script>
function feedback(){
var msg = prompt("Your feedback", "");

if(msg .length > 0){

jQuery.ajax({
    type: "POST",
    url: 'feedback.php',
    dataType: 'json',
    data: {functionname: 'save', arguments: [msg,'0']},

    success: function (obj, textstatus) {
                  if( !('error' in obj) ) {
                      yourVariable = obj.result;
                      //alert(yourVariable);
                      alert('Thank you!! Your feedback is valuable to us')
                  }
                  else {
                      console.log(obj.error);
                      alert('error');
                  }
            }
});
}
}
</script>
</head>

<body>

<div class="float-lower-left1">
<button id="btnFeedback" class="float-lower-left" onclick="feedback()">
f<br>
e<br>
e<br>
d<br>
b<br>
a<br>
c<br>
k<br>
</button>
</div>
</body>
</html>

PHP code which is called when you submit PopUp

Please save below code inside and save as feedback.php


//save this code in feedback.php
header('Content-Type: application/json');
$aResult = array();
function saveFeedback($msg){
//connecting to database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydb";

// Create connectiono
$Kconn = new mysqli($servername, $username, $password, $dbname);

$sql = "insert into feedback(Message) values ('$msg')";

if ($Kconn->query($sql) === TRUE) 
{
return 'Thank you!! Your feedback helps us in improving this website';
} 
else 
{
return 'Thank you!! Error in Saving data. Contact Admin';
}
$Kconn->close();
}

    if( !isset($_POST['functionname']) ) { $aResult['error'] = 'No function name!'; }
    if( !isset($_POST['arguments']) ) { $aResult['error'] = 'No function arguments!'; }
    
    if( !isset($aResult['error']) ) {
    switch($_POST['functionname']) {
    case 'save':
       if( !is_array($_POST['arguments']) || (count($_POST['arguments']) < 2) ) {
           $aResult['error'] = 'Error in arguments!';
       }
       else {
           $aResult['result'] = saveFeedback($_POST['arguments'][0]); /*add(floatval($_POST['arguments'][0]), floatval($_POST['arguments'][1]));*/
       }
       break;

    default:
       $aResult['error'] = 'Not found function '.$_POST['functionname'].'!';
       break;
        }
    }
    echo json_encode($aResult);