AJAX Post request working only on Web Console (Preview) - javascript

I have a really simple ajax request to "send" the ID of an element the user clicks on the webSite. The script is working only on the Web Console (in the Network -> Preview section). This happens in every browser.
here's the code:
AJAX REQUEST
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$('.point1, .point2, .point3, .point4, .point5, .point6, .point7').click(function(event) {
var itemid = event.target.id;
$.ajax({
type: 'post',
//url: "index.php",
data: {'itemid' : itemid},
cache : false,
async : true,
dataType: 'html',
success: function(data) {
alert('success');
},
failure: function(data) {
alert('failure');
}
});
});
</script>
PHP Function
<?php
if(isset($_POST['itemid'])){
$itemid = $_POST['itemid'];
echo "success";
$itemid = (int)$itemid;
echo $itemid;
} else{
echo "failure";}
?>
Can you help me with this?
Just adding the image to let you understand better.
UPDATED: Here's the full code, hope it's not too confusionary (still a beginner):
I'm getting the response correct but echo json_encode($d); is not printing.
Btw thank you very much for your support :)
<?php
$d = array();
if(isset($_POST['itemid'])){
if($_POST['itemid'] != ""){
$d['result'] = "success";
$d['itemid'] = (int)$_POST['itemid'];
} else{
$d['result'] = "error";
$d['error'] = "'itemid' was not set.";
}
header('Content-Type: application/json');
echo json_encode($d);
exit();
}
if ( !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'){
// La richiesta e' stata fatta su HTTPS
} else {
// Redirect su HTTPS
// eventuale distruzione sessione e cookie relativo
$redirect = 'https://' . $_SERVER['HTTP_HOST'] .
$_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $redirect);
exit();
}
?>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="../style.css" type="text/css">
<?php
setcookie('test', 1, time()+3600);
if(!isset($_GET['cookies'])){
include_once "../header.php";
include_once '../footer.php';
include_once '../right_column.php';
echo"<script type='text/javascript'></script>\r\n<noscript>JavaScript is off. Please enable to view full site.</noscript>";
} else {
echo "No Cookies";
}
?>
<div class="map">
<div class="point1" id="1"> </div>
<div class="point2" id="2"> </div>
<div class="point3" id="3"> </div>
<div class="point4" id="4"> </div>
<div class="point5" id="5"> </div>
<div class="point6" id="6"> </div>
<div class="point7" id="7"> </div>
</div>
<?php
$green='rgb(30,255,0)';
$yellow='rgb(255,255,0)';
$red='rgb(255,0,0)';
include '../includes/dbhinc.php';
for ($i = 1; $i <= 7; $i++) {
$sql="SELECT nummot, numbici FROM grid WHERE cellaid='$i'";
$result=mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$moto=$row["nummot"];
$bici=$row["numbici"];
$mezzi=$moto+$bici;
if($mezzi>=4){
$color=$green;
$sql="UPDATE `grid` SET `rgb`='rgb(30,255,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo "<script> document.getElementById('$i').style.backgroundColor ='rgb(30,255,0)' </script>";
} else if($mezzi<4 && $mezzi>0){
$color=$yellow;
$sql="UPDATE `grid` SET `rgb`='rgb(255,255,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo"<script> document.getElementById('$i').style.backgroundColor ='rgb(255,255,0)' </script>";
} else{
$color=$red;
$sql="UPDATE `grid` SET `rgb`='rgb(255,0,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo"<script> document.getElementById('$i').style.backgroundColor ='rgb(255,0,0)' </script>";
}
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(".point1, .point2, .point3, .point4, .point5, .point6, .point7").click(function(event) {
var itemid = $(this).attr("id");
$.ajax({
type: 'post',
url: "index.php",
data: {
'itemid': itemid
},
cache: false,
async: true,
dataType: 'json',
success: function(data) {
if(data.result == "success"){
console.log("Success", data.itemid);
} else {
console.log("Failed", data);
}
}
});
});
</script>
<?php
echo "<script type='text/javascript'>\r\n";
echo "$('.point1, .point2, .point3, .point4, .point5, .point6, .point7').click(function(event) {\r\n";
echo "\talert('itemid');\r\n";
echo "\tvar itemid = event.target.id;\r\n";
echo "});\r\n";
echo "</script>";
if(isset($_SESSION['id'])){
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 120)) {
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
header("Location: index.php");
}
$_SESSION['LAST_ACTIVITY'] = time();
echo "<script type='text/javascript'>\r\n";
echo " Inserisci qui il n°di Bici da prenotare <input type='number' id='bicidapren' method='post'> Inserisci qui il n°di Moto da prenotare <input type='number' id='motodapren' method='post'> <button id='tryit' onclick='myFunction()'>Confirm</button>";
echo "function myFunction() {\r\n";
echo "\tBicidaprenotare = parseInt(document.getElementById('bicidapren').value)-1;\r\n";
echo "\tMotodaprenotare = parseInt(document.getElementById('motodapren').value)-1;\r\n";
echo "}\r\n";
echo "</script>";
}
?>
</body>
</html>

