Partial Update a list with AJAX - javascript

I have a list from the database and I want to implement edit functionality where in onclicking a table column, the column becomes editable and on clicking out of column, the value gets updated.
I have used AJAX for this purpose. My code is as under:
Page1.php
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function showEdit(editableObj)
{
$(editableObj).css("background","#FFF");
}
function saveToDB(editableObj,column,id)
{
$.ajax(
{
url: "page2.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data)
{
$(editableObj).css("background","#FDFDFD");
}
});
}
</script>
The column of my table is as under:
<td contenteditable="true" onBlur="saveToDB(this, 'exmid','<?php echo $p0; ?>')"
onClick="showEdit(this);"><?php echo $p3 ?>
Note: $p0 contains the serial no of row from mysql database table and $p3 contains the displayed text.
The code for page2.php is:
<?php
include_once 'includes/db_connect.php';
?>
<?php
$result = mysql_query("UPDATE examlist1 set " . $_POST["column"] . " = '".$_POST["editval"]."' WHERE sno=".$_POST["id"]);
?>
Problem:
When I click on the column it becomes editable. Using alert() inside saveToDB() I have checked that the function is called on clicking out of the column and also values of column and id are correct.
Then I tried the alert() function inside $.ajax and it was not called. I am not sure whether ajax is running or not. This is the first time I am trying to use ajax in a php code myself.
Please suggest what is the problem and what is the solution? The code is being implemented on a Linux based server hosted at Godaddy using PHP 5.4.
Also I would like to set the background color on fail. How to write it inside ajax block?

If you are getting the correct values when alerting.In your page2.php. Use mysqli instead of mysql and also use $connection object in mysqli_query().
<?php
include_once 'includes/db_connect.php';
$column=$_POST["column"];
$editval=$_POST["editval"];
$id=$_POST["id"];
$result = mysqli_query($connection,"UPDATE examlist1 SET $column='$editval' WHERE sno=$id");//$connection is database connection variable
if ($result)
{
echo json_encode(array('success'=>true));
}
else
{
echo json_encode(array('success'=>false));
}
?>
Here is Javascript: Try 100% works (Define what you want on if/else statement)
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function showEdit(editableObj)
{
$(editableObj).css("background","#FFF");
}
function saveToDB(editableObj,column,id)
{
$.ajax(
{
url: "page2.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data)
{
var res=eval(data);
//if success then
if (res.success)
{
//write JS code that you want after successful updation
$(editableObj).css("background","#FDFDFD"); //<- according to problem
}
//if fails then
else
{
//write JS code that you want after unsuccess
}
}
});
}
</script>

Related

Update MYSQL Table On Div Click using Ajax - No Page Refresh?

I have a MYSQL Table called users.
I also have a column called online_status.
On my page I want a user to be able to toggle their status as 'Online' or 'Offline' and have this updated in the database when they click on the div using Ajax, without refreshing the page.
Here's my PHP/HTML code:
<?php if ($profile['online_status'] == "Online") {
$status = "Offline";
}else{
$status = "Online";
} ?>
<div id="one"><li class="far fa-circle" onClick="UpdateRecord(<? echo $profile['online_status']; ?>);"/></li><? echo 'Show as ' .$status; ?></div>
My Ajax:
<script type="text/javascript" src="/js/jquery.js"></script>
<script>
function UpdateRecord(id)
{
jQuery.ajax({
type: "POST",
url: "update_status.php",
data: 'id='+id,
cache: false,
success: function(response)
{
alert("Record successfully updated");
}
});
}
</script>
update_status.php
<?php
$var = #$_POST['id'] ;
$sql = "UPDATE users SET online_status = 'Offline' WHERE user_id = 1";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
//added for testing
echo 'var = '.$var;
?>
I am currently getting no alert, nothing is being updated in my database either. Please can someone help me improve/fix the code to get it to work? Also, if there's a way of eradicating the need for the update_status.php file and have the ajax self post then this would be preferred.
Thank you in advance.
From what i see, the reason why no alert pops up nor nothing gets updated is because of the onclick() on button you have. Add quotes around the parameter to the update function. As you have it, javascript sees the parameter as a javascript variable as $profile['online_status']; is a string.
If you had debugged your code, you should see an error pointing towards the onclick() line
Change this
onClick="UpdateRecord(<? echo $profile['online_status']; ?>);"
To
onClick="UpdateRecord('<? echo $profile['online_status']; ?>');"
Also you are hardcoding the where clause in your update statement. You should be using the $_POST['id'] variable via prepared statements
pass data to PHP file
data: { id: id },
add a database connection to your PHP file
<?php
$var = $_POST['id'] ;
$sql = "UPDATE users SET online_status = 'Offline' WHERE user_id = '$var'";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
?>
If you still see any errors then press F12 and go to network tab, then click on that div, network tab will record your ajax file returns, you can check there on by selecting your php file's response, hope it helps

