Update database on buttonclick with AJAX and PHP [duplicate] - php

This question already has answers here:
JavaScript does not fire after appending [duplicate]
(3 answers)
Closed 7 years ago.
I have searched all over for this and cannot find a solution. I am still a beginner in both PHP and AJAX, so please bear with me.
I have a file fetch.php which generates content for my page index.html.
Fetch.php gets data from a MySQL database and adds it to my index page like this:
while ($res = mysqli_fetch_array($rs)) {
$str .= '<div class="task" id='.$res['tid'].'>
<table>
<tr>
<td>
<button class="btnDelete" data-id="'.$res['tid'].'">x</button>
</td>
<td>'.$res["name"].'</td>
</tr>
<tr>
<td>'. $res["task"].'</td></tr></table></div>';
}
echo $str;
The "tid" being my table index. Now, when I click the button with the data-id of 1, I want to delete the row with the tid of 1.
<script type="text/javascript">
$('.btnDelete').click(function() {
var recordid = $('.btnDelete').data('id');
$.ajax({
type: 'POST',
url: 'remove.php',
data: { 'id': recordid},
});
});
</script>
This sends the (supposed to) data-id to the following PHP.
$con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);
if (!$con) {
die("Can not connect: " .mysql_error());
}
$id = $_POST['recordid'];
$sql = "UPDATE tasks SET visible = 'hide' WHERE tid = $id ";
$query = mysqli_query($con, $sql);
if(mysqli_affected_rows($con)) {
echo "Record deleted successfully";
}
mysqli_close($con);
My PHP files work, but nothing happens when I click the button?
Below is my complete HTML:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src='https://code.jquery.com/jquery-2.1.3.min.js'></script>
<script type="text/javascript">
$(function() {
getStatus();
});
function getStatus() {
$('div#data').load('fetch.php');
setTimeout("getStatus()",300000);
}
</script>
</head>
<body>
<div id="data">
</div>
<script type="text/javascript">
$('.btnDelete').click(function() {
var recordid = $('.btnDelete').data('id');
$.ajax({
type: 'POST',
url: 'remove.php',
data: { 'id': recordid},
});
});
</script>
</body>
</html>
How can I get the AJAX to trigger on the buttonclick and send the data-id to remove.php?
This is not a duplicate, it is an AJAX question and not a MySQL question

As your AJAX loads your HTML and injects it in to the page, you'll have to use on event when binding.
$(document).on("click", ".btnDelete", function () {
/** Your code here. **/
});
Reading Material
Event Delegation

Related

AJAX load to another div with variable