Here is what can work for you. If it does not work then please share your entire code and the response from PHP too.
// jQuery AJAX call should be something like this
$.ajax({
url: 'index.php',
data: {
"itemid": itemid
},
type: "post",
dataType: "json",
success: function(json) {
if(json.success) {
alert("Item ID is " + json.itemid);
} else {
alert("Item ID is " + json.itemid);
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error :: " + textStatus + " :: " + errorThrown);
}
});
// PHP code can be like this
if(isset($_POST['itemid'])){
$itemid = $_POST['itemid'];
echo json_encode(['success' => true, 'itemid' => $itemid]);
} else {
echo json_encode(['success' => false, 'itemid' => 'Not available']);
}

Consider the following.
JavaScript
$("[class*='point']").click(function(e) {
var itemid = $(this).attr("id");
$.ajax({
type: 'post',
url: "index.php?",
data: {
'itemid': itemid
},
cache: false,
async: true,
dataType: 'json',
success: function(data) {
if(data.result == "success"){
console.log("Success", data.itemid);
} else {
console.log("Failed", data);
}
}
});
});
PHP
<?php
$d = array();
if(isset($_POST['itemid'])){
$d['result'] = "success";
$d['itemid'] = (int)$_POST['itemid'];
} else{
$d['result'] = "error";
$d['error'] = "'itemid' was not set.";
}
header('Content-Type: application/json');
echo json_encode($d);
?>
In a lot of cases, it's better to pass JSON data back. It's easier for JavaScript to handle it. So we build an array of data that we want to pass back to AJAX request and encode it as JSON.
When we make the AJAX Post, PHP will result in a Successful response. You're welcome to catch an error, this would happen with 400 or 500 Status result from the PHP call. You can also see this in your Web Console.
We're going to get a JSON Object back from PHP, either:
{
result: "success",
itemid: 2
}
Or:
{
result: "error",
error: "'itemid' was not set."
}
In JavaScript, we can use dot notation to access the elements of the object. You can also access it like this:
if(data['result'] == "success")
Dot notation is advised.
Update 1
In your PHP File, you will want a different structure. You're going to have to perform some actions before the HTML is presented to the Browser.
<?php
$d = array();
if(isset($_POST['itemid'])){
if($_POST['itemid'] != ""){
$itemid = (int)$_POST['itemid'];
} else{
$d['result'] = "error";
$d['error'] = "'itemid' was not set.";
}
$d;
// Connect to SQL
// Query DB for Table Data ...WHERE itemId = '$itemid'
// Store resultset to $d
header('Content-Type: application/json');
echo json_encode($d);
exit();
}
if ( !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'){
// La richiesta e' stata fatta su HTTPS
} else {
// Redirect su HTTPS
// eventuale distruzione sessione e cookie relativo
$redirect = 'https://' . $_SERVER['HTTP_HOST'] .
$_SERVER['REQUEST_URI'];
header('HTTP/1.1 301 Moved Permanently');
header('Location: ' . $redirect);
exit();
}
?>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="../style.css" type="text/css">
<?php
setcookie('test', 1, time()+3600);
if(!isset($_GET['cookies'])){
include_once "../header.php";
include_once "../grid.asp";
include_once '../footer.php';
include_once '../right_column.php';
echo"<script type='text/javascript'></script>\r\n<noscript>JavaScript is off. Please enable to view full site.</noscript>";
} else {
echo "No Cookies";
}
?>
<div class="map">
<div class="point1" id="1"> </div>
<div class="point2" id="2"> </div>
<div class="point3" id="3"> </div>
<div class="point4" id="4"> </div>
<div class="point5" id="5"> </div>
<div class="point6" id="6"> </div>
<div class="point7" id="7"> </div>
</div>
<?php
$green='rgb(30,255,0)';
$yellow='rgb(255,255,0)';
$red='rgb(255,0,0)';
include 'includes/dbhinc.php';
for ($i = 1; $i <= 7; $i++) {
$sql="SELECT nummot, numbici FROM grid WHERE cellaid='$i'";
$result=mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$moto=$row["nummot"];
$bici=$row["numbici"];
$mezzi=$moto+$bici;
if($mezzi>=4){
$color=$green;
$sql="UPDATE `grid` SET `rgb`='rgb(30,255,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo "<script> document.getElementById('$i').style.backgroundColor ='rgb(30,255,0)' </script>";
} else if($mezzi<4 && $mezzi>0){
$color=$yellow;
$sql="UPDATE `grid` SET `rgb`='rgb(255,255,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo"<script> document.getElementById('$i').style.backgroundColor ='rgb(255,255,0)' </script>";
} else{
$color=$red;
$sql="UPDATE `grid` SET `rgb`='rgb(255,0,0)' WHERE cellaid = $i";
mysqli_query($conn, $sql);
echo"<script> document.getElementById('$i').style.backgroundColor ='rgb(255,0,0)' </script>";
}
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(".point1, .point2, .point3, .point4, .point5, .point6, .point7").click(function(event) {
var itemid = $(this).attr("id");
$.ajax({
type: 'post',
url: "index.php?",
data: {
'itemid': itemid
},
cache: false,
async: true,
dataType: 'json',
success: function(data) {
if(data.result == "success"){
console.log("Success", data.itemid);
} else {
console.log("Failed", data);
}
}
});
});
</script>
<?php
if(isset($_SESSION['id'])){
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 120)) {
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
header("Location: index.php");
}
$_SESSION['LAST_ACTIVITY'] = time();
echo " Inserisci qui il n°di Bici da prenotare <input type='number' id='bicidapren' method='post'> Inserisci qui il n°di Moto da prenotare <input type='number' id='motodapren' method='post'> <button id='tryit' onclick='myFunction()'>Confirm</button>";
echo "<script type='text/javascript'>\r\n";
echo "$('.point1, .point2, .point3, .point4, .point5, .point6, .point7').click(function(event) {\r\n";
echo "\talert('itemid');\r\n"
echo "\tvar itemid = event.target.id;\r\n";
echo "});\r\n";
echo "function myFunction() {\r\n";
echo "\tBicidaprenotare = parseInt(document.getElementById('bicidapren').value)-1;\r\n";
echo "\tMotodaprenotare = parseInt(document.getElementById('motodapren').value)-1;\r\n";
echo "}\r\n";
echo "</script>";
}
?>
</body>
</html>
Hope this helps.

