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
Related
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.
I am using meekro db to fetch data from database and when I return object as json format then ajax call goes to error
$(".cat").click(function() {
var value = $(this).attr('id');
$.ajax({
url:"/psl/ajax/get_words.php",
method:"post",
dataType: "json",
data:{ id: value },
success:function(response) // success part does not execute
{
var data = JSON.parse(response);
alert( data );
},
error:function (msg) { // error part executes every time
alert('error');
}
});
});
And the code which is being used to fetch data from database get_words.php
<?php
require_once '../inc/initDb.php';
$id = $_POST['id'];
$words = DB::query("select * from words where category_id = '$id'");
if (DB::count() > 0)
{
echo json_encode($words);
}
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);
}
});
});
});
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";
}
}
?>
I can't get each data from PHP file, i'm always having AJAX failure, i tried many things, and looked for some pages for this problem but i can't find any solution, this is where i came last.
This is my jQuery function:
$(document).ready(function () {
$(function () {
$('a[class="someclass"]').click(function(){
var somedata = $(this).attr("id");
$.ajax({
type: "POST",
url: "foo.php",
data: {"id": somedata},
dataType:"json",
success: function(data){
e.preventDefault();
$("#data1").html(data[0]);
$("#data2").html(data[1]);
$("#data3").html(data[2]);
$("#data4").html(data[3]);
},
error:function(){
alert("AJAX request was a failure");
}
});
});
});
});
This is my PHP file:
$data = $_POST['id'];
$con = mysqli_connect('localhost','root','','database');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"database");
$sql="SELECT * FROM table WHERE id = '".$data."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$jsondata1 = array($row['data1'], $row['data2'], $row['data3'], $row['data4']);
echo json_encode($jsondata1);
}
mysqli_close($con);
I think there is no need to share HTML file, but if you want i can share with you.
Thank You!
You are overriding the array value in the loop and echo $jsondata1, so you are sending many different arrays with the echo inside the loop, try this code:
$jsondata1 = array();
while($row = mysqli_fetch_array($result)) {
$jsondata1[] = array($row['data1'], $row['data2'], $row['data3'], $row['data4']);
}
echo json_encode($jsondata1);
e.preventDefault(); is a problem. e is not defined and if it was the default action would have already occurred by the time the success function was called. Try
$('a[class="someclass"]').click(function(e){
e.preventDefault();
var somedata = $(this).attr("id");
$.ajax({
type: "POST",
url: "foo.php",
data: {"id": somedata},
dataType:"json",
success: function(data){
$("#data1").html(data[0]);
$("#data2").html(data[1]);
$("#data3").html(data[2]);
$("#data4").html(data[3]);
},
error:function(){
alert("AJAX request was a failure");
}
});
});
});
});
You need to encode the complete response.
when you echo each encoded it will not work.
Do something like
$jsonArray = array();
while(){
array_push($jsonArray, array($row['data1'], $row['data2']);
}
echo json_encode($jsonArray);
You're calling json_encode multiple times when what you need to be doing is assigning those intermediate variables to an array and encode that array using json encode for the return.
PHP:
$data = $_POST['id'];
$con = mysqli_connect('localhost','root','','database');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"database");
$sql="SELECT * FROM table WHERE id = '".$data."'";
$result = mysqli_query($con,$sql);
$jsondata1 = [];
while($row = mysqli_fetch_array($result)) {
$jsondata1[] = array($row['data1'], $row['data2'], $row['data3'], $row['data4']);
}
mysqli_close($con);
die(json_encode($jsondata1));
JavaScript:
$(document).ready(function () {
var doc = $(document);
doc.on('click', 'a.someclass', function(e){
e.preventDefault();
var somedata = $(this).attr("id");
$.ajax({
type: "POST",
url: "foo.php",
data: {"id": somedata},
dataType:"json",
success: function(data){
$("#data1").html(data[0]);
$("#data2").html(data[1]);
$("#data3").html(data[2]);
$("#data4").html(data[3]);
},
error:function(){
alert("AJAX request was a failure");
}
});
});
});