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
Related
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.
I am trying to pass a php variable located in a php file to a separate JavaScript file. I'm trying to pass the variables at the end of the php file in the input functions into the jQuery variables called $message and $username.
Here is where I'm at so far:
chat.php
<?php
//form data
$username = $_POST['username'];
$password = $_POST['password'];
//sql server connection credentials
$servername = "localhost";
$serverusername = "suser11";
$serverpassword = "suser11";
$databasename = "chat_database";
// Create connection
$conn = new mysqli($servername, $serverusername, $serverpassword, $databasename);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br /><br />";
$username = $conn->real_escape_string($username);
$password = $conn->real_escape_string($password);
$sql = "SELECT Salt FROM users WHERE Username='$username'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
$salt = $row["Salt"];
}
$sql = "SELECT * FROM users WHERE Username='$username' AND Password=MD5('$password$salt')";
$result = $conn->query($sql);
if($result->num_rows === 0) {
$conn->close(); //close the db connection
header('Location: login.html'); //redirect to login.html
} else {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "UserID: " . $row["user_id"]. " - Name: " . $row["username"]. "<br />";
}
}
// Close the database connection
$conn->close();
?>
<textarea id="myChat" type="text" style="width:500px; height:500px;"></textarea>
<br/>
<br/>
<input id="myText" name="myText"/>
<input type="hidden" value="<?php echo $username; ?>"/>
<button id="add">
<b>Add to chat</b>
</button>
</body>
</html>
Here is my jquery file
$(document).ready(function() { //start 1
//alert("hello world, jQuery is working");
setInterval(function(){$("#myChat").load("chat.txt")},100); //update the textarea with the text file contents every 10th of a second
var $message = '';
var $username = '';
$('#add').click(function(){ // start 2
var $message = $('#myText').val();
var $username = $('$username').val();
//alert("Got the message");
$.ajax({ // start 3
type: "POST",
url:'myprocess.php',
data:{'xml': $xmlString},
dataType:'text/xml',
//success: function(r){ // start 4
//alert('Got it');
//}, // end 4
//error: function (xhr, desc, err) {
//console.log(xhr);
//console.log("Details: " + desc + "\nError: " + err);
//alert ("Error: " + err);
//}
}); // end 3
$('#myText').val(""); //clears value of text box on click of button with id=add
}); // end 2
//forming proper xml
$xmlString ='<?xml version="1.0" encoding="ISO-8859-1"?>';
$xmlString += '<message><user>' + username + '</user><text>' + $message + '</text></message>';
}); // end 1
In php you can pass like:
Just replace your code:
// output data of each row
while($row = $result->fetch_assoc()) {
echo "UserID: " . $row["user_id"]. " - Name: " . $row["username"]. "<br />";
}
with below code:
while($row = $result->fetch_assoc()) {
echo $row["user_id"]."||".$row["username"];
}
and in ajax:
$.ajax({
type: "POST",
url:'myprocess.php',
data:{'xml': $xmlString},
dataType:'text/xml',
success: function(data){
details = data.split("||");
username = details[0];
password = details[1];
}
});
I am trying to run a script. The script needs to show me data from the database. In my script I am using 1 dropdown and 1 textbox. When I change the selected value (product) in my dropdown it needs to show the price of the selected value. The price needs to be shown in the textbox.
The script is not working. I tried to figure out what the problem is. I used developer console tool of my browser. The developer console tool gives me the error:
Uncaught ReferenceError: getPrice is not defined | onchange # (index):1
Can someone help me with this problem?
The pages that I am using for this script are the following pages:
index.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM forms";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<select class='form-control select2' id='product1' name='product1' onChange='getPrice(this.value)' style='width: 100%;'>";
echo "<option selected disabled hidden value=''></option>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value='" . $row["id"]. "'>" . $row["name"]. "</option>";
}
echo "</select>";
} else {
echo "0 results";
}
$conn->close();
?>
<html>
<body>
<!-- Your text input -->
<input id="product_name" type="text">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getPrice() {
// getting the selected id in combo
var selectedItem = jQuery('.product1 option:selected').val();
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: 'id=' + selectedItem,
success: function(response){
// and put the price in text field
jQuery('#product_name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
</body>
</html>
get.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
// Check connection
if ($conn->connect_error)
{
die('Connection failed: ' . $conn->connect_error) ;
}
else
{
$product1 = filter_input(INPUT_POST, 'id', FILTER_SANITIZE_NUMBER_INT) ;
$query = 'SELECT price FROM forms WHERE id=" . $product1 . " ' ;
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0)
{
$result = mysqli_fetch_assoc($res) ;
echo "<input type='text' value='";
echo json_encode($result['price']);
echo "'>";
}
else
{
echo "<input type='text' value='";
echo json_encode('no results') ;
echo "'>";
}
}
?>
First close <script> tag :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Your scripts tags should be before </html> and inside <body> tag :
<html>
<body>
<!-- Your text input -->
<input id="product_name" type="text">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getPrice() {
// getting the selected id in combo
var selectedItem = jQuery('.product1 option:selected').val();
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: 'id=' + selectedItem,
success: function(response){
// and put the price in text field
jQuery('#product_name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
</body>
</html>
The PHP condition could be simple and you don't need any json encoding, e.g:
if (mysqli_num_rows($res) > 0)
{
$result = mysqli_fetch_assoc($res) ;
echo $result['price'];
}else{
echo 'no results';
}
Hope this helps.
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.
So, what im doing is searching for records stored in a database using AJAX, but when it prints the callback data, the first record is duplicated:
My code:
$gUser = $_GET['q'];
$connect = mysql_connect("localhost", "root", "") or die("Could not connect to the server");
mysql_select_db("socialj") or die("Could not connect to the database");
$result = mysql_query("SELECT fullname, email FROM users WHERE fullname LIKE '%$gUser%' ");
while($array[] = mysql_fetch_array ($result))
{
foreach($array as $r)
{
echo $r['fullname'].' | '.$r['email'].'<br>';
}
}
?>
JavaScript Code:
$(document).ready(function (){
$('#searchh').on('submit', function (e){
e.preventDefault();
var sVal = $('#search').val();
$.ajax({
type: 'get',
url: 'profile.php',
data: {q : sVal},
success: function (data) {
alert(data);
}
});
});
});
Could you guys help me? I don't know whats happening... Thanks.
Replace this
while($array[] = mysql_fetch_array($result)) {
foreach($array as $r) {
echo $r['fullname'] . ' | ' . $r['email'] . '<br>';
}
}
with this
while($row = mysql_fetch_array($result)) {
echo $row['fullname'] . ' | ' . $row['email'] . '<br>';
}