How to update rows in jQuery with PHP and HTML - php

My PHP script generates a table with rows which can optionaly be edited or deleted. There is also a possibilety to create a new Row.
I am having a hard time to figure out how to update the HTML rows which are generated through PHP and inserted via jQuery. After the update it must be still editable. The HTML is generated into a div.
jQuery (insert generated HTML/wait for action)
PHP (generate html)
Go back to step 1)
(EDIT: Corrected an error and changed script to answer)
PHP
require_once "../../includes/constants.php";
// Connect to the database as necessary
$dbh = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die("Unaable to connnect to MySQL");
$selected = mysql_select_db(DB_NAME, $dbh) or die("Could not select printerweb");
$action = $_POST['action'];
$name = $_POST['name'];
$id = $_POST['id'];
if ($action == "new") {
mysql_query("INSERT INTO place (id, name) VALUES (NULL, $name)");
}
elseif ($action == "edit") {
mysql_query("UPDATE place SET name = $name WHERE id = $id");
}
elseif ($action == "delete") {
mysql_query("DELETE FROM place WHERE id = $id");
}
echo "<table><tbody>";
$result = mysql_query("SELECT * FROM place");
while ($row = mysql_fetch_array($result)) {
echo "<tr><td id=" . $row["id"] . " class=inputfield_td><input class=inputfield_place type=text value=" . $row["name"] . " /></td><td class=place_name>" . $row["name"] . "</td><td class=edit>edit</td><td class=cancel>cancel</td><td class=delete>delete</td><td class=save>SAVE</td></tr> \n";
}
echo "</tbody>";
echo "</table>";
echo "<input type=text class=inputfield_visible />";
echo "<button class=new>Neu</button>";
JS
$(function() {
$.ajax({
url: "place/place_list.php",
cache: false,
success: function(html) {
$("#place_container").append(html);
}
});
$(".edit").live("click", function() {
$(this).css("display", "none").prevAll(".place_name").css("display", "none").prevAll(".inputfield_td").css("display", "block").nextAll(".cancel").css("display", "block").nextAll(".save").css("display", "block").prevAll(".inputfield_td").css("display", "block");
});
$(".cancel").live("click", function() {
$(this).css("display", "none").prevAll(".edit").css("display", "block").prevAll(".place_name").css("display", "block").prevAll(".inputfield_td").css("display", "none").nextAll(".save").css("display", "none");
});
$(".save").live("click", function() {
var myvariable1 = $(this).siblings().find("input[type=text]").val();
var myvariable2 = $(this).prevAll("td:last").attr("id");
$(this).css("display", "none").prevAll(".cancel").css("display", "none").prevAll(".edit").css("display", "block").prevAll(".place_name").css("display", "block").prevAll(".inputfield_td").css("display", "none");
alert("save name: " + myvariable1 + " save id: " + myvariable2);
});
$(".delete").live("click", function() {
var myvariable3 = $(this).prevAll("td:last").attr("id");
alert(myvariable3);
});
$(".new").live("click", function() {
var myvariable4 = $(this).prevAll("input[type=text]").val();
$.post("place/place_list.php", {
action: "new",
name: "" + myvariable4 + ""
});
});
});

place all your event-handlers outside the ajax function and use the live() method instead. And you need to include what data to send when using ajax. From visualjquery:
$(function() {
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
$(".edit").live("click", function() {
//event handler code here
});
//more event handlers
});

I think you are not getting click events for editing, deleting etc. after new rows from php are appended to the div.
Try using jquery live plugin to bind click events as and when new stuff is created. Please refer to this question dealing with similar problem.

Like peirix and TheVillageIdiot pointed out, the live plugin maybe useful. However, there are some other things you may got wrong in your code:
First, your HTML isn't valid. You have to put quotes around attribut values. You could do this within quotes by escaping inner quotes with a backslash:
echo "<input type=\"text\" class=\"inputfield_visible\" />";
since this looks not that nice, you could leave the PHP part and write pure HTML if you change this:
<?php
...
echo "</tbody>";
echo "</table>";
echo "<input type=text class=inputfield_visible />";
echo "<button class=new>Neu</button>";
?>
To that (IMHO by far more readable):
<?php
...
?>
</tbody>
</table>
<input type="text" class="inputfield_visible" />
<button class="new">Neu</button>
Secondly, and that seems to be even more important, it looks to me like you have a SQLInjection vulnerability, because you pass the field values directly to mysql without using mysql_real_escape_string first. I'm not that into PHP, so maybe I got that wrong, but what happens if you enter ';-- into you input fields?

