Using JQuery AJAX and php to fetch data to a mysql database - php

Im trying to insert data into my database with AJAX but dont working.
I can verify that im connected to the database but when i click it doesnt insert the data. thanks
with a click function i take the 2 parameter that i wanna insert in my database.
$( "#q_answer1" ).click(function () {
var q_no = $("#q_no").val();
var main_no = $("#total_no").val();
$.ajax({
url: "server.php",
type: "post",
async: false,
data: {
"done": 1,
"username": q_no,
"comment": main_no
},
success: function(){
$("#q_no").val('');
$("#total_no").val('');
}
});
});
And here is the php file, first connect to the ddbb and insert the 2 values with the mysql_query.
<?php
include("dbh.php");
if (isset($_POST['done'])) {
$q_no = mysql_escape_string($_POST['username']);
$total_no = mysql_escape_string($_POST['comment']);
mysql_query("INSERT INTO variables(id, names) VALUES('{$q_no}', '{$total_no}')");
exit();
}
?>
html is like this:
<div id="total_no">1</div>
<div id="q_answer1" class="btn left_b">yes</div>

I think you should use PDO, to connect to the database instead of the old driver, which PHP no longer supports. with PDO you can use prepared statements to prevent sql injections
PDO tutorial
filter_var() Constants
dbh.php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = 'db';
try {
$db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
exit($e->getMessage());
}
?>
serve.php
<?php
include("dbh.php");
if (isset($_POST['done'])) {
$q_no = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$total_no = filter_var($_POST['comment'], FILTER_SANITIZE_STRING);
try {
$stmt = $db->prepare("INSERT INTO variables(id, names) VALUES(?, ?)");
$stmt->execute(array($q_no, $total_no));
echo json_encode(["message" => "success"]); // sends success response to front-end
} catch (\Exception $e) {
echo json_encode(["message" => $e->getMessage() ]); // sends error response to front-end
}
}
?>
in your ajax check if the data was inserted or not.
$("#q_answer1").click(function() {
var q_no = $("#q_no").val();
var main_no = $("#total_no").val();
$.ajax({
url: "file.php",
type: "post",
async: false,
data: {
"done": 1,
"username": q_no,
"comment": main_no
},
success: function(data) {
const respose = JSON.parse(data);
if (respose.message === 'success') { // data was inserted
$("#q_no").val('');
$("#total_no").val('');
}else {
alert(respose.message); // some error has occured
}
}
});
});

You have to take value of div as mentioned below,
var q_no = $("#q_no").text();
var main_no = $("#total_no").text();
Pass data in key-value Pair, After pass first key-value data concate other data with & sign key.
$( "#q_answer1" ).click(function () {
var q_no = $("#q_no").val();
var main_no = $("#total_no").val();
$.ajax({
url: "server.php",
type: "post",
async: false,
data: 'done=' + 1 + '&username=' + q_no + '&comment=' + main_no,
success: function(){
$("#q_no").val('');
$("#total_no").val('');
}
});
});

You can't use val() on div. Try using text() and then check if your server.php is getting these value.
Thanks

