I have a Follow/unfollow button which is working perfectly with PHP. How do i write ajax to follow/unfollow without page refresh and update the button value(follow or unfollow) accordingly?
PHP:
//FOLLOW
if(isset($_POST['follow'])){
$sql = mysqli_query($conn, "INSERT INTO `follows`(`user_id`, `following_id`) VALUES ('$Sessionid','$getID')");
header("Location: /funaholic/profile?Profileid=$getID");
}
//UNFOLLOW
if(isset($_POST['unfollow'])){
$sql = mysqli_query($conn, "DELETE FROM `follows` WHERE user_id=$Sessionid AND following_id=$getID");
header("Location: /funaholic/profile?Profileid=$getID");
}
//CHECK IF ALREADY FOLLOWING
$getFollowing = mysqli_query($conn, "SELECT * FROM `follows` WHERE user_id='$Sessionid' AND following_id='$getID'");
$rowcount = mysqli_num_rows($getFollowing);
if($rowcount === 0){
if($Sessionid == $getID){
echo "<form action='update' id='followform' method='POST'>
<button class='follow' name='follow'>UDATE PROFILE</button>
</form>";
}else {
echo "<form action='profile?Profileid=".$getID."' id='followform' method='POST'>
<button class='follow' id='myBTN' name='follow'>FOLLOW</button>
</form>";
}
}else{
echo "<form action='profile?Profileid=".$getID."' method='POST'>
<button class='follow' id='myBTN' name='unfollow'>UNFOLLOW</button>
</form>";
}
AND THIS IS THE AJAX POST FUNCTION:
//FOLLOW UNFOLLOW AJAX
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: $(this).attr('action'),
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
Related
Trying to check Unique Category Title Using Ajax and Jquery.
JQuery and ajax stuff
<script>
$(document).ready(function(){
$('#category_title').change(function(){
var category_title = $(this).val();
$.ajax ({
url : "ajax_calls.php",
method : "POST",
data : {category_title :category_title },
dataType: "text",
success:function(html)
{
$('#availablity').html(html);
}
});
});
</script>
ajax_call.php
<?php
include 'commands.php';
if (isset($_POST['category_title'])) {
$category_title = $_POST['category_title'];
$obj= new commands();
$result= $obj->check_category_title($category_title);
if (empty($result)) {
echo "<span class='status-available' style='color:green;'> Username Available.</span>";
} else {
echo "<span class='status-not-available' style='color:red;'>Category Already Exist</span>";
}
}
?>
HTML stuff
<form action="" method="post" id="my_form" enctype="multipart/form-data">
<div class="form-group">
<label class="tags">Category Title</label>
<input type="text" name="category_title" class="form-control" id="category_title"><span id="availablity"></span>
<p class="errorMsg"><?php if(isset($errorTitle) && $errorTitle== 1){echo "Field Required" ;} ?> </p>
</div>
</form>
MySQLi stuff
function check_category_title($category_title){
$stmt = $this->con->prepare("SELECT category_title FROM `nm_category` WHERE category_title='$category_title'");
$stmt->execute();
$result=$stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
I want to prevent user to submit if the category already exist in table else allow user to submit
Make changes like below in your php code :
if (empty($result)) {
echo "<span class='status-available' style='color:green;'> Username Available.</span>";
//show submit button if no data found
echo "<input type='submit' value='submit'>";
} else {
echo "<span class='status-not-available' style='color:red;'>Category Already Exist</span>";
//disabled button to prevent submit if category exist
echo "<input type='submit' value='submit' disabled='disabled'>";
}
I was working on my assignment to make an ajax live search. Unfortunately, I've got an error saying 'undefined index = q'.
Here is my jquery:
<script>
$(document).ready(function(e){
$("#search").keyup(function(){
$("#here").show();
var x = $(this).val();
$.ajax({
type:'GET',
url:'index.php',
data:'q='+x,
success:function(data){
$("#here").html(data);
},
});
});
});
</script>
<input type="search" name="search" id="search">
<div id="name">
</div>
my php:
<?php
if(empty($_GET['q']))
{
$q = $_GET['q'];
$query = "SELECT * FROM info WHERE name LIKE '%$q%'";
$result = mysqli_query($conn, $query);
while($output = mysqli_fetch_assoc($result))
{
echo '<a>' . $output['name'] . '</a>';
}
}
?>
Your code is wrong. Here is a fix
<script>
$(document).ready(function(e){
$("#search").keyup(function(){
$("#here").show();
var x = $(this).val();
$.ajax({
type:'GET',
// Here we will pass the query to the php page
url:'index.php?q='+x,
// disabling the cache
cache: false,
success:function(data){
$("#here").html(data);
},
});
});
});
</script>
<input type="search" name="search" id="search">
<div id="name">
</div>
my php:
<?php
if(isset($_GET['q']))
{
$q = $_GET['q'];
// You need to sanitize the input before pass the query.
$query = "SELECT * FROM info WHERE name LIKE '%$q%'";
$result = mysqli_query($conn, $query);
while($output = mysqli_fetch_assoc($result))
{
echo '<a>' . $output['name'] . '</a>';
}
}
?>
Hey I have a form with two submit buttons and a simple text input. I want the form to be submitted by ajax (I figured out how to do that).
form:
<form method='post' action='likesystem.php' id='7'>
<input class='form-control' type='hidden' value='7' name='postid'>
<button type='submit' class='btn btn-success btn-sm' name='poslike' value='liking'>Like this</button>
<button type='submit' class='btn btn-danger btn-sm' name='poslike' value='disliking'>Dislike this</button>
the script is as follows:
<script>
$('#7').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: 'likesystem.php',
type: 'POST',
data: $('#7').serialize(),
});
});
</script>
the php page:
<?php
require_once 'config.php';
$link = mysqli_connect($DB_SERVER, $DB_USERNAME, $DB_PASSWORD, $DB_NAME);
if(! $link ) {
die('Could not connect: ' . mysql_error());
echo "Connection Error";
}
if($_SERVER["REQUEST_METHOD"] == "POST") {
$postid = $_POST['postid'];
switch($_POST['poslike']) {
case 'liking':
$sql = "UPDATE posts SET poslike = poslike + 1 WHERE id = $postid";
case 'disliking':
$sql = "UPDATE posts SET dislike = dislike + 1 WHERE id = $postid";
}
if (mysqli_query($link, $sql)) {
echo "You did something";
} else {
echo "There was an error";
}
mysqli_close($link);
}
What I am I doing wrong here? I've checked multiple sites but the answers there could help and that's why I'm asking it here now.
Change your form to this:
<form method='post' action='likesystem.php' id='7'>
<input class='form-control' type='hidden' value='7' name='postid' id='postid'>
<button type='submit' class='btn btn-success btn-sm vote' name='poslike' value='liking'>Like this</button>
<button type='submit' class='btn btn-danger btn-sm vote' name='poslike' value='disliking'>Dislike this</button>
</form>
and try this code for script:
<script>
$('.vote').on('click', function(event) {
event.preventDefault();
var postid = $('#postid').val();
var poslike = $(this).attr('value');
$.ajax({
url: 'likesystem.php',
type: 'POST',
data: 'postid=' + postid + '&poslike=' + poslike,
});
});
</script>
I have table received from database:
<p id="result"></p>
<?php
//$id = $_SESSION['staff_id'];
$teamResult = getQuarter($leader_id);
$count1 = 0;
if (mysqli_num_rows($teamResult) > 0)
{
?>
<table id="confirm">
<tr>
<th>1st Quarter</th>
</tr>
<?php
while($row = mysqli_fetch_array($teamResult))
{
$staff_id = $row['staff_id'];
$username = $row['username'];
$date1 = $row['date1']; $fdate1 = $row['fdate1']; $q1 = $row['q1']; $cfm1 = $row['cfm1'];
?>
<tr>
<td>
<?php if($date1 != NULL){
echo "Ev.date: ".$date1."<br/> Fb.date: ".$fdate1.""
."<input type='text' id='stid' name='confirm' class='confirm' value='". $q1. "| " . $staff_id ."'>";
}else {echo "";}
?>
</td>
</tr>
<?php
$count1++;
}
} else {
echo "<h2>No Data to Display</h2>";
}
?>
</table>
This field is checkbox but I changed it to text to see its value:
<input type='text' id='stid' name='confirm' class='confirm' value='". $q1. "| " . $staff_id ."'>
Here is what I got in table:
Then I have AJAX function:
<script>
$(function () {
$(document).on('click', '.confirm', function(){
var stid = $("#stid").val();
$.ajax({
url: "comAssessment/change.php",
method: "POST",
data: {stid: stid},
dataType:"text",
success: function (data) {
$('#confirm').hide();
$('#result').html(data);
}
});
});
});
</script>
And change.php:
$info = $_POST["stid"];
list($value1,$value2) = explode('|', $info);
echo $value1;
echo "<br/>";
echo $value2;
But the problem is I dont get correct value. For first and second row i get 1| 1000302. Even for second row where is should be 1| 1000305. What it the problem and how can I solve it?
IDs have to be unique. $("#stid") will always select the first element with that ID.
You can simply use $(this) to get the value of the element you clicked on.
$(document).on('click', '.confirm', function(){
var stid = $(this).val();
$.ajax({
url: "comAssessment/change.php",
method: "POST",
data: {stid: stid},
dataType:"text",
success: function (data) {
$('#confirm').hide();
$('#result').html(data);
}
});
});
I have a question about using ajax.I want to delete something of my screen (to be clear, some articles) I'm generating content (the articles) on the screen with this code:
while($test = $allArticles->fetch_assoc())
{
echo "<div class='metfoto'>";
echo "<h1 name='tt' class='titelopmaak'>".$test['titel'] . "<br /></h1>";
echo "<p class='artikelopmaak'>" . $test['article'] . "</p>";
echo "<form method='post' action=''>";
echo "<input type='submit' class='delete' name='verwijder' value='verwijder'>";
echo "</form>";
//echo "<h1>".$test['id']."</h1>";
echo "</div>";
}
This all is working very well without ajax. But I want to make this(the delete with the button) happen without a page refresh.
When i for example check the content of $test['id'], i receive one number. My problem with the code below is that when i want to put the title into variabel (var titel) for ajax, it loads all the titels from my page.
<script type="text/javascript">
$(document).ready(function(){
$(".delete").click(function(){
var titel = $(".titelopmaak").text();
var artikel = $(".artikelopmaak").text();
$.ajax({
type: "POST",
url: "assets/ajax/deleteArticle.php",
data: { titelA:titel },
}).done(function( msg ) {
if(msg.status != "error")
{
if(msg.status == "success")
{
$(".titelopmaak").fadeOut();
}
else
{
}
}
});
return false;
})
});
</script>
EDIT
I hope i explained my question in a better way now
Your problem is here
var titel = $(".titelopmaak").text();
You get all the values of the elements with class .titelopmaak but you only need one.
This is the correct one, we go up the tree and then find the item.
var titel = $(this).closest('.metfoto').find('.titelopmaak').text();
But, control elements by the title its very bad practice, use id instead of.
<script>
$(document).ready( function(){
$('.delete').submit( function() {
$.ajax({
url: $(this).attr('action'),
data: $(this).serialize(),
type: $(this).attr('method'),
success: function(data, status, jqXHR) {
$(".titelopmaak").fadeOut();
},
error: function(jqXHR, textStatus, errorThrown) {
}
);
});
});
</script>
<? while($test = $allArticles->fetch_assoc()) { ?>
<form method="POST" action="" class="delete">
<input type="hidden" value="<?=$test['id']?>" name="delete">
<input type="submit" value='verwijder'>
</form>
<? } ?>
You can try like this....
You have to specify individual id for each html elements
while($test = $allArticles->fetch_assoc())
{
$cid = $test['id'];
echo "<div id='div$cid' class='metfoto'>";
echo "<h1 name='tt' id='h1$cid' class='titelopmaak'>".$test['titel'] . "<br /></h1>";
echo "<p id='para$cid' class='artikelopmaak'>" . $test['article'] . "</p>";
echo "<input type='submit' class='delete' name='verwijder' id='verwijder$cid' onclick='deleteValue($cid);' value='verwijder'>";
echo "</div>";
}
javascript function
Refer the h1 and div by their ids.
<script type="text/javascript">
function deleteValue(cid)
{
var titel = $("#h1"+cid).text();
var artikel = $("#para"+cid).text();
$.ajax({
type: "POST",
url: "assets/ajax/deleteArticle.php",
data: { titelA:titel },
}).done(function( msg ) {
if(msg.status != "error")
{
if(msg.status == "success")
{
$("#h1"+cid).fadeOut();
}
else
{
}
}
});
return false;
})
}
</script>
deleteArticle.php
include "connection.php";
$title = $_POST['titelA'];
$ok = mysql_query("delete from yourtable where title='$title');
echo "your msg here";