I have an "Add as Buddy" button and I want it to change permanently to "Pending Request" until the request is confirmed when I click it. When I click the button, yes it changes to "Pending Request" but whenever I refresh the page, it reverts back to "Add as Buddy". Any help on how I should do it?
PHP PART
<div class="member" data-user="<?php echo $member['xmpp_user']; ?>" data-uid="<?php echo $member['uid']; ?>">
<img src="https://s3.amazonaws.com/wheewhew/user/<?php echo $member['uid']; ?>/photos/<?php echo $member['profile_pic']; ?>" />
<div class="member_name"><?php echo $member['firstname']." ".$member['lastname']; ?></div>
<div id="addbutton"><button type="submit" class="add" id="<?php echo $member['uid']; ?>"> Add as Buddy </button></div>
</div>
JS PART
function addBuddy(){
var xmpp_user = $(this).parent().parent().attr('data-user')+'#example.com/default';
var to_uid = $(this).parent().parent().attr('data-uid');
$.ajax({
type: "POST",
url: "./ajax/addBuddy",
data: "from_uid="+uid+"&to_uid="+to_uid,
success: function(data) {
var ret = eval('('+data+')');
if(ret.status == 'success'){
connection.send($pres({to:xmpp_user,type:'subscribe'}).tree());
}
else if(ret.status == 'requested'){
document.getElementById(to_uid).innerHTML="Pending Request";
}
}
});
}
You should store that this user has an invitation somewhere, typically this is done in a database, after you stored you can do something like this
<div id="addbutton">
<button type="submit" class="add" id="<?php echo $member['uid']; ?>">
<?php echo $has_request? "Pending Request":"Add as Buddy"?>
</button></div>
That's because, in your PHP code, you're not checking if there is a request pending. You could also wonder if that is a thing you should be doing.
Think about how you want the UX to work and if it makes sense.
Related
I have this Ajax function:
$(document).ready(function() {
$('.view_data2').click(function() {
var employee_id2 = $(this).attr("id");
$.ajax({
url: "includes/accomUser.inc.php",
method: "post",
data: {
employee_id2: employee_id2,
button_value: $(this).val()
},
success: function(data) {
$('#employee_detail2').html(data);
$('#adddata2').modal("show");
}
});
$('#addmodal2').modal("show");
});
});
It takes this button properties(value and id) and sends them to the modal via post:
<button type="button" class="btn btn-outline-primary view_data2" id=" <?php echo $row['idFuncionarios']; ?>" value = "<?php echo $row['dia']; ?>" name = "envio">Ver</button>
Now, I need to take a data that has nothing to do with the button ($row['nomeDepartamento'];):
<td><?php echo $row['nomeDepartamento']; ?></td>
and send it via the same ajax function to the modal.
How would I do this?
Thank you!
This is how your button will look like
<button data-field-name="<?php echo $row['nomeDepartamento']; ?>" type="button" class="btn btn-outline-primary view_data2" id="<?php echo $row['idFuncionarios']; ?>" value="<?php echo $row['dia']; ?>" name="envio">Ver</button>
and retrive the $row['nomeDepartamento']; & after click funciton declare variable
var nomeDepartamento = $(this).attr("data-field-name");
and send this in data:{} and after success change html of any element like $("element").html(nomeDepartamento)
and there you go.
"I am working in a quizz I want it to let me know if the answer is correct or incorrect. My issue is that it does that but it tell me that is correct or not correct in the next page with the next question because it is refreshing the page everytime I submit the answer." I want it to tell the student if it is correct or incorrect in the same page before moving to the next page.
If I eliminate the ajax It will display if the answer was correct or not correct but in the next page where the new question is displayed. All the codes are in the same Php/html page. Thanks in advance.
<?php while($row5 = mysqli_fetch_assoc($res)): ;{ ?>
<h1 align="center" ><?php echo $row5['Question'] ?></h1>
<?php
$id = $row5['QuizzId'];
$question = $row5['Question'];
$correctAnswer=$row5['correctAnswer'];
$ans_array = array($row5['notCorrect1'],$row5['notCorrect2'], $row5['correctAnswer']);
shuffle($ans_array);
?>
<label>A<input type="radio" value="<?php echo $ans_array[0]; ?>" name="name"> <?php echo $ans_array[0]; ?></label>
<br/>
<br/>
<label>B<input type="radio" value="<?php echo $ans_array[1]; ?>" name="name"> <?php echo $ans_array[1]; ?></label>
<br/>
<br/>
<label>C <input type="radio" value="<?php echo $ans_array[2]; ?>" name="name"> <?php echo $ans_array[2]; ?></label>
<input type="hidden" name="correctAn" value="<?php echo $correctAnswer; ?>">
<?php } ?>
<br />
<br />
<input type="submit" value="Submit" name="correct">
<script>
$('#correct').click(function() {
$.ajax({
type: 'POST',
url: 'questions_1.php',
data: 'correctAnswer1',
success: function(php) {
alert('yes');
}
});
});
</script>
<?php
if($_GET["correctAnswer1"]){
$mianswer = $_POST["name"];
$correctAn = $_POST["correctAn"];
if($mianswer==$correctAn) {
echo "<h1>Great Job</h1>";
echo '<br>';
echo "<h1>The correct answer was $correctAn</h1>";
} else {
echo '<h1>Not correct</h1>';
echo "<h1>The correct answer was $correctAn</h1>";
}
}
?>
First of all in your ajax request you have defined type:'POST' but you have used $_GET in php , change that i.e : if($_POST['something'])
Then you need to take value of radio button which is selected by user and correct answer value .i.e:
$("input[name='correct']").click(function(e) {
e.preventDefault();
//getting selected radio button value
var name=$("input[name='name']:checked").val();
//getting value of correct answer
var correctAn=$("input[name='correctAn']").val();
$.ajax({
type: 'POST',
url: 'questions_1.php',
data: {'correctAn': correctAn,'name':name },//<-passing value to php
success: function(php) {
alert(php);
}
});
});
And in your php script , do like below :
if(isset($_POST['correctAn']) && isset($_POST['name'])){
//getting values
$mianswer=$_POST["name"];
$correctAn=$_POST["correctAn"];
//do something
}
Since you are passing the correct answer as a hidden field there is no need to make an ajax call, you can manage what you want client-side. Is questionable if this is the right approach, since inspecting the page will reveal the correct answer, but based on what you are currently doing, this is a possibility.
$('form').on('submit', function(ev) {
ev.preventDefault(); // This prevents form submission
let answer = $("input[name='name']:checked").val();
let correct = $("input[name='correctAn']").val();
if (answer == correct) { // Check if selected option is the correct one
alert('Congratulations!');
}
});
I have a form in PHP & MySQL and I want to submit it with AJAX.
I Have similar data so I have put these data in a foreach loop.
The problem is that when I try to submit the first row data it all goes well but it changes the data in all rows. and when I try to submit other data except the first row it doesn't submit at all.
I think the problem is because the submit button always gets the same id and therefore goes to the first row always.
I don't know how to get the value in Ajax.
Here goes the code:
//php form
<?php
$pid = $_GET['pid'];
include('config.php');
$timeline_query="SELECT * FROM timeline_table WHERE pid=$pid";
$result_timeline=mysqli_query($conn,$timeline_query);
if(!$result_timeline){
echo "Error: " . $conn->error;
}
$timelines=array();
while($row_timeline=mysqli_fetch_assoc($result_timeline)){
$timelines[]=$row_timeline;
}
?>
<?php
$x = 0;
foreach ($timelines as $timeline):?>
<div class="card">
<div class="card-header" id="heading<?php echo $x; ?>">
<h5 class="mb-0">
<button class="btn btn-link" data-toggle="collapse" data-target="#collapse<?php echo $x; ?>" aria-expanded="true" aria-controls="collapse<?php echo $x; ?>">
<?php echo $timeline['timeline_title'];?>
</button>
</h5>
</div>
<div id="collapse<?php echo $x; ?>" class="collapse" aria-labelledby="heading<?php echo $x; ?>" data-parent="#accordion">
<div class="card-body">
<form id="register_form">
<input type="text" id="tid" name="tid" value="<?php echo $timeline['tid']; ?>"/>
<textarea class="form-control" rows="4" id="timeline_description" name="timeline_description"><?php echo $timeline['timeline_description'];?></textarea>
<input id="submit" type="submit" name="submit" value="Submit" />
</form>
</div>
</div>
</div>
<?php $x++; endforeach;
// ajax function
$(document).ready(function(){
$("#submit").click(function(){
var timeline_description = $("#timeline_description").val();
var tid = $("#tid").val();
alert(timeline_description);
alert(tid);
// Returns successful data submission message when the entered information is stored in database.
// var dataString = 'timeline_description='+timeline_description+'&pid='+ pid + '&tid='+ tid +;
var dataString = 'timeline_description='+timeline_description;
alert(dataString);
if(timeline_description=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "process.php?tid"=+tid,
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
//process.php
<?php
include('config.php');
$tid=$_GET['tid'];
if( $_POST['timeline_description']==NULL ){ $timeline_description=''; }
else { $timeline_description=$_POST['timeline_description']; }
$query_timeline = "UPDATE timeline_table SET
timeline_description='$timeline_description' WHERE tid=$tid ";
$result=mysqli_query($conn,$query_timeline);
if(!$result){
echo "Error: " . $conn->error;
}
?>
Any idea?
Id of elements must be unique. The abnormal behaviour of your code is due to non-unique ids of your input elements.
In the case, If you cannot assign unique ids to elements you can achieve desired output by using this keyword and siblings() method in jquery.
Instead of
var timeline_description = $("#timeline_description").val();
var pid = $("#pid").val();
var tid = $("#tid").val();
try to get values in this way.
var timeline_description = $(this).siblings('#timeline_description').val();
var pid = $(this).siblings('#pid').val();
var tid = $(this).siblings('#tid').val();
I see there a problem with Yours inputs id - <input type="text" id="pid" - this is in foreach, so You have multiple elements with same id. So var pid = $("#pid").val(); will return You always a value of first found element. Try to use arrays:
<input type="text" id="pid[$pid]" name="pid[$pid]" value="<?php echo $pid ?>"/>
<input type="text" id="tid[$pid]" name="tid[$pid]" value="<?php echo $timeline['tid']; ?>"/>
Please remember one thing: id of any element in html PAGE (whole document) must be unique.
I am beginner in php and I am currently working on admin panel (you can see my admin panel page). The thing is that I want to pass serial number through these two buttons to perform further. But I can't find how to send $value to edit and delete a particular line.
<div id="headin2"><strong> <h3>Admin page </h3></strong></div>
<?php
echo "<table width=\"100%\" border=\"0\" id=\"tab\">";
echo "<tr>";
echo "<th id=\"td1\">Serial No</th><th id=\"td2\">Account Title</th>
<th id=\"td3\">Email</th><th id=\"td4\">Gender</th><th id=\"td5\">city</th>
<th id=\"td6\">Course</th><th id=\"td7\">status</th><th id=\"td8\" colspan=\"3\">Action</th>";
echo "</tr>";
while ( $row = mysql_fetch_array($query))
{
$SN = $row['SN'];
$actitle = $row['ac_title'];
$email = $row['email'];
$gender = $row['sex'];
$cite = $row['city'];
$course = $row['CRS'];
$status = $row['status'];
echo "<tr>";
echo "<td>".$SN."</td><td>".$actitle."</td><td>".$email."</td>
<td>".$gender."</td><td>".$cite."</td><td>".$course."</td><td>".$status."</td>
<td>"."<input type=\"button\" name=\"edit\" value=\"Edit\"/>
<input type=\"button\" value=\"Delete\" name=\"delete\" >"."</td>";
echo "</tr>";
}
?>
</table>
You need both the action (edit/delete) and the row id. Unfortunately, without some JS the button will only post one value.
You can create a new form for each row, add in a hidden element. For example:
<?php while ($row = mysql_fetch_array($query)) : ?>
<tr>
<!-- other cells -->
<td>
<form method="post" action="">
<input type="submit" name="action" value="Edit"/>
<input type="submit" name="action" value="Update"/>
<input type="hidden" name="id" value="<?php echo $row['id']; ?>"/>
</form>
</td>
</tr>
<?php endwhile; ?>
Then after posting it you can just check for the action and id
if ($_POST['action'] && $_POST['id']) {
if ($_POST['action'] == 'Edit') {
// edit the post with $_POST['id']
}
}
You can do it one of two ways.
jQuery and AJAX
For each <tr>, everywhere there is a delete button,
Delete
Script at the bottom:
//Include jQuery here
<script language="javascript">
$('.delete-row').click(function (event) {
event.preventDefault();
var id = $(this).data('id');
$.ajax({
url: "url/to/delete",
method: "POST",
cache: false,
data: { id: id },
success: function (html) {
$(this).parent().parent().remove();
});
});
});
</script>
This puts the ID of the row into the <a href> itself using data and uses jQuery to send out an AJAX call to delete the record. If the delete is successful, it removes the row from the table.
Old-School Button
For each <tr>, everywhere there is a Delete button,
<form method="POST" action="url/to/delete">
<input type="hidden" name="id" value="<?php echo $value; ?>" />
<input type="submit" value="Delete" />
</form>
This is the old-school way to do it, where the hidden field is how the backend knows which row to delete.
On the backend, you still use $_POST['id']; to get the ID of the record to remove. In the above examples, $value is the ID for each row, and is most likely something like $row['id'] when it is coming from a foreach().
Use a hidden input (e.g.<input type="hidden" value="your_value_here">)
when you click Edit it open a page with corresponding record. You can do it by a Edit link or a image or a button.
<?php echo "<a href='".BASE_URL."admin/edit.php?id=$id' target='_blank'> <img src=".BASE_URL."/images/edit.png width=16 height=16 alt=Edit /> </a>";?>
for delete you can use jquery. here is a example
echo "<a href='#' onclick='deletePrescription($id)' ><img src=images/document_delete.png width=16 height=16 title='Delete Prescription' alt=Delete /> </a>";
<script type="text/javascript">
function deletePrescription(checkup_id) {
//alert(checkup_id);
var agree=confirm("Do you really want to delete the prescription?");
if (agree)
{
$.ajax
({
type: "POST",
url: "delete_prescription_admin.php",
data: "checkup_id="+checkup_id,
success: function(msg)
{
//
//alert( "array Updated: " + msg );
location.reload(true);
}
});
}
else
{
return false ;
}
}
</script>
PHP is on the server side, so you need to send parameters, parse it and have your php act.
i.e.
The edit button will make POST or GET request with parameter: id=123&action=edit
and your PHP will parse the Query String:
$strID = $_GET['id'];
$strAction = $_GET['action'];
then act on it..
if ($strAction=='edit'){
// do something...
}
Your buttons should be wrappen in a form like:
<form action="yourFile.php?id=<?=$SN ?>&action=edit" method="GET" id="formEdit<?=$SN ?>">
<button type="submit" value="Edit">
</form>
<a href=register_course.php?id=$roll&code=".$row['course_code']."&name=".$row['course_name']."><input type=submit value=Register>
*here register_course.php is the file where you are sending some variable having some data it will be delivered when button is clicked whose value is register //course code is the variable you want to send ... im assigning its value as $ code... and assigning id $roll as id and assigning course_name as $name....
the other file will get the variables having some data
What I need to do is prepend the users latest status update with not only the newmsg and the users id but I need to also add my comment toggle link, my divider-postid div my users picture and name, my delete button, and my like and dislike button. So what I'd have is something like what Twitter and facebook do. ->Send the form data into ajax and print everything out into the feed. My profile.php has everything I use that needs to be included.
So is there a way I can call these blocks of html and display them in the prepended div after the Ajax success? Its really hard to explain as I don't know what I'm doing, but hopefully you get the idea. I'm just not up on all this.
PROFILE.PHP
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
var content = $("#toid").val();
var newmsg = $("#newmsg").val();
$.ajax({
type: "POST",
cache: false,
url: "insert.php",
data: "toid=" + content + "&newmsg=" + newmsg,
success: function(){
$("#myThing").prepend("<div class='userinfo'>"+newmsg+" </div>");
}
});
});
});
</script>
<div class="userinfo"><div id="divider">
<div class="form">
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id; ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed">
</div>
</form>
</div></div></div></body>
<p id="myThing"></p>
COMMENT LINK
echo "<div class='stream_option'><a style='cursor:pointer;' id='commenttoggle_".$streamitem_data['streamitem_id']."' onclick=\"toggle_comments('comment_holder_".$streamitem_data['streamitem_id']."');clearTimeout(streamloop);swapcommentlabel(this.id);\"> Write a comment...</a></div>";
}else{
echo "<div class='stream_option'><a style='cursor:pointer;' id='commenttoggle_".$streamitem_data['streamitem_id']."' onclick=\"toggle_comments('comment_holder_".$streamitem_data['streamitem_id']."');clearTimeout(streamloop);swapcommentlabel(this.id);\"> Show Comments (".$num2.")</a></div>";
LIKE LINK
cho "<div class='stream_option'><a id='likecontext_".$streamitem_data['streamitem_id']."' style='cursor:pointer;' onClick=\"likestatus(".$streamitem_data['streamitem_id'].",this.id);\">";
DISLIKE LINK
echo "<div class='stream_option'><a id='dislikecontext_".$streamitem_data['streamitem_id']."' style='cursor:pointer;' onClick=\"dislikestatus(".$streamitem_data['streamitem_id'].",this.id);\">";
DELETE LINK
<? if($streamitem_data['streamitem_creator']==$_SESSION['id']){
echo "<div style='cursor:pointer;position:relative;top:-70px;float:right;padding-right:5px;' onclick=\"delete_('".$streamitem_data['streamitem_id']."');\">X</div>";}
I guess here:
success: function(){
$("#myThing").prepend("<div class='userinfo'>"+newmsg+" </div>");
}
Is where you're inserting the HTML? If that's the case, and if insert.php returns HTML, try this:
success: function(r){
$("#myThing").prepend("<div class='userinfo'>"+newmsg+r.responseText+" </div>");
}
To get the ID:
I guess the insertion is done with mysql, so after the new message is inserted you'd do:
$new_id = mysql_insert_id();
and then output the HTML:
echo "<div class='stream_option'><a id='likecontext_".$new_id."' style='cursor:pointer;' onClick=\"likestatus(".$new_id.",this.id);\">";
echo "<div class='stream_option'><a id='dislikecontext_".$new_id."' style='cursor:pointer;' onClick=\"dislikestatus(".$new_id.",this.id);\">";
if ($new_id == $_SESSION['id'])
echo "<div style='cursor:pointer;position:relative;top:-70px;float:right;padding-right:5px;' onclick=\"delete_('".$new_id."');\">X</div>";