AJAX update MYSQL database using function called from HTML generated from PHP - javascript

I have a php page generating and displaying a table. for the last row in the table i want to display an image with an 'onclick' function attached. this will send the username for the selected row to a script that will use AJAX to update a database. The table displays fine but the AJAX is not working. my php to display the image is:
echo "<td> <img id='tblimg'
onclick='like('" . $row['Username'] . "')'
src='like.jpg' alt='like/dislike image'
width='80px' height='30px'></td>";
The javascript function is:
<script type="text/javascript" >
function like(user)
{
$.ajax(
url: "update.php",
type: "POST",
data: { 'username': user, 'liked': '1' },
success: function()
{
alert("ok");
}
);
}
</script>
And here is update.php:
<?php
$con=mysqli_connect("","sam74","********","sam74");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$Username = $_POST['username'];
$Liked = $_POST['liked'];
$sql = "UPDATE 'followers' SET 'Liked' = '$Liked' WHERE 'Username' = '$Username'";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>

There are some mistakes in this code, let me help you line by line.
echo "<td> <img id='tblimg'
onclick=\'like('" . $row['Username'] . "');\'
src='like.jpg' alt='like/dislike image'
width='80px' height='30px'></td>";
The javascript function is:
Escape your quotes for the onclick event first
function like(user)
{
$.ajax({
url: "update.php",
type: "POST",
data: { 'username': user, 'liked': '1' },
success: function()
{
alert("ok");
}
});
}
add { and } to the ajax call
Remove the quotes from table name and fields
$sql = "UPDATE followers SET Liked = '$Liked' WHERE Username = '$Username'";
in ajax success and after the function begins, you can always print a message to see if your function is being called, and if php script is returning some error, use an alert for that
UPDATE
success: function(data){
alert(data); // this will print you any php / mysql error as an alert
}
UPDATE 2
Write your onclick option like this.
echo "<img onclick=\"like('" . $row['Username']. "');\"
src='like.jpg' alt='like/dislike image'
width='80px' height='30px' />";

The jQuery.ajax() function expects an object to be passed; you need to use { and } to begin and end your object literal. What you currently have is invalid JavaScript syntax, if you checked your browser's developer tools you'd see an error indicating that. So:
$.ajax(
url: "update.php",
type: "POST",
data: {
'username': user,
'liked': '1'
},
success: function () {
alert("ok");
}
);
should be
$.ajax({ // added {
url: "update.php",
type: "POST",
data: {
'username': user,
'liked': '1'
},
success: function () {
alert("ok");
}
}); // added }

Related

Delete all data from MySQL table with button

I am currently trying to implement a 'Delete' button that clears a MySQL table of all its data. I am finding it much more difficult than the submit button was.
Researched examples all show how to do it by a row, but I just have a single 'Delete' button. I believe I am currently way off, as I was trying to come up with a solution based on the submit Ajax function.
Currently:
HTML
<button class="myButton" id="delete" type="delete">DELETE</button>
JavaScript (This is where my hangup is I think)
function deleteMessage() {
$.ajax({
type: 'POST',
url: 'info_message.php',
async: false,
//data: ,
success: function(response) {
if (response == "success") {
successPopup("Successfully deleted message");
}
else {
alert("Unable to delete message. " + response);
}
}
});
}
PHP (or here???)
if (isset($_POST['deleteMessage'])) {
$message = $_POST['message'];
// Deletes all records in Announcement table
$query = "DELETE from Announcement";
if ($dbc->query($query) === FALSE) {
echo "Error: " . $query . "<br>" . $dbc->error;
}
else {
echo "success";
}
exit();
}
You looking for post data which you're not passing with your ajax call. Specifically you need to add deleteMessage and message which is the 2 post variables you are trying to read in your php script. Something like below
$.ajax({
type: 'POST',
url: 'info_message.php',
async: false,
data: { deleteMessage: true, message:"insert what message you want to pass" } ,
success: function(response) {
if (response == "success") {
successPopup("Successfully deleted message");
}
else {
alert("Unable to delete message. " + response);
}
}
});
}

Inline CKEditor save to MySQL using AJAX/PHP