Related

Store name and value of a Button in a mysql table row

I've been hanging on this problem for 3 days and just can't solve it. It seems relatively simple, but unfortunately, I can't do it, because I'm a noob.
I would like to use the button's onclick function to get its 2 pieces of information
```html
<input id="'.$row['id'].'" type="button" value="Pause" name="'.$row['name'].'" onclick="pushDataToDB()">```
name = "'. $ row [' name '].'" [the name reference from a database
table]
and value="Pause"
this two informations i would like to store in some other database table.
I have tried to solve this problem in different ways.
I have tried to store in different ways the event.target.name & event.target.event javascript output in PHP Variables and then use it in the mysql insert line but i failed.
I have tried to post the value to the ajax.php then store the value in a PHP variable and use this as Value to push it to the database, but this also doesn't work
index.php
<div class="button2">
<form action="ajax.php" method="POST">
<input id="'.$row['id'].'" type="button" value="Pause" name="'.$row['name'].'" onclick="pushDataToDB()">
</Form>
</div>'
script.js:
function pushDataToDB() {
$.get("ajax.php");
return false;
}
ajax.php
<?php
include_once ('dbh.php');
if(isset($_POST['name'])){
$sqlAufPause = "INSERT INTO aktuellaufpause (name, pausenart) VALUES ('$name', 'BP')";
}
if ($conn->query($sqlAufPause) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
I would say this is the reason, why the name Value is empty,
but i don't know how to fix ist..
emptyNameValue
You can use JQuery + AJAX to perform asynchronous POST
<?php
$con = mysqli_connect("localhost", "root", "", "testdb");
$query = mysqli_query($con, "SELECT * FROM mytable WHERE id = 1");
$row = mysqli_fetch_assoc($query);
print_r($row);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div class="button2">
<form id="frm">
<input id="<?php echo $row['id'] ?>" type="button" value="Pause" name="<?php echo $row['name'] ?>" onclick="pushDataToDB()">
</Form>
</div>
</body>
<script type="text/javascript">
function pushDataToDB() {
var name = "<?php echo $row['name'] ?>";
var value = "Pause";
$.ajax({
url: "ajax.php",
type: "POST",
data: {
"name": name,
"value": value
},
success: function(e) {
if (e == "1") {
alert("Success!");
} else {
alert("error!");
}
}
});
}
</script>
</html>
ajax.php
<?php
$con = mysqli_connect("localhost", "root", "", "testdb");
$name = $_POST['name'];
$value = $_POST['value'];
$query = "INSERT INTO mytable(name, value) values('$name','$value')";
$result = mysqli_query($con, $query);
if ($result) {
echo "1";
} else {
echo "Error!";
}
EDITTTT****
I changed
var name = "<?php echo $row['id'] ?>";
to
var name = "<?php echo $row['name'] ?>";
since it is the "name" you want stored in the database
I solved the problem this way.
Thank you so much!!!
index.php
<?php
$sql = "SELECT * FROM `DB-TABLENAME` ORDER BY `VALUE1`, `VALUE2`";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)){
echo "<tr>";
echo "<td>";
echo '<input style="margin: 0 auto 6px 17px;" type="checkbox" id="scales" name="scales">';
echo "</td>";
echo "<td>";
echo $row['VALUE1'];
echo "</td>";
echo "<td>";
echo $row['VALUE2'];
echo "</td>";
echo "<td>";
echo '<div class="button1">
<input id="'.$row['id'].'" type="button" value="BP" name="'.$row['VALUE2'].'" onclick="pushDataToDB()">
</div>';
echo "</td>";
echo "<td>";
echo '<div class="button2">
<form id="frm">
<input id="'.$row['id'].'" type="button" value="Mittagspause" name="'.$row['name'].'" onclick="pushDataToDB()">
</form>
</div>';
echo "</td>";
echo "</tr>";
}
} else {
echo "there are no comments";
}?>
<script type="text/javascript">
function pushDataToDB() {
var name = event.target.name;
var value = event.target.value;
$.ajax({
url: "ajax.php",
type: "POST",
data: {
"name": name,
"value": value
},
success: function(e) {
if (e == "1") {
alert("Success!");
} else {
alert("error!");
}
}
});
}
</script>
ajax.php
<?php
include_once('dbconnectioncredentials.php');
$con = mysqli_connect($servername, $username, $password, $dbname);
$name = $_POST['VALUE1'];
$value = $_POST['VALUE2'];
$query = "INSERT INTO aktuellaufpause (VALUE1, VALUE2) VALUES ('$name','$value')";
$result = mysqli_query($con, $query);
if ($result) {
echo "1";
} else {
echo "Error!";
}
?>