Related

How do we pass data in ajax? [duplicate]

This question already has answers here:
How can I get the data-id attribute?
(16 answers)
Closed 5 years ago.
I am new to Ajax and I am confused as to how we pass data in Ajax. I have an index.php file which displays some data, it has a link to delete the record, now the problem is, I am not able to figure out how to transfer the id value from index.php of the selected record to ajax file. Also, how should I go about once I have fetched the value in delete.php page where lies the code to delete records.
I have coded as below.
index.php
<div id="delMsg"></div>
<?php
$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"select * from member");
$col=mysqli_num_fields($data);
echo "<table>";
while($row=mysqli_fetch_array($data))
{
echo "<tr>";
for($i=0;$i<$col;$i++)
{
echo "<td>".$row[$i]."</td>";
}
echo "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";
echo"</tr>";
}
echo "</table>";
?>
ajax-file.js
$(document).ready(function(){
$(".del").click(function(event){
event.preventDefault();
$.ajax({
url:"delete.php",
method:"get",
data:{id:'ID'},
dataType:"html",
success:function(str){
$('#delMsg').html(str);
}
})
})
})
delete.php
<?php
$id=$_GET['id'];
$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"delete from member where id='$id'");
if($data)
{
echo "success";
}
else
{
echo "error";
}
?>
Hopefully this conveys the idea of how an AJAX call works.
The first thing we want to do is setup our trigger, which in your case is a button with an onclick event.
<script
src="http://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<!-- <button id="delete">Delete Something</button> -->
<button id="delete" onclick="onClickHandler(5)">Delete Something</button>
<p id="message">AJAX</p>
<script>
/* Notice I removed the document ready */
function onClickHandler(id)
{
event.preventDefault();
$.ajax(
{
url:"delete.php",
method:"POST", /* In the real world you want to use a delete here */
data: { /* plugin your data */
id: id,
name: "Bob",
age: 25
},
dataType:"html",
success: function(success) {
// Handle the success message here!
if (success) {
$('#message').text("Your message was received!");
}
},
error: function(error) {
// Handle your errors here
$('#message').text("Something went wrong!");
}
});
};
</script>
Notice how my data is prepared in the data object. I leave it up to you to figure out how to grab data and set it in the right field. You could: $('#someId').value(); or pass it through a function. If this is a source of confusion I can clarify.
data: { /* plugin your data */
id: 1,
name: "Bob",
age: 25
},
Next, we need to setup our script.
delete.php
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Obviously validate the data.
// But this is how you access it.
// $_POST is a global array, so you can access it like so:
$id = $_POST['id'];
$name = $_POST['name'];
$age = $_POST['age'];
// Do your server side stuff...
$sql = "DELETE FROM member
WHERE id = '{$id}' AND name = '{$name}' AND age = '{$age}'";
// Do your SQL (delete) here
// $con = mysqli_connect("localhost","root","","ajaxtest");
// Use prepared statements http://bobby-tables.com/php
// $data = mysqli_query($con,"delete from member where id='$id'");
// if ($data) { // Your condition
// This is where you would check if the query passed
// and send back the appropriate message.
if ($id) {
echo json_encode($id);
}
else {
echo http_response_code(500);
}
}
else {
echo "You don't belong here!";
}
you should use what is called JSON ( Javascript Object Notation, I think). This will let you order your data better to do that you have to use, json_encode.
Now I am not exactly sure what you mean by this id value from index.php
But taking your index.php file, I would change it like this
//make sure the is no space here
<?php
//start output buffering
ob_start();
$html = ['<div id="delMsg"></div>'];
$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"select * from member");
$col=mysqli_num_fields($data);
$html[] = "<table>";
while($row=mysqli_fetch_array($data))
{
$html[] = "<tr>";
for($i=0;$i<$col;$i++)
{
$html[] = "<td>".$row[$i]."</td>";
}
$html[] = "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";
$html[] = "</tr>";
}
$html[] = "</table>";
$result = [
'html' => implode("\n", $html),
'debug' => ob_get_clean()
];
header("Content-type:application/json");
echo json_encode($result);
//?> ending tags are undesirable
Your JavaScript part will change too
$(document).ready(function(){
$(".del").click(function(event){
event.preventDefault();
$.ajax({
url:"delete.php",
method:"get",
data:{id:'ID'},
dataType:"html",
success:function(data){
$('#delMsg').html(data.html);
}
})
})
})
You can see now that instead of just returning HTML, We will be returning it like this data in the Javascript and $result in php
{
html : '<div id=" ...',
debug : ""
}
I added ob_start and ob_get_clean this can be helpful because you cannot just echo content when outputting JSON, so this will catch any echo or print_r type content and put that into the debug item in the return.
Just replace
echo "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";
To
echo "<td><a onclick="deleteRow($row[0])">Delete</a></td>";
Javascript
function deleteRow(recordID)
{
event.preventDefault();
$.ajax({
type: "GET",
url: "delete.php",
data:{id: recordID}
}).done(function( result ) {
alert(result);
});
}
In your PHP I recommend you to use PDO which is more easy and protected from SQL injection attacks.
PHP:
$db = new PDO('mysql:host=localhost;dbname=yourDB','root','');
$query = $db->prepare("Delete From yourTableName Where ID=:ID");
$id=$_GET['id'];
$query->bindParam('ID', $id);
$query->execute();
if ($query->rowCount()) {
echo "success";
}
else
{
echo "fails";
}

