Run separate queries in MySQL using a single link - javascript

I have created that toggles a material icon to on/off.
When the icon is off I need to run a delete query.
When the icon is on I need to run a insert query.
I know I need to use AJAX and am still new to it.
What I am having trouble understanding is whether I refernece the current PHP file or some other php file. Iknow I have to write my query and execute it in a PHP file, but not sure to do that. I do not want to reload the pagebecuase I lose other information by doing so.
I basically owuld like to update the icon and execute the required SQL stmnt.
Any help is appreciated.
What I have so far:
JAVASCRIPT:
//update the favorites icon
function updateFavorites(id){
if($(this).find('#staricon'+id)){
if($('#staricon'+id).hasClass('star-color')) {
$('#staricon'+id).removeClass('star-color');
//update the table
deleteFavorites();
}
else {
$('#staricon'+id).addClass('star-color');
addFavorites();
}
}
}
//delete the item from the table
function deleteFavorite(){
$.ajax({
type: "POST",
url: "somePHPFile.php",
cache: false,
data:{id:'#staricon'+id},
}).done(function( msg ) { console.log(msg);
});
}
PHP:
//check to see if this is a favorite
$query = "SELECT * FROM favorites WHERE story_id = " . $story_id;
$result = mysqli_query($conn, $query);
$is_fav = mysqli_num_rows($result);
if ($is_fav > 0) {
echo '<a class=" stats pull-right " href="javacript:void" ><span id="staricon' . $story_id .'" class="star-color" onclick="updateFavorites(' . $story_id . ')"><i class=" material-icons " title="Favorite" >star</i></span></a>';
}
else {
echo '<a class=" stats pull-right " href="javacript:void" ><span id="staricon' . $story_id .'" onclick="updateFavorites(' . $story_id . ')"><i class=" material-icons " title="Favorite" >star</i></span></a>';
}
I have update my code to reflect the following:
JAVASCRIPT:
function updateFavorites(id){
if($(this).find('#staricon'+id)){
if($('#staricon'+id).hasClass('star-color')) {
$('#staricon'+id).removeClass('star-color');
$.ajax({
type: "POST",
url: "showStoryCards.php",
data: {
id: $(this).data(id),
enabled: !$(this).hasClass('star-color') //delete
},
})
}
else {
$('#staricon'+id).addClass('star-color');
$.ajax({
type: "POST",
url: "showStoryCards.php",
data: {
id: $(this).data("id"),
enabled: $(this).hasClass('star-color') //insert
},
})
}
}
PHP:
echo $story_title ;
$query = "SELECT count(*) FROM favorites WHERE story_id = ?";
$sql= $conn->prepare($query);
$sql->bind_param("s", $story_id);
$sql->execute();
$result = $sql->get_result();
$is_fav = mysqli_num_rows($result);
if ($is_fav == 0) {
echo '<a class=" stats pull-right " href="javacript:void" ><span
id="staricon' . $story_id .'" class="star-color"
onclick="updateFavorites(' . $story_id . ')"><i class=" material-icons "
title="Favorite" >star</i></span></a>';
}
else {
echo '<a class=" stats pull-right " href="javacript:void" ><span
id="staricon' . $story_id .'" onclick="updateFavorites(' . $story_id .
')"><i class=" material-icons " title="Favorite" >star</i></span></a>';
}
if (isset($_POST['enabled'])){
if($_POST['enabled']) { // INSERT query
$sql = "INSERT INTO favorites VALUES( " . $id . ", '1') ";
$sql->execute();
} else {// Delete query
}
}
My icons update to the appropriate on /off colors but I still cannot get the query to fire. It does not even appear that the call back to the PHP page is functioning as I cannot retrieve the $_POST.

Use prepared statements because you're opening yourself to injection attacks.
Try this query
$query = "SELECT * FROM favourites WHERE story_id = ?";
$sql= $conn->prepare($query);
$sql->bind_param("s", $story_id);
$sql->execute();
$result = $sql->getResult();
print_r($result);

Simplify it all.
$(document).ready(function() {
$('#staricon').on('click', function() {
// Prevent multiple clicks before the first one finishes.
// There is probably a more elegant way to do this.
if(active){
return;
}
active = false;
//console.log($(this).hasClass('star-color'));
//console.log($(this).data("id"));
$.ajax({
type: "POST",
url: "somePHPFile.php",
data: {
id: $(this).data("id"),
enabled: !$(this).hasClass('star-color')
},
}).done(function(msg) {
active = true;
$(this).toggleClass('star-color');
console.log(msg);
});
});
});
/*
PHP
// Use ID and enabled to add or delete from db.
if($_POST['enabled']) {
// INSERT query
} else {
// Delete query
}
*/
div.star-color {
background-color: #FF00FF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="staricon" data-id="1" class="star-color">Test</div>

Related

How to prevent refreshing page after AJAX call

I have this php page with javascript ajax which calls another php file. But every time it calls, it refreshes the page.
I tried these two codes but still it keeps refreshing after calling the `php file:
e.preventDefault();
//and
return false;
But still it keeps redirecting/refreshing to the same page. I don't even have redirecting headers in php file I'm calling.
This is my HTML
<div class="col-md-3 col-sm-6 col-6 ad-image">
<label for="file1">
<img id="blah1" src="http://placehold.it/500" alt="..." class="img-thumbnail">
<input type="button" value="Remove Photo" style="margin-top: 5px;" class="btn btn-danger btn-sm" id="image-remove-btn-1">
<small id="textCount" class="form-text text-center bold">Thumbnail</small>
</label>
</div>
Here's my javascript
$("#image-remove-btn-1").click(function (e) {
e.preventDefault(); //doesn't work still page keeps refreshing
$('#blah1').attr('src', 'http://placehold.it/500');
var userId =<?php echo $userId ?>;
var adId =<?php echo $adId ?>;
deletePhoto('blah1', userId, adId); //this is the function with ajax
$(this).hide();
return false; //doesn't work still page keeps refreshing
});
Here's the deletePhoto() function:
function deletePhoto(imgeName, userid, adId) {
$(document).ready(function () {
$.ajax({
url: 'includes/remove-ad-image-inc.php',
dataType: 'text', // what to expect back from the PHP script, if anything
data: {
userId: userid,
adId: adId,
imgeName: imgeName
},
type: 'post',
success: function (php_script_response) {
alert(php_script_response); // display response from the PHP script, if any
}
});
});
}
This is my php remove-ad-image-inc.php I am calling through above ajax
<?php
include_once './dbConnection.php';
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$userId = mysqli_real_escape_string($conn, filter_input(INPUT_POST, "userId"));
$adId = mysqli_real_escape_string($conn, filter_input(INPUT_POST, "adId"));
$imgeName = mysqli_real_escape_string($conn, filter_input(INPUT_POST, "imgeName"));
if (isset($userId) && isset($adId) && isset($imgeName)) {
$sql = "SELECT * FROM adimage WHERE adimageno=? AND adid=? AND userid=?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
echo "error!";
} else {
mysqli_stmt_bind_param($stmt, "sii", $imgeName, $adId, $userId);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_assoc($result)) {
$ImageId = $row['adimageid'];
}
$fileName = "../uploads/ad/adImage-" . $ImageId . "-" . $adId . "-" . $userId . "*";
$fileInfo = glob($fileName);
$fileExt = explode(".", $fileInfo[0]);
$fileActualExt = $fileExt[1];
$file = "../uploads/ad/adImage-" . $ImageId . "-" . $adId . "-" . $userId . "." . $fileActualExt;
array_map('unlink', glob($fileName));
$sql = "UPDATE adimage SET adimagestatus=1 WHERE adimageid='$ImageId';";
mysqli_query($conn, $sql);
exit();
}
}
Can someone please help me with a solution?

Change the colour of text as it is displayed with php

At the moment I have a text area where people can insert their own sql scripts for people to see however it currently displays quite bland.
I was wondering if there was a way in which using Jquery/Javascript/PHP that when people load a note from the database, it then does a check through a list of words. For example "SELECT", "FROM", "WHERE", "INNER", "JOIN" and if they match it sets the colour of them to a defined colour?
This would need to happen when the note is displayed on the screen as the text is coming from a database. So maybe there is some way to check the words as they are pulled through from the database.
These notes are being pulled through as follows:
if (isset($_POST['noteid']))
{
$showNoteInfo = "SELECT Note, NoteName FROM Notes WHERE NoteID = " . $_POST['noteid'];
$stmt = sqlsrv_query($conn, $showNoteInfo);
}
if (isset($_POST['noteid']))
{
if (empty($_POST['noteid']))
{
$notes = 'No Data';
}
if (sqlsrv_has_rows($stmt))
{
$data = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC);
echo "<div class='custom-font title-container'>
<div class='expand-button-container fa fa-expand' onclick='expandWindow()'></div>
<div id='title-container1'><div class='edit-note fa fa-pencil' onclick='editGeneralNote()'> </div>" . "<div data-toggle='modal' data-target='#editNoteNameModal' class='display-inline'>" . $data['NoteName'] . "</div>" . " <div class='save-note fa fa-thumbs-up' onclick='saveGeneralNote(); submitNoteText();'></div></div>
</div>";
echo "<textarea spellcheck='false' readonly id='ta1'>" . $data['Note'] . "</textarea>";
}
else
{
echo "No data found";
}
}
So how can I colour certain words pulled through from a database as they are displayed on screen?
If anyone could help I would appreciate it.
Good old way :
//Your keywords to be highlighted
$keyWord = array("SELECT", "FROM", "WHERE");
//The string to stlylish
$str = "Select * From db";
foreach(explode(" ", $str) as $word)
{
if (in_array(strtoupper($word), $keyWord))
{
echo '<span class="color">' . $word . '</span>';
}
}
If you prefer to get the result of the stylish process as a string and not a simple echo. You could use implode. It's the oposite of explode. You will just have to store the echo line in an array and implode the array after the loop.Resulting in somethink like this :
//Your keywords to be highlighted
$keyWord = array("SELECT", "FROM", "WHERE");
//The string to stlylish
$str = "Select * From db";
$result = array();
foreach(explode(" ", $str) as $word)
{
if (in_array(strtoupper($word), $keyWord))
{
array_push($result, '<span class="color">' . $word . '</span>');
}
else {
array_push($result, $word);
}
}
$str = implode($result, " ");
echo $str;
I would do it with preg_replace():
$note = preg_replace('%(SELECT|FROM|WHERE)%m', '<span style="color: green;">$1</span>', $data['Note']);
echo $note;
$1 references the first capturing group. More information about regular expressions in PHP and regexp references can be found here.
How to use it in your scenario:
if (isset($_POST['noteid']))
{
$showNoteInfo = "SELECT Note, NoteName FROM Notes WHERE NoteID = " . $_POST['noteid'];
$stmt = sqlsrv_query($conn, $showNoteInfo);
}
if (isset($_POST['noteid']))
{
if (empty($_POST['noteid']))
{
$notes = 'No Data';
}
if (sqlsrv_has_rows($stmt))
{
$data = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC);
echo "<div class='custom-font title-container'>
<div class='expand-button-container fa fa-expand' onclick='expandWindow()'></div>
<div id='title-container1'><div class='edit-note fa fa-pencil' onclick='editGeneralNote()'> </div>" . "<div data-toggle='modal' data-target='#editNoteNameModal' class='display-inline'>" . $data['NoteName'] . "</div>" . " <div class='save-note fa fa-thumbs-up' onclick='saveGeneralNote(); submitNoteText();'></div></div>
</div>";
$note = preg_replace('%(SELECT|FROM|WHERE)%m', '<span style="color: green;">$1</span>', $data['Note']);
echo "<textarea spellcheck='false' readonly id='ta1'>$note</textarea>";
}
else
{
echo "No data found";
}
}

dynamic ajax dropdown menu not working

i'm trying to make a notification tab work but do not seem to get it right. The dropdown is working fine but the ajax call to newfriends.php is not working right, when viewed with firebug there are no results to be seen in the dropdown.Quite confusing.
(note the dropdown menu is located in header and can only be displayed if the session is initialised)
here is the ajax used in jquery:
function load_notifications(view=''){
$.ajax({
url: "notification/new_friends.php",
method: "POST",
data:{view:"view"},
dataType:"json",
success: function(data){
$(".dropdown-menu").html(data.notification);
if(data.unseen_notification>0){
$(".badge1").html(data.unseen_notification);
}
}
});
//$(".dynamic-notification").load("notification/pm_n.php");
// $(".dynamic-notification-f").load("notification/new_friends.php");
};
load_notifications();
$(document).on("click",".count_friend", function(){
load_notifications('yes');
});
//loads every 2 seconds for chat
setInterval(function(){load_notifications();},2000);
here is the new_friends.php content:
<?php
include '../includes/dbconfig.inc.php';
if (isset($_POST['view'])) {
if($_POST['view'] !=''){
$update="update friends set count='1' where friend_one=:session and count='0'";
$stmt=$conn->prepare($update);
$stmt->bindValue(":session", $_SESSION['uname']);
$stmt->execute();
}
$sql123="select id from friends where friend_two=:sess_uname and count='0'";
$stmt123=$conn->prepare($sql123);
$stmt123->bindValue(":sess_uname", $_SESSION['uname']);
$stmt123->execute();
$request_count=$stmt123->fetchColumn();
//$count_friend=$stmt123->rowCount();
/*$sql_f_count="select *from user where user_id=:session_id and activated='1' limit 1";
$stmt_f_count=$conn->prepare($sql_f_count);
$stmt_f_count->bindValue(":session_id", $_SESSION['id']);
$stmt_f_count->execute();
$user_details=$stmt_f_count->fetchAll();
$friend_badge=$user_details[0]['friend_count_badge'];*/
require "notification/friend_request_notification.php";
// $new_friends="<span class='dropdown'><a href='#' data-placement='bottom' class='btn dropdown-toggle' data-toggle='dropdown' title='Friend Requests' data-html='true'><span class='count_friend' style=' height:33px; width:30px;'><span class='badge1 label label-pill'>".$count."</span><img src='img/logo/group-button-white.png' style='height:25px; width:27px;' alt='new_friends_alert'></span></a><ul class='dropdown-menu'></ul></span>";
//if($request_count[0]>0){
//$new_friends="<a href='#' data-placement='bottom' class='btn' data-trigger='focus' title='Friend Requests' data-toggle='popover' data-html='true' data-content='".$friend_requests."'><span class='count_friend' style=' height:33px; width:30px;'><img src='img/logo/group-button-white.png' style='height:25px; width:27px;' alt='new_friends_alert'></span><span class='badge'>".$friend_badge."</span></a>";
/*}else{
$new_friends="<a href='all_notifications.php'><img src='img/logo/group-button-black.png' style='height:25px; width:27px;' alt='new_friends_alert'></a>";
}*/
//echo $new_friends;
//}
$data=array(
'notification'=>$friend_requests,
'unseen_notification' =>$request_count[0][0]
);
}
echo json_encode($data);
and the code for friend requests output:
<?php
//error_reporting(0);
require_once 'includes/dbconfig.inc.php';
$sql = "select * from friends where friend_two=:session and accepted='0' order by friends_date_made asc";
$stmt = $conn->prepare($sql);
$stmt->bindparam(":session", $_SESSION['uname']);
$stmt->execute();
$numrows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$friend_requests="";
if ($numrows < 1) {
$friend_requests = "You do not have any friend requests";
echo "$friend_requests";
exit();
} else {
foreach ($numrows as $i=>$row1 ) {
$reqid = $row1['friend_id'];
$user1 = $row1['friend_one'];
$datemade = $row1['friends_date_made'];
$datemade1 = strftime("%B %d, %y", strtotime($datemade));
$sql = "SELECT * FROM user WHERE uname=:user1 LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bindparam(":user1", $user1);
$stmt->execute();
$thumbrow = $stmt->fetchAll(PDO::FETCH_ASSOC);
$user1avatar = $thumbrow[$i]['avatar'];
$user1id=$thumbrow[$i]['user_id'];
if ($user1avatar =="") {
$user1pic = '<img src="img/avatardefault.png" height="50" style="float:left;" width="50" alt="'.$user1.'" class="user_pic">';
} else {
$user1pic = '<img src="../user/user/'.$user1id.'/'.$user1avatar.'" height="50" style="float:left;" width="50" alt="'.$user1.'" class="user_pic">';
}
$friend_requests .= '<li><div id="'.$reqid.'" float="right" class="friendrequests">
'. $user1pic .'
<div class="user_info '.$reqid.'" id="'.$reqid.'"><small>' . $datemade1 . '</small>
'.$user1.' is requesting your friendship<br /><br />
<button id="'.$reqid.'" name="'.$_SESSION['uname'].'" sess="'.$_SESSION['id'].'" class="accept_btn btn btn-warning">Accept</button><span class="show-spinner"></span> or
<button id="'.$reqid.'" name="'.$_SESSION['uname'].'" sess="'.$_SESSION['id'].'" class="reject_btn btn btn-warning">Reject</button>
</div>
</div><hr></li>';
}
}
You currently have data:{view:"view"}.
Which means that you are passing string 'view' in the body of your request.
Change it to something like:
function load_notifications(thisview=''){
var theData = {
view: thisview
}
$.ajax({
url: "notification/new_friends.php",
method: "POST",
data: theData,
dataType:"json",
success: function(data){

PHP Delete from javascript button click

I'm currently doing a PHP page that displays bans and also gives an option to unban users.
I can't seem to get the button to work and run the query to unban. Any help would be much appricated.
It currently does nothing and I'm also unsure as to how to display the Pnotice errors as I get
Uncaught TypeError: Cannot read property 'required' of undefined
Here is the function listed in lightcms.php for banlist.php;
function banListAll() {
global $db;
$getBanListAllQuery = "SELECT * FROM users_bans";
$getBanListAll = $db->query($getBanListAllQuery);
while ($showBanListAll = $getBanListAll->fetch_assoc()) {
echo "<tr id=\"banID" . $showBanListAll['id'] . "\">";
echo "<td>";
echo $showBanListAll['id'];
echo "</td>";
echo "<td>";
echo $showBanListAll['added_date'];
echo "</td>";
echo "<td>";
echo $showBanListAll['value'];
echo "</td>";
echo "<td>";
echo $showBanListAll['reason'];
echo "</td>";
echo "<td>";
echo $showBanListAll['expire'];
echo "</td>";
echo "<td>";
echo "<button data-id=\"" . $showBanListAll['id'] . "\" type=\"button\" class=\"btn btn-xs btn-danger btn-unban\">Unban</button>";
echo "</td>";
echo "</tr>";
}
}
Here is the javascript on banlist.php
<script type="text/javascript">
$(".btn-unban").click(function(){
var articleId = "#banID"+ $(this).attr("data-id");
var myData = "unban="+ $(this).attr("data-id"); //post variables
var formData = new FormData(this);
$.ajax({
type: "POST",
url: "./engine/post/unban.php",
dataType:"json",
data: myData,
success: processJson
});
function processJson(data) {
// here we will handle errors and validation messages
if (!data.success) {
if (data.errors.required) {
new PNotify({
title: 'Uh oh!',
text: data.errors.required,
type: 'error'
});
}
} else {
new PNotify({
title: 'Success!',
text: data.message,
type: 'success'
});
$(articleId).fadeOut("slow");
}
}
});
</script>
And here is the unban.php file
<?php
require_once $_SERVER['DOCUMENT_ROOT']."/admin_required.php";
$id = $_POST['id'];
$insert = "DELETE users_bans WHERE id = '$id'";// Do Your Insert Query
if($db->query($insert)) {
echo '{"success":true,"message":"User was unbanned!"}';
} else {
echo '{"error":true,"message":"Sorry this has not worked, try another time!"}';
}
//Need to work on displaying the error^
?>
Your JS looks for "errors.required" but your PHP sends "error" with no required.
Here's some code edits that (IMO) clean up the code. (any changes to sql are based on the assumption that you're using mysqli. that assumption based on the use of ->fetch_assoc()) Please consider atlest the change to unban.php as what you currently have is open to sql injection
Your new banListAll function:
function banListAll() {
global $db;
// don't use SELECT * if you can help it. Specify the columns
$getBanListAllQuery = "SELECT id, added_date, value, reason, expire FROM users_bans";
$getBanListAll = $db->query($getBanListAllQuery);
while ($showBanListAll = $getBanListAll->fetch_assoc()) {
$showBanListAll[] = "<button type='button' class='btn btn-xs btn-danger btn-unban'>Unban</button>";
// array_slice to get ignore the ['id']
echo "<tr data-banid='" . $showBanListAll['id'] . "'><td>" . implode("</td><td>", array_slice($showBanListAll,1)) . "</td></tr>";
}
}
New JS on banlist.php
<script type="text/javascript">
function processJson(data) {
// here we will handle errors and validation messages
if (data.error === false) {
row.fadeOut("slow");
}
// assuming we always get a "message"
new PNotify({
title : 'Uh oh!',
text : data.message,
type : 'error'
});
}
$(".btn-unban").click(function() {
var $this = $(this); // creating jQuery objects can be costly. save some time
var row = $this.closest('tr');
var banID = row.data('banid');
var postData = { unban: banID };
var formData = new FormData(this);
$.ajax({
type : "POST",
url : "./engine/post/unban.php",
dataType : "json",
data : postData,
success : processJson
});
});
</script>
And here is the unban.php file
<?php
require_once $_SERVER['DOCUMENT_ROOT']."/admin_required.php";
$id = $_POST['id'];
// Don't just concat variables that came from users into your DB queries.
// use paramterized queries. If $db is a mysqli connection
$insert = "DELETE FROM users_bans WHERE id = ?";// Do Your Insert Query
$deleteStmt = $db->prepare($insert);
// if id is a number change "s" to "i" below
$deleteStmt->bind_param("i",$id);
if($deleteStmt->execute()) {
echo jsonResult(false,"User was unbanned!");
} else {
echo jsonResult(true,"Sorry this has not worked, try another time!");
}
// add this function to return results to your JS functions
// should make it harder to put "errors" instead of "error" ;)
function jsonResult($hasErrors, $msg) {
return json_encode(array("error"=>$hasErrors,"message"=>$msg));
}
and just in case you thought unban.php was getting unnecessarily long, here it is without comments
<?php
require_once $_SERVER['DOCUMENT_ROOT']."/admin_required.php";
$id = $_POST['id'];
$insert = "DELETE FROM users_bans WHERE id = ?";// Do Your Insert Query
if ($deleteStmt = $db->prepare($insert)) {
$deleteStmt->bind_param("i",$id);
if($deleteStmt->execute()) {
echo jsonResult(false,"User was unbanned!");
} else {
echo jsonResult(true,"Sorry this has not worked, try another time!");
}
}
else {
print_r($db->error);
}
// the function should go into your general functions file
?>

inline update in mysql using jquery/php

I'm performing CRUD oprations using JQuery/Ajax and php/MySQL
i'm able to insert/select and delete data but i gotta stuck in edit/update. im pulling data into text box when i click on edit button but after editing when i click on save button unable to update in mysql db!!
Any help is Appreciated Thanks
html code
<span class="noedit name" idl='<?php echo $row->id;?>'>
<?php echo $row->url;?>
</span>
<input id="url1" name="url1" class="form-control edit name url1" 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 idc='<?php echo $row->id;?>' id="cancel" class='cancelEdit edit' href='#' style='display:none;'>CANCEL</a>
Jquery code
$('body').delegate('.edit','click',function(){
var IdEdit = $(this).attr('ide');
alert(IdEdit);
$.ajax({
url:"pages/feeds.php",
type:"post",
data:{
editvalue:1,
id:IdEdit
},
success:function(show)
{
$('#id').val(show.id);
$('#url1').val(show.url);
}
});
});
$('.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');
}
});
});
PHP Code
if(isset($_POST['editvalue']))
{
$sql = "select * from test where id='{$_POST['id']}'";
$row = mysql_query($sql);
$rows = mysql_fetch_object($row);
header("Content-type:text/x-json");
echo json_encode($rows);
exit();
}
if(isset($_POST['update']))
{
$sql = "
update test
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';
}
}
I don't see an #id input in your code. is it there? I think the problem is here.
If this input exists, use the following tips:
Check if all values (id, url) are sended to your PHP script.
You can use console.log in Javascript or print_r, var_dump functions in PHP.
Change
$('.update').click(function(){
to
$('.saveEdit').click(function(){

Categories

Resources