Receive post data ajax with php

I'm trying to receive post data with php from ajax in same page but seems like i have some issues that i have no idea to solve them
here is my html/php code :
<select style="width:auto; margin-left:6%;" class="form-control" name="n-omran-select" id="num_omrane">
<option value='' >Choisir...</option>
<?php
while ($row = $result->fetch_assoc())
{
echo "<option value=".$row['N_omran'].">".$row['N_omran']."</option>";
}
?>
</select><br>
<?php
if (isset($_POST["selectName"])) { // try to receive post values but it seems that's not working
$selectOption = $_POST["selectName"];
$query = "SELECT nom,prenom,tel,adress,matricule_assu FROM `personnel` WHERE N_omran ='$selectOption'";
$result = mysqli_query($db,$query);
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if ($row) {
echo " <h4>Nom : {$row['nom']}</h4>
<h4>Prénom : {$row['prenom']}</h4>
<h4>Téléphone : {$row['tel']} </h4>
<h4>Maticule d'assurance : {$row['matricule_assu']}</h4>
<h4>Adresse : {$row['adress']}</h4>";
}
} ?>
And here is my Ajax post request :
$('#num_omrane').on('change', function () {
var n_omrane = $('#num_omrane').val();
if(n_omrane != ''){
$.ajax({
type: "POST",
url: "index.php",
data: {selectName: n_omrane},
success: function () {
alert("Post request successfully done")
}
});
}
});
the code below can replace all your data with the new ones with clean writing :)
// get data from Database
<?php
if (isset($_POST["selectName"])) { // try to receive post values but it seems that's not working
$selectOption = $_POST["selectName"];
$query = "SELECT nom,prenom,tel,adress,matricule_assu FROM `personnel` WHERE N_omran ='$selectOption'";
$result = mysqli_query($db,$query);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
} ?>
// show rows to be selected
<select style="width:auto; margin-left:6%;" class="form-control" name="n-omran-select" id="num_omrane">
<option value='' >Choisir...</option>
<?php while ($row = $result->fetch_assoc()) { ?>
<option value="<?= $row['N_omran'] ?>"> <?= $row['N_omran'] ?></option>
<?php } ?>
</select><br>
// show recieved data
<?php if ($row) { ?>
<div id="informations">
<h4>Nom : <span id="nom"><?= $row['nom'] ?></span></h4>
<h4>Prénom : <span id="prenom"><?= $row['prenom'] ?></span></h4>
<h4>Téléphone : <span id="tel"><?= $row['tel'] ?> </span></h4>
<h4>Maticule d'assurance : <span id="matricule_assu"><?= $row['matricule_assu'] ?></span></h4>
<h4>Adresse : <span id="adress"><?= $row['adress'] ?></span></h4>
</div>
<?php } ?>
// script for making ajax call
<script>
$('#num_omrane').on('change', function () {
var n_omrane = $('#num_omrane').val();
if(n_omrane != ''){
$.ajax({
type: "POST",
url: "index.php",
data: {selectName: n_omrane},
success: function (response) {
$("#nom").text(response.nom);
$("#prenom").text(response.prenom);
$("#tel").text(response.tel);
$("#matricule_assu").text(response.matricule_assu);
$("#adress").text(response.adress);
}
});
}
});
</script>
$json_data=file_get_contents('php://input');
$json=json_decode($json_data,true);
if(array_key_exists("selectName",$json)){
$selectOption =$json["selectName"];
}

