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);
});
Related
I'm new in ajax. I have try to find solution but failed. I want to refresh MySQL query in every second but how? I have no idea how to do it so please help me.
CODE
$sql="SELECT * FROM `user`";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo $row['fname'];
echo $row['email'];
}
Try below
<div class="result"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function refresh_div() {
jQuery.ajax({
url:'YOUR PHP page url',
type:'POST',
success:function(results) {
jQuery(".result").html(results);
}
});
}
t = setInterval(refresh_div,1000);
</script>
You can use jQuery with $.ajax() to get data, setInterval() to call a function every x seconds and $.html() to insert your data into an element.
Here is an example :
setInterval(function(){ getUsers(); }, 1000);
function getUsers()
{
$.ajax({
url: 'myphppage.php',
type: 'post',
success: function(data) {
$('.htmlelement').html(data);
}
});
}
<div class="htmlelement">data will appear here</div>
.htmlelement is an HTML element (ex: a div with a class "htmlelement"), where your results will be inserted.
Brutal solution: set the meta refresh tag in HTML:
<meta http-equiv="refresh" content="1">
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 ! :)
I've been unable to get an ajax script to run for some time.
Basically, I need the user to select an option from one drop down box, then, based on what's selected, the second drop down box with populate accordingly based on a MySQL query.
My Script looks like
<script type="text/javascript">
$(function(){
$('select [name="front-size"]').change(function()
{
$.ajax({
url: '../functions/process.php',
type:'get',
data:{'value' : $(this).val()},
dataType:"html",
success: function(data) {
$("#sub").html(data);
}
});
});
});
</script>
My initial drop down box is populated by a MySQL query like so
<select name="front-size" onchange="ajaxfunction(this.value)">
<?php
$door_size = $db->prepare("SELECT DISTINCT door_size FROM doors WHERE door_model = '".$_SESSION['front_door']."'");
$door_size->execute();
while($row = $door_size->fetch(PDO::FETCH_ASSOC))
{
$size = $row['door_size'];
echo '<option value="'.$size.'">'.$size.'</option>';
}
?>
</select>
The second drop down box is empty
<select name="front-finish" id="sub" onchange="ajaxfunction(this.value)">
</select>
And process.php should do the next query based on what was previously selected (this works on its own)
<?php
session_start();
include ('config.php');
$parent = $_GET['parent'];
$update_option = $db->prepare("SELECT door_finish FROM doors WHERE door_model = '".$_SESSION['front_door']."' AND door_size = '".$parent."'");
$update_option->execute();
while($row = $update_option->fetch(PDO::FETCH_ASSOC))
{
$door_finishes = $row['door_finish'];
echo '<option value="'.$door_finishes.'">'.$door_finishes.'</option>';
}
?>
In Firebug, when I select my first drop down menu, this error is shown and I've been unable to solve it.
ReferenceError: ajaxfunction is not defined
ajaxfunction(this.value)
How can I fix this?
you are calling ajaxfunction but you haven't defined it anywhere in the code.
<script type="text/javascript">
$(function(){
$('select [name="front-size"]').change(function()
{
$.ajax({
url: '../functions/process.php',
type:'get',
data:{'value' : $(this).val()},
dataType:"html",
success: function(data) {
$("#sub").html(data);
}
});
});
});
function ajaxFunction(stuff){
//do ajax stuff here will fix the error
}
</script>
On a broader note, why are you calling that inline in your html (onchange=ajaxfunction(this.value)) when the same thing can be accomplished in your ready function?
<script type="text/javascript">
(function(){
$('select[name="first"]').change(function(){
//do stuff
});
$('select[name="second"]').change(function(){
//do other stuff
});
})
</script>
would be better
EDIT: check this jsfiddle for a working example http://jsfiddle.net/WF8CV/
I have been researching for the last two days, and have found nothing.
structure:
index.php:
<head>
<script type="text/javascript" src="JS/jquery-1.6.2.js"></script>
<script type="text/javascript" src="function.js"></script>
</head>
<body>
<div>
<div>Show</div> *-->if I click this link data loads into DIV below by function.js without reloading*
<div id="producten"></div> *-->testpage.php loads here perfect,
the code of testpage.php makes by while loop other links.
Here I want to click on a link to load next data in div id=information
without reloading the index.php so the data in the first DIV stay visible
and I dont know how to do that*
<div id="information"></div> *-->testpage2.php have to load data from sql in this DIV*
</div>
</body>
function.js:
$(document).ready(function() {
$(".testcat").click(function() {
var testid = $(this).attr("id");
var datastring = 'id='+ testid ;
$.ajax({
type: "POST",
url: "testpage.php",
data: datastring,
cache: false,
success: function(res) {
$('#producten').html("<div class='loading'><img src='IMG/loading.gif' /></div>")
.hide()
.fadeIn(2000, function() {
$('#producten').html(res);
})
}
});
return false;
});
});
testpage.php and testpage2.php are PDO code for sql data.
You'll want to attach your click handlers with on so that dynamically added content still has the same ajax handlers available to them:
Add whatever information is needed to differentiate one click from the next, ie
<a href='...' data-resultdiv='production'
Then, cleaning up your handler a bit: I assume you want the ajax request to go to the href of the link, and that you want to show "loading" immediately (instead of waiting for the request to complete).
Finally, to cancel the anchor's default behavior of browsing to the page referenced by the href, you can return false;
$(document).on("click", "a", function() {
var href = $(this).attr("href");
var successDiv = $(this).data("resultdiv");
$('#' + successDiv).html("<div class='loading'><img src='IMG/loading.gif' /></div>");
$.ajax({
type: "POST",
url: href,
data: datastring,
cache: false,
success: function(res) {
$('#' + successDiv).hide().html(res).fadeIn(2000);
}
}
return false;
});
And of course if you only want this to run for certain anchors, you can put a selector on your call to on
$(document).on("click", "a.someClass", function() {
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>