Thanks for reading.
I'm trying to improve so I'm doing an example project to improve. I made a simple. voting system. I have number of contents which displayed by php each of them have up or down vote button. by the way I use twitter bootstrap.
this is the html code:
<html>
<button type="submit" class="btn btn-mini upvote" id="'.$data['ContentID'].'">
<i class="icon-arrow-up"></i>
</button>
<span id="voteresponse">'.$data['VoteSum'].'</span>
<button type="submit" class="btn btn-mini downvote" id="'.$data['ContentID'].'">
<i class="icon-arrow-down"></i>
</button>
</html>
the problem is when I lick up button which is class="upvote" all other buttons does same thing. because the data populated by php there are many of them.
this is my javascript.
<script>
jQuery(document).ready(function($){
$('.upvote').click( function(event) {
event.preventDefault();
$("#voteresponse").html('');
var voteID = $(".upvote").first().attr("id");
$.ajax({
url: "/ajax.php?Page=votetitle",
type: "post",
dataType: "json",
data: {id : voteID},
success: function(data, textStatus){
if(data.success == 'true'){
$('#voteresponse').html(data.message);
return true;
}else{
$('#voteresponse').popover({
title: 'Hata!',
content: data.message
});
}
},
error:function(){
$('#voteresponse').popover({
title: 'error!',
content: 'Server error'
});
}
});
});
});
</script>
and the php code is just usual database request.
<?php
if ( $_SESSION['UserID'] <1 )
die( print_r(json_encode(array('success'=>'false', 'message'=>'error for user!'))) );
print_r(json_encode(array('success'=>'true', 'message'=>$_POST['id'])))
?>
you can see the action here. if you click one of them all other up arrows do same thing. also is this approach right?
thanks. best regards
Only the first one "responds" when you click any of them... This is likely because of var voteID = $(".upvote").first().attr("id"); The voteID should be something like $(this).attr('id'); instead.
Note that you need to recognize which button was clicked, you can use for example $(this).parent()... That will give you to the upper DOM level of the clicked button (div media isotope-item) and from there you can modify only the content of that div.
try changing
var voteID = $(".upvote").first().attr("id");
to this
var voteID = $(this).first().attr("id");
or
var voteID = $(this).attr("id");
Related
I have this button that sends the information to another php folder. but I want it to send but stay in the same page.
<button class="btn btn-outline-dark w-60"><?php echo "<td> <a href='carrinho.php?acao=adc&id=$PegaID'>Adicionar ao carrinho</a></td>";?></button>
I want it to send but stay in the same page.
You want to use AJAX.
You set your button to call a Javascript function. That Javascript function then launches the call to the URL: carrinho.php?acao=adc&id=$PegaID.
You can handle any returned data or just discard it. Usually, you would want to at least handle it so you can give the user feedback that the button was clicked and it accomplished what it was supposed to accomplish, or an error was generated.
Specifically, you will use XMLHttpRequest. Here's a link to a good write up to get you started.
Using XMLHttpRequest
You can use ajax to send data without referesh html page or change url.
ex:
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h2>Let AJAX change this text</h2>
<button type="button" onclick="loadDoc('$PegaID')">Change Content</button>
</div>
<script>
function loadDoc(PegaID) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "carrinho.php?acao=adc&id=PegaID", true);
xhttp.send();
}
</script>
</body>
</html>
This code send data using get method. We send PegaID to the javascript function and then send data and then showing the result in demo using change html.
Give your button an ID.
Remove your anchor.
Attach an ajax post to your button.
This is what your code should look like:
<button id="adicionar" class="btn btn-outline-dark" data-id="<?php echo $pegaID;?>">
Adicionar ao carrinho
</button>
<script>
$(document).ready(function(){
$("#adicionar").click(function(event){
let id = $(event.relatedTarget).data("id");
$.ajax({
type: "POST",
data: {id: id},
url: "another php.php"
});
});
});
</script>
If you're getting sent to another page just add event.preventDefault() above let id=$(event.relatedTarget).data("id")
It should look like:
<script>
$(document).ready(function(){
$("#adicionar").click(function(event){
event.preventDefault();
let id = $(event.relatedTarget).data("id");
$.ajax({
type: "POST",
data: {id: id},
url: "another php.php"
});
});
});
</script>
In "another php.php" you'll want to receive the id with $_POST['id'].
Something like $id = $_POST['id'];. Then you can do whatever you want with the id in "another php.php".
i searched a lot about this problem, but I didn't find a solution, yet.
At first a short description about my setup to make my problem clearer.
Settings.php Page with a Menu, where you can select different settings categories
By clicking on one menu point the corresponding loads by ajax and is displayed.
$('#content').load("http://"+ document.domain + "/domainhere/settings/menupoint1.php");
On the menupont1.php page I got a list with mysql data.
I implemented a "edit" button for each row - while clicking on the edit button, a boostrap modal appears with a form and the corresponding data filled in and ready to edit.
When i now click on "Save changes", the POST-Request is always empty.
To realize the form submit, I already tried several codes:
e.g.:
$.ajax({
type: "POST",
url: "php/form-process.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
}
}
});
or
$(function(){
$('#editform').on('submit', function(e){
e.preventDefault();
$.ajax({
url: url, //this is the submit URL
type: 'GET', //or POST
data: $('#editform').serialize(),
success: function(data){
alert('successfully submitted')
}
});
});
});
At the moment:
while($xy= $xysql->fetch_assoc()) {
<div class="modal fade" id="edit-<?php echo $xy["id"] ?>" [..]>
<button id="submit>" class="btn btn-default">Save</button>
</div>
<script>
$(function() {
$('button#submit').click(function(){
$.ajax({
type: 'POST',
url: './test2.php',
data: $('form#modal-form').serialize(),
success: function(msg){
$('#test').html(msg)
$('#form-content').modal('hide');
},
error: function(){
alert('failure');
}
});
});
});
</script>
Maybe someone here could help me out with this problem?
thank you very much :)
I've set up a minimal example of how this would work:
example html of two modals, which are produced in a loop in your case.
I've now done it without a unique id, but with selecting via class.
<div class="modal">
<!-- // this classname is new and important -->
<form class="editform">
<input name="test" value="value1">
<button class="btn btn-default">Save</button>
</form>
</div>
<div class="modal">
<form class="editform">
<input name="test" value="value2">
<button class="btn btn-default">Save</button>
</form>
</div>
Your javascript would be something like this:
$(function() {
var formsAll = $('.editform');
// changed this to onSubmit, because it's easier to implement the preventDefault!
formsAll.on('submit',function(e){
e.preventDefault();
var formData = $(this).serialize();
console.log(formData);
// add your ajax call here.
// note, that we already have the formData, it would be "data: formData," in ajax.
});
});
Note, that I don't have your real html structure, so details might vary. But you get the idea.
also available here:
https://jsfiddle.net/a0qhgmsb/16/
-------------------------HTML code----------------------------
<body class="bdy">
<?php include "includes/head.php"; ?>
<?php
//include "includes/connection.php";
$us=$_GET['Uid']; (user id to post)
echo '<div class="container">
<button class="btn followButton follow" rel="6">Follow</button>
</div>';
include "includes/uprofile1.php";
include "includes/footer.php";
?>
<script src="style/javascript/follow.js"></script>
</body>
-------------------jquery code-----------------------
$(document).ready(function(){
$('button.followButton').on('click', function(e){
e.preventDefault();
$button = $(this);
if($button.hasClass('following')){
//$.ajax(); Do Unfollow
//this is only the button code i need help in adding the ajax call....
$button.removeClass('following');
$button.removeClass('unfollow');
$button.text('Follow');
} else {
var data=$(this).attr('Uid');
$.ajax({
url:"follow.php",
type:"post",
data:data,
});
$button.addClass('following');
$button.text('Following');
}
});
$('button.followButton').hover(function(){
$button = $(this);
if($button.hasClass('following')){
$button.addClass('unfollow');
$button.text('Unfollow');
}
}, function(){
if($button.hasClass('following')){
$button.removeClass('unfollow');
$button.text('Following');
}
});
});
please someone help me in inserting the ajax post, to post the user id to mysql .i don't understand how to make the ajax call and all.
Since you provided no errors i will guess..
$.ajax({
url:"follow.php",
type:"post",
data:data
});
Had to remove the extra comma after data:data
Basically I have a list of files composed from a foreach loop that all have the same code except for the name, which carries the file_id for each file. My problem is that when I added an on-click pop-up event I lose the ability to fetch the current $(".flag") attribute name. Is there a way that I can pass it along the way so I can use it in the end?
PHP: (the user sees the link which they can click...remember there are several of these as a result from the foreach loop. I'm showing one for example)
echo "<td><a href='#' class='flag' name='$files[id]' >Click Here</a> ( $files[nums] )</td>";
jQuery: (on-click this will happen)
$(".flag").live('click', function() {
$(".pop").show("slow");
return false;
});
HTML: this div will popup
<div class="pop">
<form method="post" id="new_folder" >
<p><label for="folder">Reason for Reporting?</label><textarea id="report_reason" name="report_reason" maxlenght="100" style="resize:none" cols="30" rows="5">Please limit your response to 100 characters.</textarea></p>
<p><input type="submit" value="Submit" id="message_submit"/> or <a class="close" href="/">Cancel</a></p>
</form>
</div>
jQuery: on submit I need to send the current $files['id'] and textarea value via ajax. The textarea sends the correct data, but the $(".flag") instead of being the id of the selected link it is the id of the first fetched id from the foreach loop
$("#message_submit").on("click", function(e){
var fileID = $(".flag").attr("name");
var text = $("#report_reason").val();
$(".pop").hide("slow");
$.ajax({
url: '<?php echo base_url().'home/report_file';?>',
type: 'POST',
data: { val: fileID, val2: text },
dataType: 'json',
success: function(output_string){
$(".success").text("You have flagged this file!!").show().css({"color" : "green", "margin-top" : "10px"});
$(".success").fadeOut(10000);
}
});
return false;
});
You can save the .flag link being clicked and later use it.
var flagClicked;
$(".flag").live('click', function() {
$(".pop").show("slow");
flagClicked = $(this);
return false;
});
$("#message_submit").on("click", function(e){
var fileID = flagClicked.attr("name");
....
I have this page which let the user to decide yes or no. So I'm using Jquery Ajax so the user won't have to refresh his page. I have provided the button so the user may chose 'Yes' and immediately the button change to 'No'.
I represent '0' and '1' in mysql to indicate 'No' and 'Yes'. So when the user click the button, mysql will update the record '1' or '0'.
I managed to update the mysql by first click, but when come to second click, mysql won't take the order.
Here's my Jquery Ajax code:
<script type="text/javascript">
$("document").ready(function()
{
$(".roundbox_blue").click(function()
{
$(this).toggleClass("roundbox_orange roundbox_blue");
var element = $(this);
var noteid = element.attr("value");
var info = "report="+noteid;
$.ajax({
type: "POST",
url: "mcr_external_gen.php",
data: info,
success: function(msg){
}
});
});
$(".roundbox_orange").click(function()
{
$(this).toggleClass("roundbox_blue roundbox_orange");
var element = $(this);
var noteid = element.attr("value");
var info = "not_report="+noteid;
$.ajax({
type: "POST",
url: "mcr_external_gen.php",
data: info,
success: function(msg){
}
});
});
});
</script>
Then I have this code for the user to click:
<div class="show">
<button class="roundbox_blue" value="1"> Click </button>
<button class="roundbox_blue" value="2"> Click </button>
</div>
The PHP code that will parse the AJAX query is like this:
if(isset($_POST['report']))
{
$line_id = $_POST['report'];
$Portal->LoginDB('test');
mysql_query('UPDATE `ajax` SET `report` = "1" WHERE `id`="'.$line_id.'"');
}
if(isset($_POST['not_report']))
{
$line_id = $_POST['not_report'];
$Portal->LoginDB('test');
mysql_query('UPDATE `ajax` SET `report` = "0" WHERE `id`="'.$line_id.'"');
}
The problem I'm facing is, once the user click the button, mysql did update the record however, when the user click the button second time (meaning to cancel) mysql did not update the record accordingly.
I appreciate if you guys can help me out here..
You are only hooking the blue box on doc load.
change class of second button,
<div class="show">
<button class="roundbox_blue" value="1"> Click </button>
<button class="roundbox_orange" value="2"> Click </button>
</div>