Hey Im trying to load another div with passing variable.
Im in the div#main , I want a after click #modifybtn button pass the btn value and load it with another div#modify and working with some query.
im noob for jQuery and ajax, I search in web but cant get solution for this.
please check relevant code and tell me about issue.
here is the div#main #modifybtn button and div#modify
<div id=main>
<button id="modifybtn" value="some_value" >Modify</button>
</div>
<div id="modify">
<?php
$resultmodi=$conn->query("SELECT * FROM vacancy WHERE vc_id='{$_GET['id']}' LIMIT 1 ");
?>
</div>
dashcompany.php inside
<div class="contentcm" >
//contentcm.php page load content here
</div>
this is my jQuery, after clicking button alert showing but not redirect to the #modify div
$(document).ready(function(){
$('.contentcm').load('contentcm.php #main');
$('a').click(function(){ //main and modify division in contentcm.php
var clickedLink1 = $(this).attr('id');
$('.contentcm').load('contentcm.php #' + clickedLink1);
});
});
$(document).on("click", '#modifybtn', function(event) {
var id = $(this).val();
alert(id);
event.preventDefault();
$.ajax({
url: 'dashcompany.php',
type: 'get',
data: {'id' : id},
success: function(response) {
$('#modify').html(response);
}
});
});
This will be initial.html file
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src = "FILE_NAME.js"></script>
</head>
<body>
<div id=main>
<button id="modifybtn" value="some_value" >Modify</button>
<div id="modify"></div>
</div>
</body>
</html>
Your code in FILE_NAME.js should be like
$(document).on("click", '#modifybtn', function(event) {
var id = $(this).val();
alert(id);
event.preventDefault();
$.ajax({
url: 'dashcompany.php',
type: 'get',
data: {'id' : id},
success: function(response) {
$('#modify').html(response);
}
});
Your js file will load the data from dashcompany.php and load in #modify which is in initial.html file
dashcompany.php
<?php
include_once('connection.php');
$id = $_GET['id'];
$resultmodi=$conn->query("SELECT * FROM vacancy WHERE vc_id='$id' LIMIT 1 ");
$row = $resultmodi->fetch_assoc();
echo "Name: " . $row["name"];
''' print data whatever you need '''
$conn->close();
?>
REASON:
May be you forgot to print data in dashcompany.php file that's why you are getting blank response from ajax request.
And don't forget to include #modify div in the same html file where #main#modify div exists
You can use as follow code, and I suggest you to use post method
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<button type='button' id="modifybtn" class='btn btn-info' value="some_value">click here</button>
<div class="" id="modify"></div>
<script type="text/javascript">
$(document).on("click", '#modifybtn', function(event) {
var id = $(this).val();
//alert(id);
$.ajax({
url: 'dashcompany.php',
type: 'post',
data: {'id' : id},
dataType: 'json',
success: function(response) {
//now you can call with column name of data table
$('#modify').html("<P>"+response.column_one_name+"</p><br><P>"+response.column_two_name+"</p>");
}
});
});
</script>
And your dashcompany.php page should like this,
<?php
// $localhost = "127.0.0.1";
// $username = "root";
// $password = "";
// $dbname = "db_304";
//
// $connect = new mysqli($localhost, $username, $password, $dbname);
// // check connection
// if ($connect->connect_error) {
// die("Connection Failed : " . $connect->connect_error);
// }
$id = $_POST['id'];
$sql = "SELECT * FROM vacancy WHERE vc_id = '$id' LIMIT 1 ";
$result = $connect->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_array();
} // if num_rows
$connect->close();
echo json_encode($row);
Hope this will help you.

searchfunction with JQuery AJAX

So Im designing a searchfunction for the backend of a website and Im doing so with AJAX.
So far if you press the "Members" Button it gets the relevant info from the database and displays the members in a table. So far so good.
Now I added a form above the div in which it displays the table:
<form id="searchmember" method="post">
<input type="text" name="searchm" placeholder="Look for a Member!"/>
<input id="search" type="submit" value=">>" name="search"/>
</form>
<div id="eachTable">
And added a function into my JQuery that reacts when the "search" button gets pressed:
$("#search").click(function(){
if(ifIssetData == 1){
var searchm = $('input[name="searchm"]').val();
$.post('/website/administrator/components/com_backend/searchPerson.php', 'val=' + $(searchm).val());
$.ajax({
async: true,
dataType: 'json',
url: '/website/administrator/components/com_backend/searchPerson.php',
error: function(data2, error2, errorThrown2){
alert(JSON.stringify(data2));
alert(error2);
alert(errorThrown2);
},
success: function(data2,status)
{
createTableByJqueryEach2(data2);
},
});
The createTable function is designed to take the data, put it into a table and display that table in the eachTable Div.
So you see it posts searchm to the php file where the following happends:
<?php
include($_SERVER['DOCUMENT_ROOT'].'/website/dbConnection.php');
$searchtrue = $_POST['val'];
$query = "SELECT Titel, Vorname, Nachname, Unternehmen, Gruppe FROM mitglieder WHERE Titel LIKE '%$searchtrue%' OR Vorname LIKE '%$searchtrue%' OR Nachname LIKE '%$searchtrue%' OR Unternehmen LIKE '%$searchtrue%' OR Gruppe LIKE '%$searchtrue%'";
function filterTable($query)
{
$filter_Result = mysqli_query($GLOBALS['connect'], $query);
return $filter_Result;
}
$searchresult = filterTable($query) or die("Tabelle kann nicht angezeigt werden");
$data2 = mysqli_fetch_all($searchresult);
echo json_encode($data2);
?>
So now that you have the code, the Issue. When I press the "search" button the page just reloads and nothing happens. I assume the PHP File doesnt receive the POST? But why? The html is very simple so Im sure that works. The PHP should work but Im not sure since I always had a difficult time getting JQuery and PHP Files to work together.
Anybody know where my issue lies?
edit: I thought Ill just add the function in case the issue lies there
function createTableByJqueryEach2(data2)
{
var eTable2="<table><thead><tr><th colspan='5'>Created by for loop</th></tr><tr><th>Titel</th><th>Vorname</th><th>Name</th><th>Unternehmen</th><th>Gruppe</th</tr></thead><tbody>"
$.each(data2,function(index2, row2){
// eTable += "<tr>";
// eTable += "<td>"+(data2)[i]['Titel']+"</td>";
// eTable += "<td>"+(data2)[i]['Vorname']+"</td>";
// eTable += "<td>"+(data2)[i]['Name']+"</td>";
// eTable += "<td>"+(data2)[i]['Unternehmen']+"</td>";
// eTable += "<td>"+(data2)[i]['Gruppe']+"</td>";
// eTable += "</tr>";
eTable2 += "<tr>";
$.each(row2,function(key2,value2){
eTable2 += "<td>"+value2+"</td>";
});
eTable2 += "</tr>";
});
eTable2 +="</tbody></table>";
$('#eachTable').html(eTable2);
}
Your form is getting submitted as you have a submit input, and it has no action, so it's refresing.
You can change your form to a div or use this:
$(document).ready(function() {
$('#searchmember').on('submit', function(e){
e.preventDefault();
});
});
Also, I created this file and it's working nice:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form id="searchmember" method="post">
<input type="text" name="searchm" placeholder="Look for a Member!"/>
<input id="search" type="submit" value=">>" name="search"/>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#searchmember').on('submit', function(e){
e.preventDefault();
});
});
$("#search").click(function(e){
var ifIssetData= 1;
if(ifIssetData == 1){
var searchm = $('input[name="searchm"]').val();
$.post('/website/administrator/components/com_backend/searchPerson.php', 'val=' + $(searchm).val());
$.ajax({
async: true,
dataType: 'json',
url: '/website/administrator/components/com_backend/searchPerson.php',
error: function(data2, error2, errorThrown2){
alert(JSON.stringify(data2));
alert(error2);
alert(errorThrown2);
},
success: function(data2,status)
{
createTableByJqueryEach2(data2);
}
});
}
});
</script>
</body>
</html>
You don't need to use a form with AJAX.
If you replace the form with a div, it will resolve the problem.
When you "submit" the form, it tries to post the data somewhere.
Since you've not supplied a URL, it reloads.