jquery ajax request fails

I'm new to web programming and I'm trying to select value for a selector box based on value selected in another selector box. Below is the jquery code snippet and php script for your reference. thanks for the help in advance.
jquery-ajax code
$(function(){
$("#tier").change(function(){
var formdata = {'tierval':document.getElementById("tier").value};
alert("Selected Tier : "+document.getElementById("tier").value);
$.ajax({
type: "POST",
url: "/includes/getplayers.php",
data: formdata,
success: function(data)
{
alert("called getplayers.php");
$("#opp").empty();
$("#opp").html(data);
},
error:function()
{
alert('ajax failed');
}
});
});
});
php script:
<?php
if (isset($_POST['tierval']))
{
$tier = $_POST['tierval'];
}
$query = "select PlayerID,First_Name from GOFTEL.PLAYER where TierID = $tier";
$result = mysqli_query($pconn, $query);
$row = mysqli_fetch_assoc($result);
while($row)
{
echo '<option value=\"$row[PlayerID]\" > $row[First_Name] </option>';
}
/* free result set */
$result->free();
/* close connection */
$pconn->close();
?>
Since you are already using jQuery consider the below:
var formdata = {'tierval':$("#tier").val};
alert("Selected Tier : "+$("#tier").val);
// or
console.log(formdata); // using the browser console
// or
alert( this.value );
// or
console.log($(this).val())
then you need to output something in the php script, so that #opp actually gets populated with the result, so
$query="select PlayerID,First_Name from GOFTEL.PLAYER where TierID = $tier";
$result=mysqli_query($pconn, $query);
$row=mysqli_fetch_assoc($result);
print $row['First_Name'];
Then evaluate what you get in the console or alerts and go from there.
You need to use below code in php script
while($row=mysqli_fetch_assoc($result)){
echo "<option value=" . $row[PlayerID]. ">" . $row[First_Name] . "</option>";
}

Inserting data into mysql using jquery yes or no vote

