First time AJAX attempt.....
I am attempting to update a based on a selection made with a button.
I am currently just alerting the ID back, as that is all I can figure out what to do.
Is it possible to put the file my_page.php into the div with class "populated_info"?
Then when I press a different button, the page will function will run again, and populate the div with the new result. I have the my_page.php already built and running based on the ID, just can't get it to render in the correct place.
HTML:
<form name="gen_info">
<div class="body">
<div class="row">
<div class="col-md-2">
<table width="100%" class="border_yes">
<tr>
<td>
Last Name, First Name
</td>
</tr>
<?php
$result = mysqli_query($conn,"SELECT * FROM general_info");
while($row = mysqli_fetch_array($result))
{
$CURRENT_ID = $row['ID'];
$firstName = $row['firstName'];
$lastName = $row['lastName'];
?>
<tr>
<td>
<button type="button" class="btn btn-default custom" onclick="function1('<?php echo $CURRENT_ID;?>')"><?php echo $lastName.', '.$firstName; ?></button>
<!-- button that will run the function -->
</td>
</tr>
<?php
}
?>
</table>
</div>
<div class="col-md-10 populated_info"> <!-- WHERE I WOULD LIKE THE UPDATED INFORMATION -->
</div>
</div>
</div>
</form>
AJAX:
<script>
function function1(ID) {
$.ajax({
type: "POST",
url: "functions/my_page.php",
data: "ID="+ID,
success: function(resp){
alert(resp); //how to get this to put the page back into the right spot?
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
Your approach:
With regards to your button, I'd suggest separating the inline Javascript handler to keep your HTML and Javascript separate. I'll use a custom data attribute to store the ID here:
<button type="button" class="btn btn-default custom mybutton" data-id="<?php echo $CURRENT_ID;?>">
<?php echo $lastName . ', ' . $firstName; ?>
</button>
Then jQuery:
$('.mybutton').click(function() {
var ID = $(this).data('id');
function1(ID);
});
Your AJAX request:
You can shorten that whole function and use $.load() to get the data into your div:
function function1(ID) {
// Get the output of functions/my_page.php, passing ID as parameter, and
// replace the contents of .populated_info with it
$('.populated_info').load('functions/my_page.php', { ID: ID });
}
Doesn't look like you need a callback function here, but if you do you can put it in after the data parameter. A useful application of a callback here might be for your error handler. See here how to implement one.
An an aside, if you're just getting data, you should probably be using the GET HTTP method instead of POST.
if you successfully get the response from the server just replace alert(resp) with $('.populated_info').html(resp);
<script>
function function1(ID) {
$.ajax({
type: "POST",
url: "functions/my_page.php",
data: "ID="+ID,
success: function(resp){
$('.populated_info').html(resp);
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
Related
Loading image being displayed below the button of 1st result in while loop no matter which button is clicked from which result. For example, if I click submit button on the first result the loading image is displayed below it. That's okay. But when I click on the submit button of any other result except the first then also the loading image is displayed below the first result only and not below the submit button of that particular result.
<?php while($a = $stmt->fetch()){ ?>
<form method="post" action="">
<input type="hidden" value="<?php echo $mbs_id; ?>" class="memid">
<select class="validity" class="upgrade-valsel">
<?php while($mv = $mval->fetch()){ extract($mv); ?>
<option value="<?php echo $mv_id; ?>"><?php echo $mv_validity; if($mv_validity == 1){ echo " month"; }else{ echo " months"; } ?></option>
<?php } ?>
</select>
<input type="submit" value="Upgrade" class="submit">
<div class="center-align" style="margin-left: -20px"><img src="images/loading.gif" width="auto" id="loading-rent" style="margin-right: 0px; height: 40px"></div>
</form>
<?php } ?>
Script
$(document).ready(function() {
$(".submit").click(function () {
var dataString = {
memid: $(this).parent().find(".memid").val(),
memname: $(this).parent().find(".memname").val(),
validity: $(this).parent().find(".validity").val()
};
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to upgrade your membership to ' + dataString.memname + '?',
buttons: {
confirm: function () {
$.ajax({
type: "POST",
dataType: "json",
url: "upgrade-process.php",
data: dataString,
cache: true,
beforeSend: function () {
$("#submit").hide();
$("#loading-rent").show();
$(".message").hide();
},
success: function (json) {
setTimeout(function () {
$(".message").html(json.status).fadeIn();
$("#submit").show();
$("#loading-rent").hide();
}, 1000);
}
});
},
cancel: function () {
$.alert('<span style="font-size: 23px">Upgrade Cancelled!</span>');
}
}
});
return false;
});
});
Use .classes when it comes to generating a number of elements with a loop.
Use #id for unique elements.
To fix your code do the following:
add and fix any missing class
replace all id attributes in your code with class
use event delegation to listen for click event on any submit button. Read the following: jQuery API Docs on event delegation
On the following line you have set an id tag for the loading image; this has to be unique for each iteration of the while loop otherwise you get problems like you're experiencing. Either use unique ids and/or use javascript to select the nearest loading image to display.
<div class="center-align" style="margin-left: -20px"><img src="images/loading.gif" width="auto" id="loading-rent" style="margin-right: 0px; height: 40px"></div>
I have an code where it is supposed to delete the data without refreshing. the delete process works but i have to refresh to to remove the data.
heres my code please help me
Ajax:
$(function () {
$(".trash").click(function () {
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this post? This cannot be undone later.")) {
$.ajax({
type: "POST",
url: "delete.php", //URL to the delete php script
data: info,
success: function () {}
});
$(this).parents(".record").animate("fast").animate({
opacity: "hide"
}, "slow");
}
return false;
});
});
Here's my html:
<td style="padding-left: 23px">
<img class="photo" data-toggle="modal" data-target="#gallery<?php echo $photo; ?>" src="<?php echo $r1['photo']; ?>" />
<div class="hotel">
<button class="trash" id="<?php echo $r1['photo_id']; ?>" > <span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button>
</div>
</td>
If I hover the button to the image the .trash button will appear and if I click it the image must be deleted. help me please.
You can give a data image id attr to parent tr,
<tr data-image-id="<?php echo $r1['photo_id']; ?>">
After successful delete process (in your ajax success function) you can run code below.
$("tr[data-image-id="+del_id+"]").remove();
Your code works, maybe do you need show the complete html, or at least the classes ".record" to analyze the "error"
No need to add extra attribute for ID in table row(TR).
$('.glyphicon-remove').on('click',function() {
$(this).closest( 'tr').remove();
return false;
});
Try This:
function delete_value(id)
{
if(confirm('Are you sure you want to delete this?'))
{
// ajax delete data from database
$.ajax({
url : "<?php echo site_url('yoururl/del')?>/"+id,
type: "POST",
success: function(data)
{
$("tr[id="+id+"]").remove();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}
}
<button class="btn btn-danger" onclick="delete_value(<?php echo $row->id;?>)"><i class="glyphicon glyphicon-remove"></i></button>
<!--- add tr id --->
<tr id="<?php echo $row->id; ?>">
I have a PHP page which has two sections (top and bottom). The top section has a table where I have options to Edit the data.
Once the Edit button is pressed, the content is loaded at the bottom of page and the user can change the data.
Here is part of my PHP page:
<div id="product_entry_<?php echo $id?>" class="product_entry_<?php echo $id?>">
<tr>
<td><font size=2px><?php echo $date?></font></td>
<td><font size=2px><?php echo $ProductName?></font></td>
<td><font size=2px><?php echo $Category.' / '.$SubCategory?></font></td>
<td><font size=2px><?php echo $MRP.' / '.$Price?></font></td>
<td><button type="submit" class="btn btn-primary btn-xs" style="padding:2px 2px;font-size: 9px;line-height: 10px;" onClick="DirectPromoteSubmit(<?php echo $id?>)">Promote</button></td>
<td><button type="submit" class="btn btn-primary btn-xs" style="padding:2px 2px;font-size: 9px;line-height: 10px;" onClick="RePromoteSubmit(<?php echo $id?>)">Edit</button></td>
<td><button type="submit" class="btn btn-primary btn-xs" style="padding:2px 2px;font-size: 9px;line-height: 10px;" onClick="DelPromoteSubmit(<?php echo $id?>)">X</button></td>
</tr>
</div>
<!-- page where data is loaded -->
<div class="box box-warning" id="RePromoteReplace">
....some html content here...
</div>
Here is my Javascript:
function RePromoteSubmit(id){
//alert('got into Edit Promotions');
var dataString = "id="+ id;
alert(dataString);
if(dataString=='')
{
alert('Some Problem Occurred, Please try Again');
}
else
{
//alert('into post');
$.ajax({
type: "POST",
url: "SellerPanel/post_repromote.php",
data: dataString,
cache: false,
success: function(html){
//$("#tweet").val('');
//$("#preview").hide();
$("#RePromoteReplace").replaceWith(html);
alert('Product Successfully Loaded!!! Edit(Optional) & Click Promote Button in bottom section')
}
});
}return false;
}
Here is my PHP page which loads the bottom section - post_repromote.php:
<?php
include("../dbconnection.php");
include("session.php");
if(!isset($_SESSION))
{
session_start();
}
$id=$_POST['id'];
$query1=mysqli_query($con,"select promotiondata from sellerpromotions where id=$id");
while($row=mysqli_fetch_array($query1))
{
.....some code here.....
}
?>
<div class="box box-warning">
<div class="box-header">
<h3 class="box-title">Fill Product Details</h3>
</div><!-- /.box-header -->
<div class="box-body">
<!-- <form role="form " name="PromoteForm"> -->
<div>
<!-- text input -->
<table class="table">
....some data here from query..
</table>
<div class="box-header with-border">
<h3 class="box-title">Upload your Product Image</h3>
</div><!-- /.box-header -->
<div class="box-body no-padding">
<div id='preview'>
<?php if ($uploadid){ ?>
<img src=<?php echo "SellerPanel/uploads/".$imagename?> id="<?php echo $uploadid?>" alt="User Image" class='preview' style='width:340px;height:200px;border-color:black'/>
<?php }
?>
</div>
<?php
include ("index_photo.php");
?>
<!-- <span class="users-list-date">Yesterday</span> -->
</div><!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-primary" onClick="PromoteSubmit()">Promote</button>
</div>
</div>
</div><!-- /.box-body -->
</div><!-- /.box -->
<?php }
?>
The problem I'am facing:
I'am able to load the data when I press the Edit button first.
When I press it again, I'm not able to load the new data unless I refresh the page and click the Edit button again.
I tried to read the id in JS and printed it, I found that id is being passed correctly.
Any help would be very much appreciated.
Thanks in advance!
JS after using solution:
function RePromoteSubmit(id){
//alert('got into Edit Promotions');
var dataString = "id="+ id;
alert(dataString);
function getRandomInt() {
return Math.floor(Math.random() * Math.pow(10,6));
}
//var url = "SellerPanel/post_repromote.php?"+getRandomInt();
//alert ("url is: "+ url);
if(dataString=='')
{
alert('Some Problem Occurred, Please try Again');
}
else
{
//alert('into post');
$.ajax({
type: "POST",
url: "SellerPanel/post_repromote.php?rnd="+getRandomInt();
data: dataString,
cache: false,
success: function(html){
//$("#tweet").val('');
//$("#preview").hide();
$("#RePromoteReplace").replaceWith(html);
alert('Product Successfully Loaded!!! Edit(Optional) & Click Promote Button in bottom section')
}
});
}return false;
}
Try changing your callback to use .html() instead of replaceWith(): (in your original code)
success: function(html){
//$("#tweet").val('');
//$("#preview").hide();
$("#RePromoteReplace").html(html);
alert('Product Successfully Loaded!!! Edit(Optional) & Click Promote Button in bottom section')
}
I also recommend changing your selector to a class instead of an ID, you can do this by just adding an extra class in your HTML:
<div class="box box-warning promoReplace" id="RePromoteReplace">
and then updating the selector in your success callback:
$(".promoReplace").html(html);
Sidenote: For debugging, its usually easier to use console.log() instead of alert() (when using ajax, you usually would have the console open anyway)
Your AJAX response is getting cached by the browser due to some server setting or page header. Easiest way to disable this is to append some randomly generated parameter to your url every time you send a request.
The function getRandomInt will generate a 6 digit random number. If you want to have more/less digits, change the second argument passed to Math.pow.
function getRandomInt() {
return Math.floor(Math.random() * Math.pow(10,6));
}
//then, inside your ajax function, use:
url: "SellerPanel/post_repromote.php?rnd="+getRandomInt(),
I am trying to add a voting/poll panel in sidebar of my HTML/PHP/MySQL website.
Scenario
I have list of plans for separate places in MySQL Database Table, when some one search for the place they will also see list of plans decided for that place. They can vote for what plan to be executed next in that place.
What I have worked so far?
I am able to fetch plans for specific places when viewers search for any place.
Code used:
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
Vote next plan
</h3>
</div>
<div id="voting">
<form>
<div class="panel-body">
<ul class="list-group">
<?php
while ($planvote = mysql_fetch_array($planresultv)) {
echo '<li class="list-group-item">';
echo '<div class="radio">';
echo '<label>';
echo '<input type="radio" name="optionsRadios">';
echo $planvote['plan_name'];
echo '</label>';
echo '</div>';
echo '</li>';
}
?>
</ul>
</div>
<div class="panel-footer">
<button type="button" class="btn btn-primary btn-sm">
Vote</button>
View Result
</div>
</form>
</div>
Screenshot
Now, I have a database table with columns
|sn|plan_name|poll|
|1 |Path way |0 |
How can I add/change value of poll in some on selects radio button on the voting form and clicks vote.
P.S. You can answer ideas or help me with code if you want to.
You could add a value to you radio button:
echo '<input type="radio" name="optionsRadios">';
After you did this, you could make an ajax call where you update the results by getting the value of the radiobutton. Make sure to add an id to your button:
<button id='vote_button' type="button" class="btn btn-primary btn-sm">
Ajax call:
$("#vote_button").click(function(){
if($("input[type='radio'][name='optionsRadios']:checked").length > 0){
var chosenvalue = $("input[type='radio'][name='optionsRadios']:checked").val();
var dataString = 'paramX=' + chosenvalue;
$.ajax({
type: "POST",
url: "yourfile.php",
data: dataString,
cache: false,
success: function (html) {
}
});
}
});
In your ajax call you can update the voting system by using some PHP code and an SQL like where $val = the passed value to your ajax:
UPDATE your_table SET poll = poll + 1 WHERE sn = $val
But you will probably have to add way more coding than this, else people can just spam the voting system..
Solution
JS/Ajax Script
<script src="js/jquery-latest.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
$("#vote_button").click(function(){
if($("input[type='radio'][name='optionsRadios']:checked").length > 0){
var chosenvalue = $("input[type='radio'][name='optionsRadios']:checked").val();
var dataString = 'paramX=' + chosenvalue;
$.ajax({
type: "POST",
url: "yourfile.php",
data: dataString,
cache: false,
success: function (html) {
console.log(html);
$('.notice').html(html);
},
error: function(err) {
console.log(err);
}
});
}
});
HTML/ PHP
<div id="voting">
<form>
<div class="panel-body">
<ul class="list-group">
<?php
while ($planvote = mysql_fetch_array($planresultv)) {
echo '<li class="list-group-item">';
echo '<div class="radio">';
echo '<label>';
echo '<input type="radio" name="optionsRadios" value="'.$planvote['sn'].'">';
echo $planvote['vdc_PlName'];
echo '</label>';
echo '</div>';
echo '</li>';
}
?>
</ul>
</div>
<div class="panel-footer">
<button id="vote_button" type="button" class="btn btn-primary btn-sm">
Vote</button>
View Result
</div>
</form>
Finally it update the value of poll in database table.
Up to this point, I've been using a textarea as the main input for a form. I've changed it to use a contenteditable div because I wanted to allow some formatting.
Previously, when I had the textarea, the form submitted fine with Ajax and PHP. Now that I've changed it to use a contenteditable div, it doesn't work anymore and I can't tell why.
HTML:
<form>
<div name="post_field" class="new-post post-field" placeholder="Make a comment..." contenteditable="true"></div>
<input name="user_id" type="hidden" <?php echo 'value="' . $user_info[0] . '"' ?>>
<input name="display_name" type="hidden" <?php echo 'value="' . $user_info[2] . '"' ?>>
<ul class="btn-toggle format-post">
<button onclick="bold()"><i class="fa-icon-bold"></i></button>
<button onclick="italic()"><i class="fa-icon-italic"></i></button>
</ul>
<div class="post-buttons btn-toggle">
<button class="btn-new pull-right" type="submit">Submit</button>
</div>
</form>
JQuery Ajax:
$(document).ready(function() {
$(document).on("submit", "form", function(event) {
event.preventDefault();
$.ajax({
url: 'php/post.php',
type: 'POST',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
alert(data.message);
}
});
});
});
PHP (post.php): Just your typical checks and echo a message back. This is just a snippet of the code.
<?php
$user_id = $_POST["user_id"];
$display_name = $_POST["display_name"];
$post_content = $_POST["post_field"];
$array = array('message' => $post_content);
echo json_encode($array);
?>
For some reason, it's not sending back the post content anymore ever since I added the contenteditable div.
Please help!
The contents of the div are not serialized. You would have to add them on your own.
var data = $(this).serialize();
data += "post_field=" + encodeURIComponent($("[name=post_field]").html());