Fill in data from database in multiple divs via ajax request

I have 2 divs on my html page. When I press my button I want to fill the div #question1 with the question1 data from my database and the #question2 div with the question2 data from my database. Now the 2 divs are filled with the same data.
This is my html and js code
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function () {
"use strict";
$('#button').click(function() {
$.ajax({
url: 'getquestions.php',
success: function(data) {
$('#question1').html(data);
$('#question2').html(data);
}
});
});
});
</script>
<input type="button" id="button" value="Load" />
<div id="question1"></div>
<div id="question2"></div>
</body>
</html>
The php file
<?php
$connection = mysqli_connect("localhost", "root", "" , "mobiledatabase");
$query = "SELECT question1, question2 FROM adult_questions WHERE id=3";
$query_run = mysqli_query($connection,$query);
$query_row = mysqli_num_rows($query_run);
if ($query_row==1) {
foreach ($query_run as $row ) {
echo $question1 = $row['question1'];
echo $question2 = $row['question2'];
}
}
?>
Update your php file.
Create an array like $retArr = array("question1" =>$question1,"question2" =>$question2); in your php file Then convert it in to json using json_encode($retArr) & echo json_encode($retArr) In your ajax response show $('#question1').html(data.question1);
Hope this will help
Try this,
In PHP pass it like,
$question1='';$question2='';
if ($query_row==1) {
foreach ($query_run as $row ) {
$question1 = $row['question1'];
$question2 = $row['question2'];
}
}
echo json_encode(array('question1'=>$question1,'question2'=>$question2));
In Jquery,
$.ajax({
url: 'getquestions.php',dataType:'json',
success: function(data) {
$('#question1').html(data.question1);
$('#question2').html(data.question2);
}
});

auto search the keyword in textarea