How can i update the database by adding users choices? I have two fields in the database for this purpose, when the user click on yes, it updates the (useful) field and (not_useful) if clicked on no button. I am very new on javascript, so please be patient! :) I appreciate any help in advance.
PHP
<?php
require 'db/conn.php':
$id = (int)$_GET['id'];
if($result = $db->query("SELECT * FROM table_user WHERE table_user_id = $id")){
if($result->num_rows){
while($row = $result->fetch_assoc()) {
echo "
<div class='rating'>
<center>
<p>Are you alrite " . $row['table_user_name'] . "?</p>
<div>
<button type='button' id='yes'>Yes</button>
<button type='button' id='no'>No</button>
</div>
</center>
</div>
<div class='1' style='display:none;'>Text YES</div>
<div class='2' style='display:none;'>Text NO</div>
";
}
}
}
?>
JS
$(document).ready(function(){
$("#yes").click(function(){
$(".rating").hide();
$(".1").show();
});
$("#no").click(function(){
$(".rating").hide();
$(".2").show();
});
});
You can't connect your mySQL database directly with JavaScript from client browser. Event if it would be possible you really don't want to do that because you would have to include mysql login credentials into your JavaScript which is served to client computers.
Of course you could use database like LocalStorage from within JavaScript but these databases are on client computer. If I got it right thats not what you are looking.
You have to send the data to a script on your server which then insert them into your mySQL database. As you stated you don't like the browser to reload to just submitting a form is not an option. In these cases AJAX is used. You will find several tutorials how to send data with JavaScript / JQuery using AJAX to your server.
On server side you could handle for example with a php script. The code you have posted to your question is not PHP but simple HTML. Fred -ii- posted some sample SQL statements to increment a column. I would recommend you to use PHP PDO with mysql driver as this helps you to prevent security issues.
After some working hard, i found a solution. Sharing for those who is facing similar problem. This was my solution. Anyways, have fun! ;)
I think there's a better way to organize the JS script to interact with the php files which manage the sql scripts. If someone would like to help optimize it, will be welcome.
PHP main
<?php
require 'db/conn.php':
$id = (int)$_GET['id'];
if($result = $db->query("SELECT * FROM table WHERE user_id = $id")){
if($result->num_rows){
while($row = $result->fetch_assoc()) {
echo "
<div class='rating'>
<center>
<p>Are you alrite " . $row['user_name'] . "?</p>
<div id='rating-div'>
<a href='#' id='yes' class='custom-btn'>Yes</a>
<a href='#' id='no' class='custom-btn'>No</a>
<input type='hidden' id='" . $id . "' />
</div>
</center>
</div>
";
}
}
}
?>
JS
$(function(){
$('#yes').on('click', function(e){
e.preventDefault();
var usr_id = $('#rating-div input').attr('id');
$.ajax({
url: 'db/rating-yes.php',
type: 'post',
data: {'action': 'rating', 'usr_id': user_id},
success: function(data, status){
if(data == "ok"){
$('.rating').html('<p>Nice!</p>');
}//end of if
},//end of success function
error: function(xhr, desc, err){
console.log(xhr);
console.log("Details: " + desc + "\nError: "+ err);
}
});//end of ajax
}); //end of onclick function
}); //end of main function
$(function(){
$('#no').on('click', function(e){
e.preventDefault();
var usr_id = $('#rating-div input').attr('id');
$.ajax({
url: 'db/rating-no.php',
type: 'post',
data: {'action': 'rating', 'usr_id': user_id},
success: function(data, status){
if(data == "ok"){
$('.rating').html('<p>Oh no! :(</p>');
}//end of if
},//end of success function
error: function(xhr, desc, err){
console.log(xhr);
console.log("Details: " + desc + "\nError: "+ err);
}
});//end of ajax
}); //end of onclick function
}); //end of main function
PHP rating-yes
<?php
$rating = $_POST['action'];
$user_id = $_POST['usr_id'];
if($rating == "rating") {
$conn = mysql_connect('localhost', 'root', '');
$db = mysql_select_db('your_database');
if(mysql_query("UPDATE table SET useful = useful + 1 WHERE user_id = $user_id")){
echo "ok";
}
}
?>
PHP rating-no
<?php
$rating = $_POST['action'];
$user_id = $_POST['usr_id'];
if($rating == "rating") {
$conn = mysql_connect('localhost', 'root', '');
$db = mysql_select_db('your_database');
if(mysql_query("UPDATE table SET not_useful = not_useful + 1 WHERE user_id = $user_id")){
echo "ok";
}
}
?>