editableSelect() does not fire after ajax method

I have an ajax method that runs as soon as the page is loaded without listening to any event. The ajax fetches student ID from the database and shows the student ID in a select box. I want the select box to be editable (http://indrimuska.github.io/jquery-editable-select/). The function $('#studentID').editableSelect(); runs completely fine when the options are hardcoded in the select tag. However, no data is shown in the selectbox when $('#studentID').editableSelect(); is called and the data is fetched from the database.
Here is the code that is written in the JavaScript file
$('#studentID').editableSelect();
$.ajax({
type:'POST',
url:'./public/api/studentID.php',
success:function(html){
$('#studentID').html(html);
}
});
#studentID definition
<label for="studentID">ID</label>
<select id = "studentID" class="form-control">
</select>
php code
<?php
$connection = new mysqli ("127.0.0.1", "root", "", "test");
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$query = "SELECT `SID` FROM `student` ORDER BY `SID` ";
$result1= mysqli_query($connection, $query);
while($row1 = mysqli_fetch_array($result1)):;?>
<option value="<?php echo $row1[0];?>"><?php echo $row1[0];?></option>
<?php endwhile;
$connection->close();
?>
Any help will be appreciated.
Move the editableSelect into the ajax.success method. The problem is that you are initializeing an empty select element, and then inserting it the options with the asynchronous ajax method. The success will forever happen after the data will successfully loaded, and then you can initialize the select with any framework/library, including editableSelect that you want to.
$.ajax({
type:'POST',
url:'./public/api/studentID.php',
success:function(html){
let student_el = $('#studentID');
student_el.html(html);
student_el.editableSelect();
}
});
EDIT:
you might not included the library in the right way, so for any case, here is the two ways to include it:
Inside the head tag
<head>
<!--Include jQuery + you libraries...-->
<script src="https://rawgit.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js"></script>
<link href="https://rawgit.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.css" rel="stylesheet" />
</head>
Inside the ajax call
$.ajax({
type: 'POST',
url: './public/api/studentID.php',
success: function(html){
let student_el = $('#studentID');
student_el.html(html);
$.getScript("https://rawgit.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js")
.then(() => {
student_el.editableSelect(); // Call this function after the script have been successfully loaded.
});
//student_el.editableSelect();
}
});
Why don't you try calling editableSelect on your callback
$.ajax({
type:'POST',
url:'./public/api/studentID.php',
success:function(html){
$('#studentID').html(html);
$('#studentID').editableSelect();
}
});

How can I send javascript values to PHP script?

this is my php code that creates a table using the results of a mysql query:
echo "<table id='table' class='selectQuery'>
while($row = mysqli_fetch_array($slctQuery)) {
// ; echo $row['id']; echo
echo "<tr class='someClass' idNumber="; echo $row['id']; echo ">
<td>";
echo $row['fname'];
echo "</td>
<td>";
echo $row['lname'];
echo "</td>;
</tr>";
}
echo "</table>";
and this part is my jquery code for changing style on click on table row:
<script>
$(document).ready(function(){
$("#table tr").click(function(){
$('.someClass').removeClass('selected');
$(this).addClass('selected');
idNum = $(this).attr('idNumber');
});
$("#table tr").click(function(){
$("#DelEdtQuestion").addClass('selected1');
});
});
</script>
and this part is for style:
<style>
tr.selected {
background-color: brown !important;
color: #FFF;
}
</style>
and this is my php code for button
if(#$_POST['Search']){
/// what should I do?
}
So, now I want have my idNum value when my search button in form was clicked.
thanks for attentions
You can use ajax. If you have a form with id="myform" and (example) input fields: firstname, lastname, username and password, the following script should send data to the php:
$(document).ready(function(){
var datastring = $("#myform").serialize();
$.ajax({
type: 'POST',
url: 'ajaxfile.php',
data: datastring
}).done(function(res){
var res = $.trim(res);
alert(res);
});
});
The ajaxfile.php can be something like that:
<?php
$firstname = mysql_real_escape_string($_POST["firstname"]);
$lastname = mysql_real_escape_string($_POST["lastname"]);
$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string($_POST["password"]);
//here you have the variables ready to do anything you want with them...
//for example insert them in mysql database:
$ins = "INSERT INTO users (firstname, lastname, username, password ) VALUES ( '$firstname', '$lastname', '$username', '$password' )";
if(mysql_query($ins)){echo "SUCCESS";}else{echo "FAILURE";}
?>
Another example, similar to yours, is to take the row id from your table, pass it to ajax, have ajax (for example) make a query to the database and return the results:
// your script, modified for ajax:
$(document).ready(function(){
$("#table tr").click(function(){
$('.someClass').removeClass('selected');
$(this).addClass('selected');
var idNum = $(this).attr('idNumber'); //use "var" to -initially- set the variable
$.ajax({
type: 'POST',
url: 'ajaxfile.php',
data: 'id='+idNum
}).done(function(res){
var res = $.trim(res);
alert(res);
});
});
$("#table tr").click(function(){
$("#DelEdtQuestion").addClass('selected1');
});
});
Modified ajaxfile.php to suit the above example:
<?php
$id = mysql_real_escape_string($_POST["id"]);
//query database to get results:
$result = "SELECT * FROM `users` WHERE `id` = '$id' LIMIT 1";
$row = mysql_fetch_assoc($result);
echo "Username: ".$row["username"]."Password: ".$row["password"]."Firstname: ".$row["firstname"]."Lastname: ".$row["lastname"].
?>
Since your question was rather ambigious, I put more effort to give you an idea about the basics of ajax so that you work out your own solution, rather than to suggest a potential solution -that at the end could not be what you were looking for...
And since we are talking about ajax basics, it is a good practice to secure your ajax files since they are accessible from any browser:
in the very beginning of any ajax file, right below the "?php" tag, you can add these lines below, to protect the file from being accessed by browser -but remain accessible to ajax calls:
//protect the file from un-authorized access
define('AJAX_REQUEST', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!AJAX_REQUEST) {die();}
Hope that helps you and others. T.
UPDATE:
It is ALWAYS a good practice to keep your php and javascript files separately... In the above examples there are ideally 3 files involved: the main php file, the scripts file and the ajax-php file.
So -preferably after the "body" tag of your "main" php file- you should include the scripts-file (after the jquery ofcourse!). Like that:
<!-- jQuery v.1.11.3-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- include scripts file -->
<?php include("scripts.php"); ?>
(notice that for jquery I use the regular "script" tags but for the scripts file I just do a "php include").
As you see above, the javascript file has also ".php" extension (not ".js"). This is a "trick" I like to do because it gives me the ability to execute php code within the js file. Of course, all javascript code in that file is included between "script" tags.
example of a hypothetical "scripts.php":
<script>
// I create a js variable that takes value from php
var phpDate = '<?php date("Y-m-d"); ?>';
alert(phpDate);
//or pass the contents of another php variable in your app to javascript:
var myPhpVar = '<?php echo $my_php_var; ?>';
//or put a php SESSION to a js variable:
var mySess = '<?php echo $_SESSION["my_session"]; ?>';
</script>
The above comes quite handy sometimes when you want to pass to javascript php variables that already exist in your application.
It is a very long answer (more like a tutorial!)... But now should be quite clear to you how to pass values not only from js to php but also vice versa!!!

AJAX - Javascript array to php

I know that there are so many to find on the internet, however, I have been trying this for hours now, and still not working, Maybe the community could help me out:)
http://jsfiddle.net/dkk2nqyg/14/
I've got a little explanation in the jsfiddle, else, you can take a look in my previous question, JavaScript array splice
Basicly, I want the values from selected ( 3 picked up cards )
in php, because I want to mail those values;)
$.ajax({
url: 'data.php', //I actually want it to be on same page, trying this for debugging
type: 'post',
data: {data : selected},
success: function(data) {
alert("worked");
}
});
in the data.php :
<?php
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $d){
echo $d;
}
?>
I would like that I don't even need that data.php but just 1 page, so in the index.php, is that even possible?
Edit: Please, link a JsFiddle, would really help!
First the ajax request should be within the click handler
$('#mail').click(function () {
console.log($('#dvDest .flipper').get())
var selected = $('#dvDest .flipper').map(function () {
return $(this).data('src')
}).get();
alert(selected)
$.ajax({
url: 'data.php', //I actually want it to be on same page, trying this for debugging
type: 'post',
data: {
data: selected
},
success: function (data) {
alert("worked");
}
});
})
then in server side loop through the array like(Not sure about the PHP syntax)
<?php
foreach($_POST['data'] as $d){
echo $d;
}
?>
you can write a condition as if request object have post values then
$data = json_decode(stripslashes($_POST['data']));
foreach($data as $d){
echo $d;
}
else your homepage display code
So,index.php is enough
For using a single page, eg: index.php
at the top of index.php you do:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Your code goes here
exit();
}