Jquery: Uncaught TypeError Illegal Invocation

I was following webpage to learn about displaying data from mysql without page refresh:-
http://talkerscode.com/webtricks/load%20data%20from%20database%20without%20page%20refresh%20using%20ajax%20and%20jquery.php
Following are the 2 files
File1: displaydata.html
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.3.min.js" integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=" crossorigin="anonymous"></script>
<script type="text/javascript">
function load_data() {
var name = document.getElementById("guestname");
if (name) {
$.ajax({
url: 'loaddata.php',
type: 'POST',
data: {
guest_name: name,
},
success: function(response) {
// We get the element having id of display_info and put the response inside it
$('#display_info').html(response);
//document.getElementById('display_info').innerHTML = response;
}
});
} else {
$('#display_info').html("Please Enter Some Words");
}
}
</script>
</head>
<body>
<input type="text" name="guestname" id="guestname" onKeyUp="load_data();">
<div id="display_info">
</div>
</body>
</html>
File2: loaddata.php
<?php
$host='localhost';
$user='root';
$pw='';
$db='yoigo';
$connect = new mysqli($host, $user, $pw, $db);
if(mysqli_connect_errno()){
printf("Connect failed: %s\n",mysqli_connect_error());
exit();
} else {
echo "Jatinder!";
}
if( isset( $_POST['guest_name'] ) )
//if(1)
{
$name = $_POST['guest_name'];
$sql = " SELECT lastname,email FROM myguests WHERE firstname LIKE '$name%' ";
$result = $connect->query($sql);
if($result === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$rows_returned = $result->num_rows;
}
echo $rows_returned . ' rows returned.' . '<br> <br>';
if ($rows_returned > 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_NUM)){
echo "<p>".$row[0]."</p>";
echo "<p>".$row[1]."</p>";
}
}
}
?>
I am frustrated by this illegal invocation error of jquery. Not sure why its coming. Could anyone please guide?
Thanks,
Jatinder

Updating Edited Value Using Jquery/PHP/Mysql

