Working on a project where I want to be able to delete a dynamic record using jQuery and PHP. I already have the option for users to add a record dynamically it is just getting the delete option to work. While I am trying to develop this function I have set the Delete to INSERT. Where I am having trouble is getting the value from the hidden field to delete-class.php (the bottom script). Below I have posted the code:
<form id="frmDelete" method="post" action="delete-class.php">
<input id="btnSubmit" type="submit"/>
<ul id="class">
<?php
//this is being loaded from a different page and is here just to reference the fields
while ($row = mysql_fetch_array($result)) {
echo '<li id="liClass" class="ui-widget"><img src="trash-can-icon.png" id='.$row["id_distance_class"].' class="delete"/>' . $row["class_section"] . '<input type="hidden" name="hdid" id="hdid" value="'.$row["id_distance_class"].'"/></li>';
?>
</ul>
</form>
<script>
$(function() {
$(".delete").click(function() {
$('#load').fadeIn();
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = id ;
// console.log(id);
$.ajax({
type: "POST",
url: "delete-class.php",
data: $(this).serialize(),
cache: false,
success: function(){
commentContainer.slideUp('slow', function() {$(this).remove();});
$('#load').fadeOut();
}
});
return false;
});
});
</script>
//this is the delete-class.php
$results = mysql_query("INSERT INTO distance_class (class_section) VALUES ( '".$_POST['hdid']."' ) ");
The problem is you're not passing this information in your AJAX request. You're passing
data: $(this).serialize()
...presumably thinking this points to the form. It doesn't; it points to the deletion button clicked, since this code is running in the button's event handler callback.
Change the above to target the form.
Related
I need to use a localStorage value in a PHP file to update values in my database. I know that I need ajax to achieve this, I can't get it to work.
My localStorage item is named option and it exists (checked in browser and stored the value in a div)
$(document).ready(function(){
$.ajax({
type: "POST",
url: "activity.php",
data: { storageValue: localStorage.getItem('option') },
success: function(data){
alert('success');
}
});
});
PHP Example:
$option = $_POST['storageValue'];
mysql_query("...SET x = '".$option."'...");
echo 'Update complete';
I dont see any post data nor do I get a response.
Thank you!
Your page:
<form>
<input type="hidden" value="thedatayouwanttopost" id="option"/>
</form>
<script src="Your_Js_File.js"></script>
Your JS file:
document.getElementById('option').submit(); // This submits the form
var storageValue = $('#option').val(); // This gets the value of the form once it has been posted to the .php file
$(document).ready(function(){
$.ajax({
type: "POST",
url: "activity.php",
data: { storageValue:storageValue },
success: function(data){
alert('success');
}
});
return false; // This stops the page from refreshing
});
Your PHP file to callback the data to AJAX and display the alert (activity.php):
...
$option = $_POST['storageValue']; // This is the post value of your hidden input on your page
mysql_query("...SET x = '".$option."'...");
?><input type="hidden" id="option" value="<?php echo $option; ?>"><?
// The input above posts the value of 'option' on your page back to your Ajax and spits out the request.
...
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 have this jQuery which updates the DB on blur. It works fine except I want the code to show the current DB value after it got updated. There is a value in the database the amount in the field will be added to that and it gets updated. The only way to see that now is to refresh the page each time something gets updated.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
// JQUERY: Plugin "autoSumbit"
(function($) {
$.fn.autoSubmit = function(options) {
return $.each(this, function() {
// VARIABLES: Input-specific
var input = $(this);
var column = input.attr('name');
// VARIABLES: Form-specific
var form = input.parents('form');
var method = form.attr('method');
var action = form.attr('action');
// VARIABLES: Where to update in database
var where_val = form.find('#where').val();
var where_col = form.find('#where').attr('name');
// ONBLUR: Dynamic value send through Ajax
input.bind('blur', function(event) {
// Get latest value
var value = input.val();
// AJAX: Send values
$.ajax({
url: action,
type: method,
data: {
val: value,
col: column,
w_col: where_col,
w_val: where_val
},
cache: false,
timeout: 10000,
success: function(data) {
// Alert if update failed
if (data) {
document.getElementById("notice").innerHTML="Error, NO UPDATE";
}
// Load output into a P
else {
$('#notice').text('Updated');
$('#notice').fadeOut().fadeIn();
}
}
});
// Prevent normal submission of form
return false;
})
});
}
})(jQuery);
// JQUERY: Run .autoSubmit() on all INPUT fields within form
$(function(){
$('#ajax-form INPUT').autoSubmit();
});
</script>
HTML stuff
<label>Total:</label>
<input name="company" value="<?php echo $row['total'] ?>" />
<label>Tax-in:</label>
<input name="lastname" value="<?php echo $row['taxin'] ?>" />
After your PHP file inserts the row into the database, have it SELECT the new value from the database and echo it back on the AJAX response to jQuery. Then use jQuery to populate that new value wherever you want it to go.
HTML:
<select id="single">
<option>Single</option>
<option>Single2</option>
</select>
<input value="load()" id="test" type="submit" />
<div id="result"></div>
Script:
$.ajaxSetup ({
cache: false
});
var loadUrl = "http://localhost/test/process.php";
$("#test").click(function(){
$("#result").load(loadUrl, "content=sd345f"+singleValues);
});
function displayVals() {
var singleValues = $("#single").val();
}
$("select").change(displayVals);
displayVals();
That is my current code, I'm new to jquery and what i wanna ask is how do i make the var singleValues update when i choose a list from a dropdown and append it as a get value when i click on submit?
ANd here's process.php BTW:
<?php file_put_contents('1.txt',$_GET['content']); ?>
If I understand right, you want to load the result when you click on the button.
Try the following code:
$("#test").click(function(){
// get the selected value
var value = $("#single option:selected").val();
// GET to server
$.ajax({
type : "GET",
url : "http://localhost/test/process.php",
data : {
"content" : value
},
success : function(response){
$("#result").html(response);
}
});
// Don't use default submit function
return false;
});
More information about $.ajax http://api.jquery.com/jQuery.ajax/
i have a form in which if the user enters the search query, its parameter should be passed through jquery and after getting the results it should load the results in the div container. since i'm not very well-versed with jquery, how would i do this?
html:
//currently the data is being displayed on pageload:
$(document).ready(function() {
$("#bquote").load("quotes_in.php")
});
$(".bsearch")
.keydown(function() {
//pass the parameter to the php page
//display in div #bquote
});
<!-- Begin Search -->
<div id="search" style="display:none;">
<input type="text" class="bsearch" name="search" value="Search" />
</div>
<!-- End Search -->
php [using OOP]:
if (isset($_POST["search"]))
{
$quotes->searchQuotes();
}
php class:
$search = $_POST['search'];
$sql = "SELECT * FROM thquotes WHERE cQuotes LIKE '%"
. mysql_real_escape_string($search) ."%' ORDER BY idQuotes DESC";
try {
$query = $this->_db->prepare($sql);
$query->execute();
if(!$query->rowCount()==0)
{
while($row = $query->fetch())
{
echo $this->formatSearch($row);
}
I would do in that way:
$(".bsearch").keydown(function() {
//create post data
var postData = {
"bsearch" : $(this).val(),
"anotherParam" : "anotherValue"
};
//make the call
$.ajax({
type: "POST",
url: "yourAjaxUrl.php",
data: postData, //send it along with your call
success: function(response){
alert(response); //see what comes out
//fill your div with the response
$("#bquote").html(response);
}
});
});
EDIT:
For putting a loader you need to check this here:
http://api.jquery.com/category/ajax/global-ajax-event-handlers/
And to show a loader image for example:
$("#loading").ajaxStart(function(){
$(this).show();
});
And to hide it when ajax call is complete:
$("#loading").ajaxComplete(function(){
$(this).hide();
});
If you want to go down the ajax route...
$(".bsearch").keydown(function() {
// Get the current input value
var value = $(this).val();
//pass the parameter to the php page
$.ajax({
type: "POST",
url: "some.php", // replace this with the right URL
data: "bsearch=" + value,
success: function(msg){
$("#search").html(msg);
}
});
});
Read up on jQuery.ajax() and if you turn that search box into a proper form, utilize jQuery.serialize()
Instead of using $_POST, you can use $_GET or $_REQUEST like the following:
var searchString = $(".bsearch").val();
$("#bquote").load("path_to_php_file.php?search="+searchString);
Then, in PHP, replace
$_POST
...with
$_GET