AJAX PHP function onchange select box

I have a problem about which I am very confused. I have a select box with s dynamically generated using a mysqli query:
$result = mysqli_query($db, "SELECT * FROM `users` WHERE `user_id` > 0");
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
while($row = $result->fetch_assoc()){
echo '<option value = '.$row['user_name'].'>'.$row['user_name'] . '</option>';
}
echo '</select></form>';
I am completely new to AJAX, but I need to use jquery and ajax to pass the this.value variable to a php variable for use in a later query.
Here is my script (most of which was found online):
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
$("#contacts").change(function() {
//get the selected value
var selectedValue = this.value;
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});
</script>
Now, when I click a value in the select box, nothing happens. There are no warnings or errors, etc.
Please help me.
p.s. function.php does exist. It is just a simple echo for now (for testing purposes)
UPDATE: HERE IS FUNCION.PHP:
<?php
/*$val = $_REQUEST['selectedValue'];
echo $val;*/
function function(){
$val = $_REQUEST['selectedValue'];
echo $val;
}
?>
UPDATE: Thank you everyone for all your help. I have now got it to work in that the network section of chrome inspect shows the function.php being requested however I still don't get the echo (I used external .js files to get it to work). My J query function is also successful (the success function echoes into the console)
Your select box has no ID and you are watching the change event of $("#contacts").
Change:
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
to:
echo '<html><form name="contacts" method="post"><select name="contacts" id="contacts"><option value="Contact list">Contact List</option>';
^^^^^^^^^^^^^ here
You also only need one event handler, so I have removed the inline one which doesn't seem to do anything anyway.
Edit: If the select is created using ajax as well, you need event delegation:
$("body").on('change', '#contacts', function() {
^^^^ for example
Edit 2: Your variable is called $_REQUEST['option'] and not $_REQUEST['selectedValue']. You are also not calling your -badly named - function so you will not get any output from php except from an error like Parse error: syntax error, unexpected 'function' ....
Call onchange function in select tag as below
echo '<form name="contacts" method="post"><select name="contacts" onchange="func(this.value)"><option value="Contact list">Contact List</option></form>';
Javascript src should be in head of the html page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
Add the above one in head of html. Update javacript as below
As onchange function is called in the select tag itself, following is enough
<script>
function func(selectedValue)
{
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
}
</script>
Updated php: If you must want to get value from function, you must call it. Otherwise, simply, you can make as below
<?php
if($_REQUEST['option'])
{
$val=$_REQUEST['option'];
echo $val;
}
?>
In .php file, receive it first-
$val = $_REQUEST['selectedValue'];
echo $val;
set an id attribute in your php code for the select tag and
please don't use the same value for the name attribute in form and select tags !!
just change your function to a 'body'.on, and give your elements an id of 'contacts'
$("body").on('change', '#contacts', function() {
//get the selected value
var selectedValue = $(this).val();
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});

Categories