This is my coding. This coding allows me to search the keyword in my database and it worked fine. But how can i search the keyword without click the search button? What i want is same as the search function in the google search. It can automatically help you search and review without hit any button.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Search Contacts</title>
</head>
<p><body>
<h3>Search Contacts Details</h3>
<p>You may search either by first or last name</p>
<form method="post" action="search.php?go" id="searchform">
<input type="text" name="question">
<input type="submit" name="submit" value="Search">
</form>
<?php
if(isset($_POST['submit'])){
if(isset($_GET['go'])){
if(preg_match("/^[ a-zA-Z]+/", $_POST['question'])){
$question=$_POST['question'];
$con = mysqli_connect("localhost","root","");
mysqli_select_db($con,"search")or die(mysqli_error($con));;
$sql="SELECT id , question FROM question WHERE question LIKE '%" . $question . "%'";
//-run the query against the mysql query function
$result=mysqli_query($con, $sql);
while ($row=mysqli_fetch_array($result)){
$question =$row['question'];
$id=$row['id'];
echo "<ul>\n";
echo "<li>" . " " . $question . "</li>\n";
echo "</ul>";
}
}
else{
echo "<p>Please enter a search query</p>";
}
}
}
?>
</body>
</html>
</p>
Well, the way Google does it is a bit different. However, what you can do is use JavaScript (jQuery is probably easiest for you here) to send a XHR, which would retrieve the results. This would look something like this
$('input[name="question"]').on('keyup', function (e) {
$.ajax({
url: "search.php?go",
method: 'post',
data: {
query: e.target.val()
}
}).done(function(data) {
// Output your data however you want
});
}
Of course, you could also use the GET HTTP method, that's all your preference.
Now, aside from this, it looks like you have a SQL injection vulnerability in your query. Essentially, if I would input 'DROP DATABASE question as my search query, that would drop your database. What you should be doing is using prepared statements using Mysql::prepare, see the docs here.
Final note: Google does not do it this way. The best way to achieve blazing fast search results is using WebSockets to maintain a socket connection to your server, and letting the search run through a document database such as Elasticsearch, which is optimised for full-text search.
Step 1:
give ID to your input field...
<div class="content">
<input type="text" class="search" id="searchid" placeholder="Search Here" />
<div id="result"></div>
</div>
Step 2:
On keyUp search variable is cathed into vaiable and passed via AJAX to "findit.php"
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(function(){
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = \'search=\'+ searchid;
if(searchid!=\'\')
{
$.ajax({
type: "POST",
url: "findit.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
jQuery("#result").on("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find(\'.name\').html();
var decoded = $("<div/>").html($name).text();
$(\'#searchid\').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$(\'#searchid\').click(function(){
jQuery("#result").fadeIn();
});
});
</script>
Step 3:
Now create a php file having name "findit.php" and use the below code
include('conn.php'); //this is your DB connection file
if($_POST)
{
$q = mysqli_real_escape_string($connection,$_POST['search']);
$qry = mysqli_query($connection,"select col_name from tbl_name where col_name like '%$q%' order by col_name LIMIT 7");
while($row=mysqli_fetch_array($qry))
{
$col_name = $row['col_name'];
$b_res = '<strong>'.$q.'</strong>';
$final_res = str_ireplace($q, $b_res, $col_name);
?>
<?php
}
}
?>

Jquery function not work with php echoing code

I'm new to php.
I want to use jquery to delete a table row from php echoing code, but it doesn't work.
Here is my html code:
<!DOCTYPE html>
<html>
<head>
<title>test insert</title>
<script src="jquery-2.0.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.del').click(function(){
$(this).parent().parent().fadeOut('slow');
});
$('#show').click(function(){
$.post('data.php',{action: "show"},function(res){
$('#result').hide().html(res).fadeIn('slow');
});
});
});
</script>
</head>
<body>
<h2>Show Data</h2>
<button id="show">Show</button>
<p>Result:</p>
<div id="result"></div><br>
</body>
</html>
and here is my php code:
<?php
//connect to db
$con = mysql_connect('localhost','root');
$db = mysql_select_db('test');
//if show key is pressed show records
if($_POST['action'] == 'show'){
$sql = "select * from customer order by Firstname";
$query = mysql_query($sql);
echo "<table><tr><th>Firstname</th><th>Lastname</th><th>Keynumber</th>
<th>Number2</th><th>Number3</th><th>Option</th><th><button class='del' >delete</button></th></tr>";
while($row = mysql_fetch_array($query)){
echo "<tr><td>$row[firstname]</td><td>$row[lastname]</td><td class='key'>$row[keynumber]</td>
<td>$row[number2]</td><td>$row[number3]</td><td><button class='del' >delete</button></td></tr>";
}
echo "</table>";
}
?>
When I press the 'delete' button, it doesn't work.
I don't know why it doesn't work:(
It looks like your data is loaded dynamically when the show button is clicked. If so, you need to use .on() instead of .click(), and .on()'s delegated event syntax. Change your delete button code to:
$(document).on('click', '.del', function(){
$(this).parent().parent().fadeOut('slow');
});
I have corrected ur code just check it,
<script type="text/javascript">
$(document).ready(function(){
$('.del').click(function(){
$(this).parent().parent().fadeOut('slow');
});
$('#show').click(function(){
$.post(
url:'data.php',
data:{action: "show"},
type:'POST',
function(res){
$('#result').hide().html(res).fadeIn('slow');
});
});
});
</script>

Categories