I’m working on a homepage and will use an AJAX inline editing script for the admin to make it as simple as possible.
The script I’ve been using is this and it has almost everything I wanted from an inline editing script. My problem arises when I’m going to capture the new changes and send them to a PHP function which will update my database with those new changes.
I don’t have that much experience with AJAX and PHP together so I’m somewhat lost but I’ve tried a code I found:
$.ajax({
type: "POST",
url: "update_handler.php",
data: "newfieldvalue=" + newValue,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
The problem is that I don’t quite know how or where to implement this code or if it’s even the right code to use. To show you the code I’ve attached two txt documents:
Index.php.txt
And
Jquery.editableText.js.txt
In index.php.txt is the index page where it retrieves my data from the database and uses a bit of jQuery code. In the jQuery.editableText.js.txt is the concrete jQuery code. I guess that the PHP handler page is pretty much standard with taking the correct field and then update it in the database.
I have questions for you:
$menuID contains the id of something and you use it to fetch it from table by this ID. It's right?
If it's right you must pass this ID to the PHP handler page.
Example:
index.php:
<script type="text/javascript">
jQuery(function($){
$('h2.editableText, p.editableText').editableText({
newlinesEnabled: false
});
$.editableText.defaults.newlinesEnabled = true;
$('div.editableText').editableText();
$('.editableText').change(function(){
var newValue = $(this).html();
// important code:
$.ajax({
type: "POST",
url: "save.php",
data: { val : newValue, key:$(this).parent().tagName, id:$(this).parent().attr('class')},
success: function(msg){
alert( "Data Saved: " + msg );
}
});
});
});
</script>
and body part:
<body>
<div id="wrapper">
<div id="content">
<?php
$isnull = getContent($menuID, "title");
if ($isnull != "") {
echo "<h2 class=\"editableText\"><center><p>" . getContent($menuID, "title") . "</p></center></h2><br>";
} else {
null;
}
?>
<div class="editableText">
<p class="<?php echo $menuID?>"><?php echo getContent($menuID, "maincontent");?></p>
</div>
</script>
<?php
mysql_close($connection);
?>
and one more, save.php:
<?php
# content that you send from client; you must save to maincontent
$content=$_POST['val'];
# $from=='div' if it from maincontent or $from=='center' if it from title
$from=$_POST['key'];
# id of your post
$id=$_POST['id'];
#here you can save your content;
?>
As it says on the edit-in-page page you should be using that code within a script block. So you pretty much had it. The following should work (untested).
<script type="text/javascript">
jQuery(function($){
$('h2.editableText, p.editableText').editableText({
newlinesEnabled: false
});
$.editableText.defaults.newlinesEnabled = true;
$('div.editableText').editableText();
// bind an event listener that will be called when
// user saves changed content
$('.editableText').change(function(){
var newValue = $(this).html();
// do something
// For example, you could place an AJAX call here:
$.ajax({
type: "POST",
url: "update_handler.php",
data: "newfieldvalue=" + newValue,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
});
});
</script>
Related
i want to delete a row of data in my sql when delete button is pressed in xdk. i searched for some codes but still doesnt delete the data.
this is the php file (delete.php)
<?php
include('dbcon.php');
$foodid = $_POST['foodid'];
$query = "DELETE FROM menu WHERE id ='$foodid'";
$result=mysql_query($query);
if(isset($result)) {
echo "YES";
} else {
echo "NO";
}
?>
and now here is my ajax code.
$("#btn_delete").click( function(){
alert("1");
var del_id = $(this).attr('foodid');
var $ele = $(this).parent().parent();
alert("2");
$.ajax({
type: 'POST',
url: 'http://localhost/PHP/delete.php',
data: { 'del_id':del_id },
dataType: 'json',
succes: function(data){
alert("3");
if(data=="YES"){
$ele.fadeOut().remove();
} else {
alert("Cant delete row");
}
}
});
});
as you can see, i placed alerts to know if my code is processing, when i run the program in xdk. it only alerts up to alert("2"); . and not continuing to 3. so i assume that my ajax is the wrong part here. Im kind of new with ajax.
<?php
$sqli= "*select * from temp_salesorder *";
$executequery= mysqli_query($db,$sqli);
while($row = mysqli_fetch_array($executequery,MYSQLI_ASSOC))
{
?>
//"class= delbutton" is use to delete data through ajax
<button> Cancel</button>
<!-- language: lang-js -->
//Ajax Code
<script type="text/javascript">
$(function() {
$(".delbutton").click(function(){
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("id");
//Built a url to send
var info = 'id=' + del_id;
$.ajax({
type: "GET",
url: "deletesales.php",
data: info,
success: function(){
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
return false;
});
});
</script>
//deletesales.php
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_database = 'pos';
$db = mysqli_connect($db_host,$db_user,$db_pass,$db_database);
$id=$_GET['id']; <!-- This id is get from delete button -->
$result = "DELETE FROM temp_salesorder WHERE transaction_id= '$id'";
mysqli_query($db,$result);
?>
<!-- end snippet -->
A couple of things:
You should be testing using console.log() instead of alert() (imo)
If you open up your console (F12 in Google Chrome) do you seen any console errors when your code runs?
Your code is susceptible to SQL Injection, you will likely want to look into PHP's PDO to interact with your database.
Does your PHP file execute correctly if you change:
$foodid = $_POST['foodid'];
To
$foodid = 1
If number 4 works, the problem is with your javascript. Use recommendations in numbers 1 and 2 to diagnose the problem further.
Update:
To expand. There are a few reasons your third alert() would not fire. The most likely is that the AJAX call is not successful (the success handler is only called if the AJAX call is successful). To see a response in the event of an error or failure, you can do the following:
$.ajax({
url: "http://localhost/PHP/delete.php",
method: "POST",
data: { del_id : del_id },
dataType: "json"
})
.done(function( msg ) {
console.log(msg);
})
.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
More information on AJAX and jQuery's $.ajax can be found here
My "best guess" is a badly formatted AJAX request, your request is never reaching the server, or the server responds with an error.
I'm trying to show a specific div depending on the result of a SQL query.
My issue is that I can't get the divs to switch asynchronously.
Right now the page needs to be refreshed for the div to get updated.
<?php
//SQL query
if (foo) {
?>
<div id="add<?php echo $uid ?>">
<h2>Add to list!</h2>
</div>
<?php
} else {
?>
<div id="remove<?php echo $uid ?>">
<h2>Delete!</h2>
</div>
<?php
}
<?
<script type="text/javascript">
//add to list
$(function() {
$(".plus").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_add.php",
data: info,
success: function(data){
$('#add'+I).hide();
$('#remove'+I).show();
}
});
return false;
});
});
</script>
<script type="text/javascript">
//remove
$(function() {
$(".minus").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "ajax_remove.php",
data: info,
success: function(data){
$('#remove'+I).hide();
$('#add'+I).show();
}
});
return false;
});
});
</script>
ajax_add.php and ajax_remove.php only contain some SQL queries.
What is missing for the div #follow and #remove to switch without having to refresh the page?
"I'm trying to show a specific div depending on the result of a SQL query"
Your code doesn't seem to do anything with the results of the SQL query. Which div you hide or show in your Ajax success callbacks depends only on which link was clicked, not on the results of the query.
Anyway, your click handler is trying to retrieve the id attribute from an element that doesn't have one. You have:
$(".plus").click(function(){
var element = $(this);
var I = element.attr("id");
...where .plus is the anchor element which doesn't have an id. It is the anchor's containing div that has an id defined. You could use element.closest("div").attr("id") to get the id from the div, but I think you intended to define an id on the anchor, because you currently have an incomplete bit of PHP in your html:
<a href="#" class="plus" ?>">
^-- was this supposed to be the id?
Try this:
<a href="#" class="plus" data-id="<?php echo $uid ?>">
And then:
var I = element.attr("data-id");
Note also that you don't need two separate script elements and two document ready handlers, you can bind both click handlers from within the same document ready. And in your case since your two click functions do almost the same thing you can combine them into a single handler:
<script type="text/javascript">
$(function() {
$(".plus,.minus").click(function(){
var element = $(this);
var I = element.attr("data-id");
var isPlus = element.hasClass("plus");
$.ajax({
type: "POST",
url: isPlus ? "ajax_add.php" : "ajax_remove.php",
data: 'id=' + I,
success: function(data){
$('#add'+I).toggle(!isPlus);
$('#remove'+I).toggle(isPlus);
}
});
return false;
});
});
</script>
The way i like to do Ajax Reloading is by using 2 files.
The first: the main file where you have all your data posted.
The second: the ajax file where the tasks with the db are made.
Than it works like this:
in the Main file the user lets say clicks on a button.
and the button is activating a jQuery ajax function.
than the ajax file gets the request and post out (with "echo" or equivalent).
at this point the Main file gets a success and than a response that contains the results.
and than i use the response to change the entire HTML content of the certain div.
for example:
The jQuery ajax function:
$.ajax({
type: 'POST', // Type of request (can be POST or GET).
url: 'ajax.php', // The link to the Ajax file.
data: {
'action':'eliran_update_demo', // action name, used when one ajax file handles many functions of ajax.
'userId':uId, // Simple variable "uId" is a JS var.
'postId':pId // Simple variable "pId" is a JS var.
},
success:function(data) {
$("#div_name").html(data); // Update the contents of the div
},
error: function(errorThrown){
console.log(errorThrown); // If there was an error it can be seen through the console log.
}
});
The PHP ajax function:
if (isset($_POST['action']) ) {
$userId = $_POST['userId']; // Simple php variable
$postId = $_POST['postId']; // Simple php variable
$action = $_POST['action']; // Simple php variable
switch ($action) // switch: in case you have more than one function to handle with ajax.
{
case "eliran_update_demo":
if($userId == 2){
echo 'yes';
}
else{
echo 'no';
}
break;
}
}
in that php function you can do whatever you just might want to !
Just NEVER forget that you can do anything on this base.
Hope this helped you :)
if you have any questions just ask ! :)
ive been trying for hours to get this to work and havent moved a budge.
What im trying to do is send an url when a button is click, but without refreshing the page
php code of button:
echo 'Send';
jquery code:
<script type="text/javascript">
//Attach an onclick handler to each of your buttons that are meant to "approve"
$('approve-button').click(function(){
//Get the ID of the button that was clicked on
var id_of_item_to_approve = $(this).attr("id");
$.ajax({
url: "votehandler.php", //This is the page where you will handle your SQL insert
type: "POST",
data: "id=" + id_of_item_to_approve, //The data your sending to some-page.php
success: function(){
console.log("AJAX request was successfull");
},
error:function(){
console.log("AJAX request was a failure");
}
});
});
</script>
votehandler.php:
<?php
$data = $_POST['id'];
mysql_query("UPDATE `link` SET `up_vote` = up_vote +1 WHERE `link_url` = '$data'");
?>
Ive removed all the error checks from votehandler.php to try to get any response but so far nothing.
any advice is welcome, trying to understand jquery/ajax.
Two problems with your code:
The jquery selector isn't working. Correct is: 'a[class="approve-button"]'
The code should being wrapped within the jquery ready() function to make sure that the DOM (with the links) has already been loaded before the javascript code executes.
Here comes a working example:
$(function() { // wrap inside the jquery ready() function
//Attach an onclick handler to each of your buttons that are meant to "approve"
$('a[class="approve-button"]').click(function(){
//Get the ID of the button that was clicked on
var id_of_item_to_approve = $(this).attr("id");
$.ajax({
url: "votehandler.php", //This is the page where you will handle your SQL insert
type: "POST",
data: "id=" + id_of_item_to_approve, //The data your sending to some-page.php
success: function(){
console.log("AJAX request was successfull");
},
error:function(){
console.log("AJAX request was a failure");
}
});
});
});
i want to send all the input fields of the form to process/do_submitattendance.php,
where i can use the to store in the database.
However i am having trouble doing this.
My jQuery code is-
<script type="text/javascript">
$("#submitattendance").submit(function(){
var_form_data=$(this).serialize();
$.ajax({
type: "POST",
url: "process/do_submitattendance.php",
data: var_form_data,
success: function(msg){
alert("data saved" + msg);
});
});
</script>
submitattendance is the ID of the form element.
I'm guessing the form is submitting, and you'll have to prevent the default submit action:
<script type="text/javascript">
$(function() {
$("#submitattendance").on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url : "process/do_submitattendance.php",
data: $(this).serialize()
}).done(function(msg) {
alert("data saved" + msg);
});
});
});
</script>
var var_form_data=$(this).serialize();
is all i can find, or there must be an error in your code somewhere else. you can look in your chrome console to see if there is an error (f12). also add return false; to stop the form submitting itself.
Why don't you try to pass values through session?
By using session you can pass the values from one page to anyother pages you want.
the typical code looks like this:
Mainpage.php
<?php
session_start(); // You should start session
$_SESSION['UserName']="YourTextfield";
?>
SecondPage.php
<?php
session_start();
$var = $_SESSION['UserName'];
?>
After you saved the data...then you need reset the session
$_SESSION['UserName']="";
That's what I usually use. and I hope it will help you...
I've used jQuery to create a page where users can click on a cell in a table that says, "delete," and it will send an ajax request to delete that entry from a database based on the id of the cell and then it will alter the CSS to hide the cell.
I created a test page while I was creating/tweaking the jQuery code. This page works perfectly. Here is the code:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
(function( $ ){
$.fn.deleterow = function(event) {
if (!confirm('Are you sure you want to delete this student?')) {
return false;
}
var id = event.target.id;
$.ajax({
url: 'delete.php',
type: 'GET',
data: 'id=' + id,
});
$(this).parent().css('display', 'none');
}
})( jQuery );
});
</script>
</head>
<table border="1">
<tr>
<td>Cell 2, Row 2</td><td onclick="$(this).deleterow(event);" id="13376">delete</td>
</tr>
</table>
<html>
Now I'm working on getting the code to work in the actual page that it's going to be used in. This page has a short form where users can select their name and a date. This form sends an ajax request that returns the results in a div. The data that is returned is a table , and this is where I'm trying to get my function to work. This table has a tablesorter script attached to it and also my function attached to it.
The tablesorter still works fine, but nothing happens when I click the cell with "delete" in it. I used FireBug to look at the issue and it gives me the error, "TypeError: $(...).deleterow is not a function"
Here is the code for the main page where the user submits a form and where the result is loaded in a div:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript' src='jquery.tablesorter.js'></script>
<script type='text/javascript'>
$(document).ready(function()
{
$('#myTable').tablesorter();
}
);
</script>";
</head>
<body id="my-students">
<?php include 'header.php'; ?>
<?php include 'nav-tutoring.php'; ?>
<div id="content">
This is where you can view students whom you have assigned to tutoring.
<p>
You may change the way each column is sorted by clicking on the column header.
<p>
<b>Select your name and the date to view students you have assigned for that day.</b>
<form> My form is here; removed to make post shorter </form>
<script>
$('#submit').click(function()
{
$.ajax({
type: 'POST',
url: "mystudents.php",
data: $('#name').serialize(),
success: function(data) {
$("#list").empty();
$('#list').append(data);
}
});
return false;
});
</script>
<div id="list"></div>
Here is the code for the page that is inserted into the div underneath the form. This is the page where the tablesorter works, but I cannot get my function to work. I've also made sure that I include these script libraries in the head of the main page where this div is.
<script src='//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>
<script type='text/javascript' src='jquery.tablesorter.js'></script>
<script type='text/javascript'>
$(document).ready(function()
{
$('#myTable').tablesorter();
(function($) {
$.fn.deleterow = function(event) {
if (!confirm('Are you sure you want to delete this student?')) {
return false;
}
var id = event.target.id;
$.ajax({
url: 'delete.php',
type: 'GET',
data: 'id=' + id,
});
$(this).parent().css('display', 'none');
}
})(jQuery);
});
</script>
<table id='myTable' class='tablesorter' border="1">
<thead><tr><th>ID Number</th><th>Last</th><th>First</th><th>Tutoring<br>Assignment</th><th>Assigning Teacher</th><th>Delete?</th></tr></thead><tbody>
<?php
while($row = mysql_fetch_array($data)){
echo "<tr><td>".$row['id']. "</td><td>". $row['last']. "</td><td>". $row['first']."</td><td>". $row['assignment']."</td><td>". $row['assignteacher']."</td><td onclick='$(this).deleterow(event);' id='".$row['pk']."'>Delete</td></tr>";
}
?>
</tbody></table>
I've done many searches based on the error I'm getting, but I just can't seem to fix the problem. Any help would be greatly appreciated.
First it makes no sense to include the $.fn.deleterow = function(event) { inside the document.ready. You should move it outside of that method.
Personally I would change the code to not rely on the inline event handlers in the table. You are using jQuery, so utilize it. Use event bubling to your advantage.
Add it to the table level and listen for click events on the td's that have ids.
$("table tbody").on("click", "td[id]", function(e){
if (!confirm('Are you sure you want to delete this student?')) {
return false;
}
var id = this.id;
$.ajax({
url: 'delete.php',
type: 'GET',
data: 'id=' + id,
});
$(this).parent().css('display', 'none');
});
jsFiddle
Test if jQuery loaded in console (check for jQuery variable)...
You should wrap your code this way:
(function( $ ){
$(document).ready(function(){
$.fn.deleterow = function(event) {
if (!confirm('Are you sure you want to delete this student?')) {
return false;
}
var id = event.target.id;
$.ajax({
url: 'delete.php',
type: 'GET',
data: 'id=' + id,
});
$(this).parent().css('display', 'none');
}
});
})( jQuery );
But the most important is check if jQuery are loading correctly and solve it...
Hope it help
try rewriting to a usual javascript function
function deleterow(id) {...}
and in php
echo "<tr><td>".$row['id']. "</td><td>". $row['last']. "</td><td>". $row['first']."</td><td>". $row['assignment']."</td><td>". $row['assignteacher']."</td><td onclick='deleterow(".$row['id']. ")' id='".$row['pk']."'>Delete</td></tr>";
It's due to this:
<td onclick='$(this).deleterow(event);'
JavaScript can't see this as a function due to the enclosing ' '.
What I advise doing is this:
<td class='deleterow'>
then
$(body).on('click', '.deleteRow', function(event) {
$(this).deleterow(event);
});
You'd be better off binding those events using jQuery's handers instead of onclick, which is poor practice. Eg:
$('#myTable').on('click', 'td', function(e) {
$(this).deleterow(e);
});