can some one help me out in updating edited value in mysql db using jquery/php.
I have three buttons edit/save/cancel
when i click on edit button span data pushed into input text and edit button replaced with save button!!
when i click on edit button i'll get span data in my text box with save and cancel button but when i try to update using save button its not updating in my db and in UI
Code
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function showdata()
{
$.ajax({
url:"pages/feeds.php",
type:'post',
async:false,
data:{
showtable:1
},
success:function(re){
$('#showdata').html(re);
}
});
}
$('#orders').delegate('.editOrder','click',function(e){
e.preventDefault(e);
var $li = $(this).closest('li'); $li.find('input.name').val($li.find('span.name').html());
$li.addClass('edit');
});
$('#orders').delegate('.cancelEdit','click',function(e){
e.preventDefault(e);
$(this).closest('li').removeClass('edit');
});
//Edit Code
$('body').delegate('.edit','click',function(){
var IdEdit = $(this).attr('ide');
$.ajax({
url:"pages/feeds.php",
type:"post",
data:{
editvalue:1,
id:IdEdit
},
success:function(show)
{
$('#id').val(show.id);
$('#url1').val(show.url);
}
});
});
//Ends
//Update Starts
$('.update').click(function(){
var id = $('#id').val()-0;
var urls = $('#url1').val();
$.ajax({
url:"pages/feeds.php",
type:"post",
async:false,
data:{
update:1,
id:id,
upurls:urls
},
success:function(up)
{
$('input[type=text]').val('');
showdata();
},
error:function(){
alert('error in updating');
}
});
});
//UPdate Ends
</script>
<style type="text/css">
ul li .edit{
display:none;
}
ul li.edit .edit{
display:initial;
}
ul li.edit .noedit{
display:none;
}
</style>
</head>
<body>
<ul id="orders">
<?php
$sql = "select * from demo";
$result = mysql_query($sql);
while($row = mysql_fetch_object($result))
{
?>
<li>
<span class="noedit name" value='<?php echo $row->id;?>'><?php echo $row->url;?></span>
<input id="url1" class="form-control edit name" value="<?php echo $row->id;?>"/>
<a ide='<?php echo $row->id;?>' id="edit" class='editOrder' href="#" style="display:block-inline;">EDIT</a>
<a idu='<?php echo $row->id;?>' id="update" class='update saveEdit' href='#' style='display:none;'>SAVE</a>
<a idd='<?php echo $row->id;?>' id="delete" class='delete' href="#" style="display:block-inline;">DELETE</a>
<a idc='<?php echo $row->id;?>' id="cancel" class='cancelEdit edit' href='#' style='display:none;'>CANCEL</a>
</li>
<?php } ?>
</ul>
</body>
</html>
<?php
//Edit Starts
if(isset($_POST['editvalue']))
{
$sql = "select * from deccan where id='{$_POST['id']}'";
$row = mysql_query($sql);
$rows = mysql_fetch_object($row);
header("Content-type:text/x-json");
echo json_encode($rows);
exit();
}
//Ends
//UPdate Starts
if(isset($_POST['update']))
{
$sql = "
update deccan
set
url='{$_POST['upurls']}'
where id='{$_POST['id']}'
";
$result = mysql_query($sql);
if($result)
{
//alert('success');
echo 'updated successfully';
}
else
{
//alert('failed');
echo 'failed to update';
}
}
?>
Alright. I was still missing the following code from you, so you'll have to add these yourself:
The HTML element with parameter id="id" needed for $('#id').val(text.id);
The HTML element with parameter id="url1" needed for $('#url1').val(text.url);
The PHP response code for JS function showdata(); inside feeds.php
Since I don't have your database here, I was unable to test the code. It should work fine, but if anything is wrong, just let me know:
PHP file: index.php
<?php
// Include PDO class
include_once("pdo.class.php");
// Database connection settings
define("DB_HOST", "localhost");
define("DB_USER", "username");
define("DB_PASS", "password");
define("DB_NAME", "database");
?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- CSS resources -->
<link rel="stylesheet" type="text/css" href="style.css">
<!-- Javascript resources -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="main.js"></script>
<title>Update Script</title>
</head>
<body>
<ul id="orders">
<?php
// Instantiate database
$db = new Database;
// Try getting data from database
Try {
// Query
$db->query("SELECT * FROM demo");
// Get results
$data = $db->resultset();
// Echo reults
foreach($data as $row){ ?>
<li>
<span class="noedit name" value="<?php echo $row['id']; ?>"><?php echo $row['url']; ?></span>
<input id="url1" class="form-control edit name" value="<?php echo $row['id']; ?>" />
<a data-ide="<?php echo $row['id']; ?>" class='editOrder' href="#" style="display:block-inline;">EDIT</a>
<a data-idu="<?php echo $row['id']; ?>" class='update saveEdit' href='#' style='display:none;'>SAVE</a>
<a data-idd="<?php echo $row['id']; ?>" class='delete' href="#" style="display:block-inline;">DELETE</a>
<a data-idc="<?php echo $row['id']; ?>" class='cancelEdit edit' href='#' style='display:none;'>CANCEL</a>
</li>
<?php }
//Catch any database errors
} Catch(PDOException $e){
echo "Database error:". $e->getMessage();
}
?>
</ul>
</body>
</html>
Javascript file: main.js
$('#orders').delegate('.editOrder','click',function(e){
e.preventDefault();
var $li = $(this).closest('li');
$li.find('input.name').val($li.find('span.name').html());
$li.addClass('edit');
});
$('#orders').delegate('.cancelEdit','click',function(e){
e.preventDefault();
$(this).closest('li').removeClass('edit');
});
//Edit Code
$('body').delegate('.edit','click',function(){
var IdEdit = $(this).attr('data-ide');
$.ajax({
url: "pages/feeds.php",
type: "POST",
data: 'editvalue=1&id='+IdEdit,
success: function(text){
$('#id').val(text.id);
$('#url1').val(text.url);
}
});
});
//Update Code
$('.update').click(function(){
var id = $('#id').val()-0;
var urls = $('#url1').val();
$.ajax({
url: "pages/feeds.php",
type: "POST",
async: false,
data: 'update=1&id='+id+'&upurls='+urls,
success: function(text){
$('input[type=text]').val('');
showdata();
},
error:function(){
alert('Error in updating');
}
});
});
function showdata(){
$.ajax({
url: "pages/feeds.php",
type: "POST",
async: false,
data: 'showtable=1',
success:function(text){
$('#showdata').html(text);
}
});
}
CSS file: style.css
ul li .edit{
display:none;
}
ul li.edit .edit{
display:initial;
}
ul li.edit .noedit{
display:none;
}
PHP file: feeds.php
<?php
// Include PDO class
include_once("pdo.class.php");
// Database connection settings
define("DB_HOST", "localhost");
define("DB_USER", "username");
define("DB_PASS", "password");
define("DB_NAME", "database");
// Instantiate database
$db = new Database;
// Edit
if(isset($_POST['editvalue']) && $_POST['editvalue'] == 1){
// Try getting data from database
Try {
// Query
$db->query("SELECT * FROM deccan WHERE id = :id");
// Prepare POST data (to prevent SQL injection)
$db->bind(":id", $_POST['id']);
// Get result
$data = $db->single();
// Set header JSON
header("Content-type:text/x-json");
// Return result
echo json_encode($rows);
} Catch(PDOException $e){
echo "Database error:". $e->getMessage();
}
} else if(isset($_POST['update']) && $_POST['update'] == 1){
// Try updating data in database
Try {
// Query
$db->query("UPDATE deccan SET url = :url WHERE id = :id");
// Prepare POST data (to prevent SQL injection)
$db->bind(":url", $_POST['upurls']);
$db->bind(":id", $_POST['id']);
// Execute Query
$db->execute();
// Return succes
echo 'updated successfully';
} Catch(PDOException $e){
echo "Database error:". $e->getMessage();
}
} else if(isset($_POST['showtable']) && $_POST['showtable'] == 1){
/*
This part was not included in your code, so write it
yourself using above data as examples
*/
}
?>
PHP file: pdo.class.php
<?php
Class Database {
private $host = DB_HOST;
private $user = DB_USER;
private $pass = DB_PASS;
private $dbname = DB_NAME;
private $dbh;
private $error;
private $stmt;
public function __construct(){
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
// Set options
$options = array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
);
// Create a new PDO instanace
try{
$this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
}
// Catch any errors
catch(PDOException $e){
$this->error = $e->getMessage();
return $this->error;
}
}
public function query($query){
$this->stmt = $this->dbh->prepare($query);
}
public function bind($param, $value, $type = null){
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($param, $value, $type);
}
public function execute(){
return $this->stmt->execute();
}
public function column(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_COLUMN);
}
public function resultset(){
$this->execute();
return $this->stmt->fetchAll(PDO::FETCH_ASSOC);
}
public function single(){
$this->execute();
return $this->stmt->fetch(PDO::FETCH_ASSOC);
}
public function rowCount(){
return $this->stmt->rowCount();
}
public function lastInsertId(){
return $this->dbh->lastInsertId();
}
public function beginTransaction(){
return $this->dbh->beginTransaction();
}
public function endTransaction(){
return $this->dbh->commit();
}
public function cancelTransaction(){
return $this->dbh->rollBack();
}
public function debugDumpParams(){
return $this->stmt->debugDumpParams();
}
}
?>
I would normally have two scripts (.php) files.
One to display the form and one to catch the submission (possibly via ajax)
You can have both in the same .php file but then you'd want to check before outputting any text whether you have any POST data to process.
If you go with two files
view file:
<html>
<body>
<form method="POST" action="path/to/formname_submit.php">
your form fields go here
<input name="somefield"/>
...
</form>
<script>
//your jquery code
....
</script>
<body>
</html>
submit file
<?php
if (empty($_POST['id'])){
die("no ID");
};
if (empty($_POST['editvalue'])){
die("no editvalue");
}
//get a database connection
$db = mysqli(DBHOST,DBUSER,DBPASS,DBNAME);
$db->set_charset("utf8");
// read in the POST data
//should do some more validation / anti SQL injection
$editvalue = $db->escape_string($_POST['editvalue']);
$id = intval($_POST['id']);
$sql = "UPDATE sometable SET `field` = '$editvalue' WHERE id=$id";
if ($db->query($sql)){
echo 'Success';
}
else {
echo 'UPDATE ERROR:'.$db->errno.': '.$db->error;
}
your jquery can now send the data to the second script and see if the data coming back from the call is 'Success' and display an error if it's not.