jquery: ajax request not working

I am getting no responses when I try to fire this ajax request from jquery:
/********************************
CHANGE USER SETTINGS
*********************************/
$(".submitUserSetting").live('click', function() {
//get values
var department = $("#us_department").val();
var sortOrder = $("input[#name=us_sortOrder]:checked").val();
$.ajax({
type: "POST",
url: "lib/includes/updateUserSettings.php",
data: "empname=" + empname + "&department=" + department + "&sortOrder=" + sortOrder,
success: function(data) {
alert(data);
}
});
});
I mean nothing. No javascript errors, no errors on the MySQL query, not even POST data in the console.log. Just a taunting batch o' silence. Even if I comment out all the code in the PHP page and just echo the data I sent over to it, nothing. Here's the PHP page (the class exists, the functions work, I'm using them on a dozen or so other pages)
<?php
require_once("../classes/mysqlconnect.php");
$db = new dbconnect();
$db->makeConnections("TimeSheetManager");
$empname = $_POST['empname'];
$department = $_POST['department'];
$sortOrder = $_POST['sortOrder'];
//get the department id
$dQuery = "SELECT id FROM departments WHERE department = '" . $department . "'";
$dResults = $db->getResults($query);
if (mysql_num_rows($dResults) > 0) {
while($rows = mysql_fetch_array($dResults) {
$deptID = $rows['id'];
}
}
//update database
$query = "UPDATE users SET `department` = '" . $department "', `displayOrder` = '" . $sortOrder . "' WHERE username = '" . $empname . "'";
$results = $db->getResults($query);
if ($results) {
echo "!success";
} else {
echo "!fail";
}
?>
Here's the form code:
<div id="userSettingsForm">
<form name="userSetting">
<p><label for="sortOrder">Display Order:</label></p>
<p class="userSettingElement">Oldest First <input type="radio" name="us_sortOrder" value="asc"> Newest First <input type="radio" name="us_sortOrder" value="dsc"></p>
<p><label for="us_department">Department:</label></p>
<p class="userSettingElement">
<select id="us_department" name="us_department">
<option value="null">Select A Department</option>
<?php
$query = "SELECT * FROM departments";
$results = $db->getResults($query);
while($row = mysql_fetch_array($results)){
if (count($results) > 0) {
//get department and id
$department = $row['department'];
$deptID = $row['id'];
print "<option value=\"" . $deptID . "\">" . $department . "</option>";
}
}
?>
</select>
</p>
<p>Submit</p>
</form>
</div>
Thanks for all the help and suggestions. I rebooted Firefox and the error was in empname, I wasn't setting it (doh!). Beluga was on to that but it took a bit for it to dawn on me. Wish I could award everyone with the answer.
How can you tell you're not getting an error? Add an error handler to your .ajax() call:
$.ajax({
type: "POST",
url: "lib/includes/updateUserSettings.php",
data: "empname=" + empname + "&department=" + department + "&sortOrder=" + sortOrder,
success: function(data) {
alert(data);
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
OK, some more investigation shows that the error is actually in a peculiar combination of pieces of code that you are using.
Apparently, href="javascript:void(0)" prevents event propagation. The event is triggered on the element itself (so handlers bound with .click(fn) work) but ancestor elements are not notified of the event.
Since you are using the .live() method, which relies upon event propagation, this doesn't work here.
I would suggest the following instead:
Submit
and JS:
$(".submitUserSetting").live('click', function(e) {
e.preventDefault(); // disable the link action
[snip]
});
See jsFiddle demonstrating this.
The issue is the way you send the data.
Try enclosing the property in { } 's and changing the variable format to
{ "propertyName" : "value", "propertyName" : "value" }
i.e
data: { "empname" : empname ,"department" : department, "sortOrder" :sortOrder }
alternatively if it is a form you can even say
data : { $("#form").serialize() }
you need to return some value in your php function
data: "empname=" + empname + "&department=" + department + "&sortOrder=" + sortOrder,
define empname in your call which is missing.
this gives you Uncaught ReferenceError

Table doesn't respond to second jQuery request

My PHP script generates a table with rows which can optionally be edited or deleted. There is also a possibility to create a new Row. The PHP is activated through jQuery Events.
Now all works well, I can edit delete and create an Item. After each action which makes use of the PHP script the HTML table gets updated.
But when I try after an Event to do an action again the HTML Table doesn't get updated though in the background the PHP script makes an entry into the database.
Does someone of you know why my HTML Table doesn't update itself when I trigger a second event?
Here is the Script:
PHP
<?php
require_once "../../includes/constants.php";
// Connect to the database as necessary
$dbh = mysql_connect(DB_SERVER,DB_USER,DB_PASSWORD)
or die ("Unaable to connnect to MySQL");
$selected = mysql_select_db(DB_NAME,$dbh)
or die("Could not select printerweb");
$action = $_POST['action'];
$name = $_POST['name'];
$id = $_POST['id'];
if($action == "new")
{
mysql_query("INSERT INTO `place` (`id`, `name`) VALUES (NULL, '$name')");
}
elseif($action == "edit")
{
mysql_query("UPDATE `place` SET `name` = '$name' WHERE `id` = '$id'");
}
elseif($action == "delete")
{
mysql_query("DELETE FROM place WHERE id = '$id'");
}
echo "<table><tbody>";
$result = mysql_query("SELECT * FROM place");
while ($row = mysql_fetch_array($result)) {
echo "<tr><td id=".$row["id"]." class=inputfield_td><input class=inputfield_place type=text value=".$row["name"]." /></td><td class=place_name>".$row["name"]."</td><td class=edit>edit</td><td class=cancel>cancel</td><td class=delete>delete</td><td class=save>SAVE</td></tr> \n";
}
echo "</tbody>";
echo "</table>";
echo "<input type=text class=inputfield_visible />";
echo "<button class=new>Neu</button>";
?>
JS
$(function() {
$.ajax({
url: "place/place_list.php",
cache: false,
success: function (html){
$("#place_container").append(html);
}
});
$(".edit").live("click", function() {
$(this).css("display","none").prevAll(".place_name").css("display","none").prevAll(".inputfield_td").css("display","block").nextAll(".cancel").css("display","block").nextAll(".save").css("display","block").prevAll(".inputfield_td").css("display","block");
});
$(".cancel").live("click", function() {
myvariable5 = $(this).prevAll(".place_name").html();
$(this).css("display","none").prevAll(".edit").css("display","block").prevAll(".place_name").css("display","block").prevAll(".inputfield_td").css("display","none").nextAll(".save").css("display","none").siblings().find("input[type=text]").val(myvariable5);
});
$(".save").live("click", function() {
var myvariable1 = $(this).siblings().find("input[type=text]").val();
var myvariable2 = $(this).prevAll("td:last").attr("id");
$(this).css("display","none").prevAll(".cancel").css("display","none").prevAll(".edit").css("display","block").prevAll(".place_name").css("display","block").prevAll(".inputfield_td").css("display","none");
$.post("place/place_list.php", {action: "edit", name: ""+myvariable1+"", id: ""+myvariable2+""}, function (html){$("#place_container").replaceWith(html);});
});
$(".delete").live("click", function() {
var myvariable3 = $(this).prevAll("td:last").attr("id");
$.post("place/place_list.php", {action: "delete", id: ""+myvariable3+""}, function (html){$("#place_container").replaceWith(html);});
});
$(".new").live("click", function() {
var myvariable4 = $(this).prevAll("input[type=text]").val();
$.post("place/place_list.php", {action: "new", name: ""+myvariable4+""}, function (html){$("#place_container").replaceWith(html);});
});
});
I think I know. You do replaceWith instead of append, so your DIV with ID #place_container disappears after the first operation (you are left with only a table in your page), and of course jQuery does not find it and is unable to refresh it with new content from the second operation.
Just use append or, better yet, html methods.
Shouldnt you replace the complete table ?
$("#place_container").html(html);

Categories