Inline CKEditor save to MySQL using AJAX/PHP - javascript

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()'

Related

Making clickable result list from Bootstrap typeahead and JSON

I want to make the result list for my Bootstrap typeahead list clickable and if the user clicks on any of the items in the dropdown list it will be redirected to the url [on my site, not external links] of the selected item. I made my changes regarding this Stackoverflow topic: jquery autocomplete json and clickable link through
The problem is, that I'm not into JS and Jquery and I can't tell why I get this error (Firefox Firebug Console output). I get this error everytime I enter any letter in my input textbox:
TypeError: it.toLowerCase is not a function bootstrap3-typeahead.min.js (1. line, 3920. column)
I see that the results of my PHP seems okay, so it must be something in the jQuery statement...
This is my result from the PHP:
[{"name":"TEXT-ONE","url":"\/textone-postfix"},{"name":"TEXT-TWO","url":"\/texttwo-postfix"},{"name":"TEXT-THREE"
,"url":"\/textthree-postfix"}]
This is my JQuery code:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});
This is my PHP code:
<?php
require_once('../config/config.php');
require_once('../functions/functions.php');
require_once('../config/db_connect.php');
$query = 'SELECT name_desc FROM tbl_name ';
if(isset($_POST['query'])){
$query .= ' WHERE LOWER(name_desc) LIKE LOWER("%'.$_POST['query'].'%")';
}
$return = array();
if($result = mysqli_query($conn, $query)){
// fetch object array
while($row = mysqli_fetch_row($result)) {
$array = array("name" => $row[0], "url" => "/" . normalize_name($row[0])."-some-url-postfix");
$return[] = $array;
}
// free result set
$result->close();
}
// close connection
$conn->close();
$json = json_encode($return);
print_r($json);
?>
Can someone please help me what could be the problem here?
Thank you very much!
The problem was that the displayText wasn't defined:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
displayText: function(item) {
return item.value
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});

How to use jQuery to get variable from PHP

I am trying to get data from MySQL using ajax and jQuery. Right now, the only thing being returned is "0". Here is my PHP function:
function dallas_db_facebook_make_post () {
global $wpdb;
$query = "SELECT * FROM wp_dallas_facebook WHERE time > NOW() ORDER BY time LIMIT 1";
$results = $wpdb->get_results($query, ARRAY_A);
foreach($results as $result) {
$fbpost = $result['text'];
}
}
Here is my jQuery function:
function send_fb_post() {
jQuery.ajax({
type: "GET",
url: my_ajax.ajaxurl,
data: {
'action': 'dallas_db_facebook_make_post'
},
beforeSend: function() {
},
success: function(data){
console.log(data);
},
error: function(){
},
});
};
You are not getting anything, because you are not printing/echoing anything.
What happens if you try
foreach($results as $result) {
echo $fbpost = $result['text'];
}
You code is not working because you are not print anything on server side. so you can small change in your code like below.
jsonencode is use to return an array of data.
function dallas_db_facebook_make_post () {
global $wpdb;
$query = "SELECT * FROM wp_dallas_facebook WHERE time > NOW() ORDER BY time LIMIT 1";
$results = $wpdb->get_results($query, ARRAY_A);
$fbpost = array();
foreach($results as $result) {
$fbpost = $result['text'];
}
echo json_encode($fbpost);
exit;
}
in response you json_encodeed data. You can decode and use this data using below function in response callback.
function send_fb_post() {
jQuery.ajax({
type: "GET",
url: my_ajax.ajaxurl,
data: {
'action': 'dallas_db_facebook_make_post'
},
beforeSend: function() {
},
success: function(data){
console.log(jQuery.parseJSON( data ));
},
error: function(){
},
});
};

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);
};
})
});

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

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 }

Categories

Resources