Insert record into mysql using json

I want to insert the record using json into mysql and the system could display the new record without refreshing the page.
My code is shown as below:
Part 1, the script get two values from form and convert it into json, passing them to action.php
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var name = $("#name").val();
var dataString = {'content': textcontent, 'name': name};
if (textcontent == '') {
alert("Enter some text..");
$("#content").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
dataType: 'json',
cache: true,
success: function(html){
$("#show").html(html);
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
<div>
<?php
$conn=mysqli_connect('localhost','Practical4','1234') or die('Not connected');
$database=mysqli_select_db($conn,'Practical4') or die('Database Not connected');
$id=$_GET['id'];
$query = "select * from hotel where name='$id'";
$data=mysqli_query($conn,$query);
while($rows=mysqli_fetch_array($data)){
$name=$rows['name'];
$price=$rows['price'];
$duetime=$rows['dueTime'];
$address=$rows['location'];
}
?>
<form method="post" name="form" action="">
<h3>Add Comment for <?php echo $name;?><h3>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="text" name="name" id="name" value="<?php echo $name;?>" hidden > <br>
<input type="submit" value="Add Comment" name="submit" class="submit_button"/>
</form>
</div>
<?php
$host="localhost";
$username="Practical4";
$password="1234";
$db_name="Practical4";
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from comment where name='$name'";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_row($result)){
$json[] = $row[1];
}
}
mysql_close($con);
echo implode('<br />', $json);
?>
<div class="space" ></div>
<div id="flash"></div>
<div id="show" ></div>
Part2, action.php, which insert the record into mysql database.
<?php
$DBServer = 'localhost'; // e.g 'localhost' or '192.168.1.100'
$DBUser = 'Practical4';
$DBPass = '1234';
$DBName = 'Practical4';
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
// check connection
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
$v1="'" . $conn->real_escape_string($_POST['content']) . "'";
$v2="'" . $conn->real_escape_string($_POST['name']) . "'";
$sql="INSERT INTO comment (content,name) VALUES ($v1,$v2)";
if($conn->query($sql) === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$last_inserted_id = $conn->insert_id;
$affected_rows = $conn->affected_rows;
echo '<div class="showbox">'.$v1.'</div>';
}
?>
So far the code can insert new data, but it won't display the new record dynamically without refreshing page. Any idea to fix that?
Change your dataType to html since this parameter tells the server what kind of response it will accept in return:
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
dataType: 'html',
cache: true,
success: function(data){
$("#show").html(data);
$("#flash").hide();
$("#content").focus();
}
});
In the above case the return value should be plain html:
print '<div class="showbox">' . $v1 . '</div>';
You then add it to your page using:
$('#show').html(data);
If you still would like to use json you could encode your response using something like this:
print json_encode(array('html' => '<div class="showbox">' . $v1 . '</div>'));
Then you would need to parse this value:
$("#show").html(data.html);
In the above example it seems clearer to name the success functions argument to something like data since it won't contain just html in the case.

Categories