You have typo error in jquery
$qAnswer1.click(function () {
Should be
$('#q_answer1').click(function () {
You can try following to test
$( "#q_answer1" ).click(function() {
alert( "Handler for .click() called." );
});
Include the jquery at the top of your page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Full working code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="total_no">1</div>
<div id="q_answer1" class="btn left_b">yes</div>
<script type="text/javascript">
$( "#q_answer1" ).click(function () {
var q_no = $("#q_no").val();
var main_no = $("#total_no").val();
$.ajax({
url: "ajax.php",
type: "post",
async: false,
data: {
"done": 1,
"username": q_no,
"comment": main_no
},
success: function(){
$("#q_no").val('');
$("#total_no").val('');
}
});
});
</script>
in your PHP file try to print $_POST to see its working.

Related

Posting data from ajax to a php script

Issue
I have an onclick Jquery function that will return the value in the first cell of the clicked table row. I then try to pass this value using ajax type: 'POST' to a php script that will then execute a database query using this value for comparison. For some reason, $_POST is always empty. The ajax is not returning any errors but i'm unable to receive the value of the array on server-side. Any help is appreciated.
jQuery
$('tr.profileTableClick').click(function() {
var tableData = $(this).find('td:nth-child(1)').map(function() {
return $(this).text();
}).get();
$.ajax({
url: 'selectAnswers.php',
type: 'POST',
data: {
'id': tableData
},
dataType: 'text',
error: function() {
console.log('Error in ajax request');
},
success: function(data) {
console.log('Success of ajax request');
console.log(data);
}
});
PHP
Here is the selectAnswers.php file:
<?php
$id = $_POST['id'][0];
try {
$conn = new PDO(
"mysql:host=$servername;dbname=$dbname",
$username,
$password
);
$conn->setAttribute(
PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION
);
$stmt = $conn->prepare(
"SELECT
quality_of_service,
self_improvement,
personal_behavior,
organization_rules_commitment,
team_work,
appearance, work_with_high_responsibility,
loyalty_to_organization,
punctuality_on_work,
office_maintaining, areas_of_improvement,
points_of_weakness,
points_of_strength
FROM appraisals_table
WHERE Apr_Id = :id"
);
$stmt->bindValue(
':id',
$id,
PDO::PARAM_INT
);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$ans1 = $row['quality_of_service'];
$ans2 = $row['self_improvement'];
$ans3 = $row['personal_behavior'];
$ans4 = $row['organization_rules_commitment'];
$ans5 = $row['team_work'];
$ans6 = $row['appearance'];
$ans7 = $row['work_with_high_responsibility'];
$ans8 = $row['loyalty_to_organization'];
$ans9 = $row['punctuality_on_work'];
$ans10 = $row['office_maintaining'];
$ans11 = $row['areas_of_improvement'];
$ans12 = $row['points_of_weakness'];
$ans13 = $row['points_of_strength'];
}
} catch(PDOException $e) {
echo 'Error: '. $e->getMessage();
}
$conn = null;
Change either js:
var tableData = $(this).find("td:nth-child(1)").text();
or the php:
$id = (int)$_POST['id'][0]
Use the new javascript's FormData API like so. . .
var formdata = new FormData();
formdata.append('id', tableData);
$.ajax({
url: 'selectAnswers.php',
type: 'POST',
data: formdata,
dataType: 'text',
error: function(){
console.log("Error in ajax request");
},
success: function(data) {
console.log("Success of ajax request");
console.log(data);
}
});

How to insert php ajax textbox value into mysql database table?

I have ajax call in my index page, when the user enter a username into the text box it's need to insert into a mysql db table,can't find a way to do it?
This is my code
$(document).ready(function () {
$('#enter_email_id').change(function () {
var str = $('#enter_email_id').val();
var webFormURL = "get_acc_info.php?q=" + str;
$.ajax({
url: webFormURL,
async: false,
success: function (response) {
$('.test_acc').html(response);
}
});
This is insert db php page
<?php
session_start();
$_SESSION["username"];
function insert_Details(){
include 'Db_Connection.php';
$sql="INSERT INTO search(searcher,searched_time,searched_email)
VALUES('$_SESSION[username]',".NOW().",'$_POST[searched_email]')";
}
?>
for security reasons you should use mysqli_real_escape_string() for input values.
I've got to fix your code, but you should replace $_SESSION["username"] value with what you want, use this code:
JavaScript:
$(document).ready(function () {
$('#enter_email_id').change(function () {
var str = $('#enter_email_id').val();
var webFormURL = "get_acc_info.php?q=" + str;
$.ajax({
type: 'post',
url: webFormURL,
async: false,
success: function (response) {
$('.test_acc').html(response);
}
});
PHP:
$_SESSION["username"] = 'test_username';
function insert_Details(){
//create mysqli connection
include 'Db_Connection.php';
$string = mysqli_real_escape_string($mysqli_link,$_POST[searched_email]);
$session = mysqli_real_escape_string($mysqli_link,$_SESSION[username]);
$sql="INSERT INTO search(searcher,searched_time,searched_email)
VALUES('$session',NOW(),'$string')";
if(mysqli_query($mysqli_link,$sql) ) {
echo "OK";
}
}
?>

How can I retrive data from db with ajax and php?

I'm trying to check if a field is just present into db before submit a form.
So I add the keyup event to that field to get data from db with ajax.
So where I have the form I add this code:
$(document).ready(function (){
$("#matricola").keyup(function () {
$.ajax({
type:"get",
url: "getMatricolaAjax.php",
data: {'type':'user', 'matricola':$("#matricola").val()},
dataType: "text",
success: function(result){
console.log("OK");
$("#matricola").val("");
alert("Matricola "+ result +" già presente!!");
},
error: function(){
console.log("KO");
}
});
});
});
And this is my getMatricolaAjax.php:
<script src='js/jquery-2.1.4.js' type="text/javascript"></script>
<?php
require_once 'config.php';
require_once FUNCTION_PATH.'/dbFunction.php';
if($_GET['type'] == "user"){
$queryMatricolaMatch = 'select * from user where matricola = "'.$_GET['matricola'].'"';
}else{
$queryMatricolaMatch = 'select * from 150ore where matricola = "'.$_GET['matricola'].'"';
}
echo $queryMatricolaMatch;
$conn = dbConnect($USERDB, $PASSWORDDB, $NAMEDB);
$matricola = dbQueryGetResult($queryMatricolaMatch);
dbDisconnect($conn);
echo $matricola;
It works for half, beacause in result I obtain all html code from getMatricolaAjax.php..
Why??
How can I get only matricola??
Comment or remove dataType: "text" and try again.
$.ajax({
type:"get",
url: "getMatricolaAjax.php",
data: {'type':'user', 'matricola':$("#matricola").val()},
// dataType: "text",
success: function(result){
console.log("OK");
$("#matricola").val("");
alert("Matricola "+ result +" già presente!!");
},
or else you can use json_encode() in PHP to get data as JSON object array.
You should use POST to check for value in database before submitting a form.
$(document).ready(function (){
$("#matricola").keyup(function (e) {
var thevalue = $(this).val();
$.post('getMatricolaAjax.php',{'type':'user','matricola':thevalue},
function(data) {
console.log("OK");
$("#matricola").val("");
alert("Matricola "+ data +" già presente!!");
});
});
});
And the php file
<?php
require_once 'config.php';
require_once FUNCTION_PATH.'/dbFunction.php';
$conn = dbConnect($USERDB, $PASSWORDDB, $NAMEDB);
if($conn->real_escape_string($_POST['type']) == "user"){
$queryMatricolaMatch = 'select * from user where matricola = "'.$conn->real_escape_string($_POST['matricola']).'"';
}else{
$queryMatricolaMatch = 'select * from 150ore where matricola = "'.$conn->real_escape_string($_POST['matricola']).'"';
}
$matricola = dbQueryGetResult($queryMatricolaMatch);
dbDisconnect($conn);
echo $matricola;
This should work, but I have no idea what dbQueryGetResult is supposed to do so you should post it too.
Note:If you use PDO edit remove 'real_escape_string' function and use other methods of sanitization

How to handle json response from php?

I'm sending a ajax request to update database records, it test it using html form, its working fine, but when i tried to send ajax request its working, but the response I received is always null. where as on html form its show correct response. I'm using xampp on Windows OS. Kindly guide me in right direction.
<?php
header('Content-type: application/json');
$prov= $_POST['prov'];
$dsn = 'mysql:dbname=db;host=localhost';
$myPDO = new PDO($dsn, 'admin', '1234');
$selectSql = "SELECT abcd FROM xyz WHERE prov='".mysql_real_escape_string($prov)."'";
$selectResult = $myPDO->query($selectSql);
$row = $selectResult->fetch();
$incr=intval($row['votecount'])+1;
$updateSql = "UPDATE vote SET lmno='".$incr."' WHERE prov='".mysql_real_escape_string($prov)."'";
$updateResult = $myPDO->query($updateSql);
if($updateResult !== False)
{
echo json_encode("Done!");
}
else
{
echo json_encode("Try Again!");
}
?>
function increase(id)
{
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
success: function (response) {
},
complete: function (response) {
var obj = jQuery.parseJSON(response);
alert(obj);
}
});
};
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
dataType: 'json',
success: function (response) {
// you should recieve your responce data here
var obj = jQuery.parseJSON(response);
alert(obj);
},
complete: function (response) {
//complete() is called always when the request is complete, no matter the outcome so you should avoid to recieve data in this function
var obj = jQuery.parseJSON(response.responseText);
alert(obj);
}
});
complete and the success function get different data passed in. success gets only the data, complete the whole XMLHttpRequest
First off, in your ajax request, you'll want to set dataType to json to ensure jQuery understands it is receiving json.
Secondly, complete is not passed the data from the ajax request, only success is.
Here is a full working example I put together, which I know works:
test.php (call this page in your web browser)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Define the javascript function
function increase(id) {
var post_data = {
'prov': id
}
$.ajax({
'type': 'POST',
'url': 'ajax.php',
'data': post_data,
'dataType': 'json',
'success': function (response, status, jQueryXmlHttpRequest) {
alert('success called for ID ' + id + ', here is the response:');
alert(response);
},
'complete': function(jQueryXmlHttpRequest, status) {
alert('complete called');
}
});
}
// Call the function
increase(1); // Simulate an id which exists
increase(2); // Simulate an id which doesn't exist
</script>
ajax.php
<?php
$id = $_REQUEST['prov'];
if($id == '1') {
$response = 'Done!';
} else {
$response = 'Try again!';
}
print json_encode($response);

Auto Refresh JS Array if content changes?

I have this javascript function which serves an AJAX request to an external PHP Script, I want this to auto update a HTML <div> if the new check is different from the old check.
<script>
window.setInterval(function()
{
$(function ()
{
$.ajax({
url: 'api.php', data: "", dataType: 'json', success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var vname = row[1];
var Password = row[2]
$('#output').append("<hr />").append("<b>id: </b>"+id+"<b> name: </b>"+vname+" <b>Password: </b>"+Password);
}
}
});
});
}, 5000);
</script>
This currently sucessfully returns and updates the div with the content from the array, the problem is, since adding the window.setInterval(function() line, it will server the connection every 5 seconds and update the <div> with duplicate data.. when all I want, it for it to echo the new data (if there is a ny)
Here is my other PHP script:
$STD = new mysqli ("localhost", "root", "hidden", "ajaxrequests");
$array = array();
$Query = $STD->prepare ("SELECT * FROM ajaxdata");
$Query->execute();
$Query->bind_result($ID, $Name, $Password);
while ($Query->fetch())
{
$array[] = array ( $ID, $Name, $Password);
}
echo json_encode($array);
Just add a call to empty() before your loop.
<script>
window.setInterval(function()
{
$(function ()
{
$.ajax({
url: 'api.php', data: "", dataType: 'json', success: function(rows)
{
$('#output').empty();
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var vname = row[1];
var Password = row[2]
$('#output').append("<hr />").append("<b>id: </b>"+id+"<b> name: </b>"+vname+" <b>Password: </b>"+Password);
}
}
});
});
}, 5000);
</script>
Of course if your data size is large, this would not be very optimal. I would actually suggest having the PHP server send a timestamp value with it's response. You could then pass this back in subsequent AJAX requests and have the server determine if there are actually updates to deliver since that last timestamp. You could then have the server only send those updated records, which you could append/update similar to how you are already doing it.

Categories