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

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";
}
}
?>

Related

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

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.

Replace div contents with content from PHP file

This is the php file containing the new content, to replace .hotels when the form is submitted.
<?php
if(isset($_POST['submit'])){
$pdo = new PDO('mysql:host=localhost;dbname=CSV_DB', 'root', 'root');
$inputType = $_POST['type'];
$inputCategory = $_POST['category'];
$type = $pdo->query("SELECT * FROM Hotels WHERE Type LIKE '%$inputType%' AND Price_Range= '$inputCategory'");
foreach($type as $row){
echo"<div id='newHotels'>";
echo "<div class='hotelImage'></div>";
echo'<h4>'.$row['Hotel_Name']." ".$row['Rating']."*".'</h4>'." ".'<p>'.$row['Description'].'</p>'." "."Location: ".$row['Location']." ".'<h4 style="font-weight: bold">'."£".$row['Price']."p/p".'</h4>';
echo "</div>";}
}
?>
Here is the original div that displays all the hotels in the database when the page loads and that I want to replace with the new content when the form is submitted:
<div id="hotels">
<?php
$pdo = new PDO('mysql:host=localhost;dbname=CSV_DB', 'root', 'root');
$display = $pdo->query('SELECT Hotel_Name, Description, Location, Rating, Price FROM Hotels');
foreach ($display as $row){
if($row)
echo"<div id='hotel'>";
echo "<div class='hotelImage'></div>";
echo'<h4>'.$row['Hotel_Name']." ".$row['Rating']."*".'</h4>'." ".'<p>'.$row['Description'].'</p>'." "."Location: ".$row['Location']." ".'<h4 style="font-weight: bold">'."£".$row['Price']."p/p".'</h4>';
echo "</div>";}
?>
</div>
And here is the Ajax that is supposed to change the content
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'form.php',
data: $('form').serialize(),
success: function(data) {
$(".hotels").html(data);
}
});
});
});
I need help replacing the contents of .hotels with the search results of my form when the form submits however the div just becomes empty. I think I need to make data equal to the search results but not sure how to go about it.
submitted the console log says data is not defined.
You need to define data in the success function.
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'form.php',
data: $('form').serialize(),
success: function(data) { /* you missed variable data here */
$("#hotel").html(data);
}
});
});
});
The console log saying "data" is not defined means there is no variable named "data". to solve this issue, you could either create a global variable called "data", or pass "data" as an argument to the success function. This would then look somewhat like this:
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'form.php',
data: $('form').serialize(),
success: function(data) {
$("#hotel").html(data);
}
});
});
});

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

jQuery autosave running success function, but not updating MySQL

My jQuery autosave is running the success function, but not updating the MySQL database. What am I doing incorrectly?
jQuery:
function autosave() {
var t = setTimeout("autosave()", 5000);
var translation = $("#doc-translation").val();
if (translation.length > 0) {
$.ajax({
type: "POST",
url: "update-draft-submission.php",
data: translation,
cache: false,
success: function() {
$(".autosaved").empty().append("saved");
}
});
}
}
PHP:
<?php
session_start();
//retrieve our data
$iddoc = $_GET['iddoc'];
$trans = translation;
$transowner = $_SESSION['userid'];
$true = 1;
include "../dbconnect.php";
$query = "UPDATE translations
SET trans='$trans'
WHERE iddoc='$iddoc'
AND transowner='$transowner'";
mysqli_query($query);
mysqli_close();
echo "Saved";
?>
You are not fetching the data in your PHP correctly:
$iddoc = $_GET['iddoc'];
$trans = translation;
iddoc is not passed as a GET parameter anywhere
"translation" is not a variable (neither do I think it is a constant)
Your SQL will break if it does not get the required values in the query.
Update your javascript so:
$.ajax(
{
type: "POST",
url: "update-draft-submission.php",
data: data: {translation:translation,iddoc:"XXX"},
cache: false,
success: function()
{
$(".autosaved").empty().append("saved");
}
});
Replace XXX with your iddoc value.
Then in PHP fetch them as:
$iddoc = $_POST['iddoc'];
$trans = $_POST['translation'];

Jquery ajax is not sending data

For some reason ajax is not sending data.
On the PHP I have this code:
if (isset($_POST['submit'])) {
echo "submit";
} else {
echo "not submit";
}
And I get not submit.
This is JS code:
$(function () {
$('#submit').click(function () {
var length = $('#number').val();
var small = $('#small').val();
var big = $('#big').val();
var number = $('#numero').val();
var special = $('#special').val();
var submit = 'submit';
var url = 'public/php/codegenerator.php';
var data = "length=" + length + "&small=" + small + "&big=" + big +
"&number=" + number + "&special=" + special + "&submit=" + submit;
$.ajax({
type: "POST",
url: url,
data: data,
success: function () {
$('#code').load(url, function () {
$(this).fadeIn(1000)
});
}
});
return false;
});
});
You can try this approach
$(function(){
$('#submit').click(function(){
//YOUR CODE
var param = {
length:length,
small:small,
big:big,
number:number,
special:special,
submit:submit
}
$.ajax({
type: "POST",
url: url,
data: param,
//EDITED LINE
success: function (data) {
$('#code').hide().html(data).fadeIn(1000);
}
});
return false;
});
});
// REVISED ANSWER
// IN YOUR PHP FILE
if (isset ($_POST['submit'])) {
echo json_encode(array('result'=>"submit"));
}
else {
echo json_encode(array('result'=>"not submit"));
}
//IN YOUR JQUERY CODE
$.ajax({
type: "post",
url: url,
data: param,
dataType:'json';
//EDITED LINE
success: function (data) {
// alert(data.result);
$('#code').hide().html(data.result).fadeIn(1000);
}
});
You are getting Not submit, because it comes from the .load() call and not from .ajax - and in the load call you just load the URL without passing any POST data. So why you are running .load inside the success callback of .ajax with the same url?

Categories