I have a few caption boxes that I want to be able to edit inline and to save these to my database to update a certain record in my table.
For some reason, nothing happens when I click the save button.. not even in the console.
It's just using jQuery at the moment, will I have to use AJAX for this?
If so any tips would be great to point me in right direction as I'm not familiar that much with AJAX.
Here is my code:
index.php
<div class="caption" id="caption1" contenteditable="true" style="min-height: 450px;">
<?php
$query3 = "SELECT * From (select * from ckeditor ORDER BY id DESC LIMIT 2) AS name ORDER BY id LIMIT 1";
$show = mysql_query($query3, $con);
while ($row = mysql_fetch_array($show))
{
echo $row['file'];
}
?>
</div>
<button type="button" id="save"><span>Save</span></button>
<script>
$(document).ready(function (e) {
$("#save").click(function (e) {
var data = CKEDITOR.instances.caption1.getData();
var options = {
url: "save.php",
type: "post",
data: { "editor" : encodeUriComponent(data) },
success: function (e) {
echo "Succesfully updated!";
}
};
}
});
</script>
</div>
save.php
<?php
$connection = mysql_connect("localhost", "", "");
$db = mysql_select_db("castle", $connection);
//Fetching Values from URL
$data = nl2br($_POST['caption1']);
//Insert query
$query ="INSERT INTO `ckeditor`(`file`) VALUES ('$data')";
echo "Form Submitted Succesfully";
mysql_close($connection);
?>
You need to send the data to the server like this;
$.ajax({
url: "save.php",
data: {
"editor" : encodeUriComponent(data)
},
error: function() {
//Error
},
success: function(data) {
//Success
},
type: 'POST'
});
Currently you are just creating an object called 'options'
Your code should look like this;
$("#save").click(function (e) {
var data = CKEDITOR.instances.caption1.getData();
$.ajax({
url: "save.php",
data: {
"editor" : encodeUriComponent(data)
},
error: function() {
//Error
},
success: function(data) {
alert('Success');
},
type: 'POST'
});
}
Just a side note, 'echo' doesn't work in js. You need to use 'alert()' or 'console.log()'

How to tell PHP which comments to show under the article with AJAX?

I am building a news page for my website but I'm stuck displaying the right comments with ajax...
commentsLoad.php
<?php
include('config.php');
$newsid = $_GET['newsid'];
$comments=array();
$commentsQuery = "SELECT * FROM comments
where fk_news like ".$newsid;
$result = $conn->query($commentsQuery);
if($result->num_rows>0){
while($row = $result->fetch_assoc()){
$comments[]=array('id' => $row['id'], 'name' => $row['cnick'], 'text' => $row['ctext'], 'date' => $row['cdate']);
}
}
//header('Content-type: application/json');
echo json_encode($comments);
exit;
?>
I dont know how to pass the right 'NEWSID'.
Website picture: http://prntscr.com/8nwy8k
How I want to pass that ID to the SQL Query
$.ajax({
type: 'GET',
url: commentsUrl,
dataType: "json",
data:{newsid:'1'},
success: function(comments){
//console.log(komentarji);
$.each(comments, function(i, komentar){
addComment(komentar);
})
},
error: function(e){
console.log(e);
}
});
So right now if I change the line data:{newsid:'1 or 2 or 3...'} I get the comments I want, but I dont know how to get that ID into a variable.
You can use onClick event for this.
Explanation:
Comment link will look as follows
Comments
Then you can have a fucntion in your JQuery code to pass it to PHP file.
function getComments(article_id)
{
var artid = article_id;
$.ajax({
type: 'POST',
url: commentsUrl,
dataType: "json",
data:{newsid: artid},
success: function(comments){
$.each(comments, function(i, komentar){
addComment(komentar);
})
},
error: function(e){
console.log(e);
}
});
}
Try set onclick function in the comment link.
<a href="javascript:void(0)" onclick='myfunction <?php echo newsid ?>'Comment</a>
Get the newsid form the link.
<script>
function myfunction(newsid){
$.ajax({
type: 'GET',
url: commentsUrl,
dataType: "json",
data:{newsid:newsid},
success: function(comments){
//console.log(komentarji);
$.each(comments, function(i, komentar){
addComment(komentar);
})
},
error: function(e){
console.log(e);
}
});
}
</script>
Get the newid from commenntsUrl page.

How to get ID from DB if user enters INT to text input using Ajax/PHP?

I'm running a database with itemID's and a shelfnumber for every itemID..
As the user enters an itemID I want it to run through my database to get the shelfnumber using Ajax/PHP. Then post the shelfnumber back so the user can see where to find the item. (The items are in a room and are marked with unique ID's and shared shelfnumbers.) I need to use the onChange method (or anything similar) beacuse I want it to work like a tip/search engine. In other words automatic..
I'm totally new to ajax and I can't seem to get this to work at all.. No result is given and i'm at a roadblock right now.. Any form of help will be very appreciated
HTML
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
<script type="text/javascript">
$('#target').change(function() {
$.ajax({
url: 'shelfid.php',
type: 'POST',
dataType: 'JSON',
data:{
itemID: $(this).val()
},
success:function(response) {
alert("Item: "+response.itemID+", Shelf: "+response.Hyllplacering);
}
});
});
</script>
</head>
<body>
<a>Enter Item ID 1:</a>
<input id="target" type="text" name="itemID" required />
<div id="hyllplacering">ENTER Shelfnumber here: </div>
</body>
</html>
PHP
<?php
$con = mysql_connect("localhost", "root", "") OR die(' Could not connect');
$db = mysql_select_db('book1', $con);
$itemID = filter_input(INPUT_POST, 'itemID', FILTER_VALIDATE_INT);
$query = "SELECT Hyllplacering from booking WHERE itemID = $itemID";
$result = mysql_query($query);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo json_encode(array('itemID' => $itemID, 'Hyllplacering' => $row['Hyllplacering']));
?>
JavaScript is executed as soon as it is encountered. You bind the Event to an Element before it is available.
You need to wrap the script in a document.ready body.
As the other answers mentioned you want to use the success callback instead of done.
<script>
$(document).ready(function(){
$('#target').change(function() {
$.ajax({
url: 'shelfid.php',
type: 'POST',
dataType: 'JSON',
data:{
itemID: $(this).val()
};
})
.success(function(response) {
alert("Item: "+response.itemID+", Shelf: "+response.Hyllplacering);
});
});
});
</script>
You may add a sentence in AJAX function
$.ajax({
url: 'shelfid.php',
type: 'POST',
dataType: 'JSON',
data:{
itemID: $(this).val()
};
success:function(data){
console.info(data);
}
})
to monitor what your PHP responsed, it's more easy to check what's wrong.
I think you incorrect to use the done method of the Ajax object. I am pretty sure you wont have your response available in that scope. Try to do it like..
$('#target').change(function() {
$.ajax({
url: 'shelfid.php',
type: 'POST',
dataType: 'JSON',
data:{
itemID: $(this).val()
},
success:function(response) {
alert("Item: "+response.itemID+", Shelf: "+response.Hyllplacering);
},
error:function(response){
alert('error '+response);
};
})
});

Return the output of html id to php string

I like to make an advertisement base on the visitor state/region. And also to display language based on visitor country.
I am trying to get data from this website and works well in ( only displaying the output) :
jQuery.ajax( {
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
// example where I update content on the page.
jQuery('#city').html(location.city);
jQuery('#region-code').html(location.region_code);
jQuery('#region-name').html(location.region_name);
jQuery('#areacode').html(location.areacode);
jQuery('#ip').html(location.ip);
jQuery('#zipcode').html(location.zipcode);
jQuery('#longitude').html(location.longitude);
jQuery('#latitude').html(location.latitude);
jQuery('#country-name').html(location.country_name);
jQuery('#country-code').html(location.country_code);
}
} );
of course this will give the visitor state data on browser :
<div id="region-name"></div>
Problems :
How can I get the id output save in php string.
I want to ave it to database using PDO prepare statement.
I have tried to save it by doing:
$state='<div id="region-name"></div>';
$pages->testsavestate($state); // save to database PDO
public function testsavestate($state) {
$ses_id = session_id();
$country='mycountry';
$query = $this->db->prepare("INSERT INTO `visitors`(`session`, `country`, `state`) VALUES
(?,?,?)");
$query->bindValue(1, $ses_id);
$query->bindValue(2, $country);
$query->bindValue(3, $state);
try{
$query->execute();
}catch(PDOException $e){
die($e->getMessage());
}
}
It didn't save the state result, but only the above the tag.
Thanks
In order for that data to travel from your first AJAX call to get location values. You can also call another ajax on top of that to your PHP processing. Consider this example:
jQuery.ajax( {
url: '//freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
jQuery('#city').html(location.city);
jQuery('#region-code').html(location.region_code);
jQuery('#region-name').html(location.region_name);
jQuery('#areacode').html(location.areacode);
jQuery('#ip').html(location.ip);
jQuery('#zipcode').html(location.zipcode);
jQuery('#longitude').html(location.longitude);
jQuery('#latitude').html(location.latitude);
jQuery('#country-name').html(location.country_name);
jQuery('#country-code').html(location.country_code);
// after your .html() below
// after your successful ajax outside, call your php file
var country = location.country_name;
var state = location.region_name;
// call your php file
jQuery.ajax({
url: 'index.php', // <-- name of the php file that will handle such request
type: 'POST',
dataType: 'JSON',
data: { country: country, state: state },
success: function(response) {
alert(response);
}
});
}
});
Then on your php file, process the values
if(isset($_POST['save'])) {
$country = $_POST['country'];
$state = $_POST['state'];
$ses_id = session_id();
$query = $this->db->prepare("INSERT INTO `visitors`(`session`, `country`, `state`) VALUES (?,?,?)");
$query->bindValue(1, $ses_id);
$query->bindValue(2, $country);
$query->bindValue(3, $state);
try {
$query->execute();
if($query->rowCount() > 0) {
echo "Save complete!";
exit;
}
} catch(PDOException $e){
die($e->getMessage());
}
}

Categories

Resources