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>
Related
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');
}
});
});
});
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 load a form by click on a button with $("#btn").load("form.php") in index.php,
I want to avoid redirect the page to action file after submit and add an item in the table which is under the form.
my demo is on http://price.parag.website
<?php include "../connection.php" ?>
<h1>Add CPU</h1>
<form method="post" action="actions/cpu_action.php">
<label for="name">Name</label>
<input type="text" name="cpu_name" />
<label for="price">Price</label>
<input type="text" name="cpu_price" />
<input type="submit" value="Add" />
</form>
<?php
$sql = "SELECT id, cpu_name, cpu_price FROM cpu";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
echo "<table>
<thead>
<tr>
<th>ID</th>
<th>CPU NAME</th>
<th>CPU PRICE</th>
</tr>
</thead>";
while($row = $result->fetch_assoc())
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['cpu_name'] . "</td>";
echo "<td>" . $row['cpu_price'] . "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
<h1>Add CPU</h1>
<form id="formupload" method="post" action="actions/cpu_action.php">
<label for="name">Name</label>
<input type="text" name="cpu_name" />
<label for="price">Price</label>
<input type="text" name="cpu_price" />
<input type="submit" value="Add" />
</form>
now we have to clear default action of form (i will use jquery)
$('#formupload').on('submit',function(e){
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $('#formupload').attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(result){
if(condition){}
else{}
}
})
})
Try this it will work
<button type="button" onclick="loadDoc()">Request data</button>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("table").innerHTML = this.responseText;
}
};
xhttp.open("POST", "pageToPost.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("data1=bar&data2=foo");
}
</script>
This will take the response and update the element with id table with the repsonse, so make sure that it is in html.
I am new to PHP. I'm trying to fix the syntax error for PHP code. But seems not working. I'm getting the syntax error at s[i][4]. If I change to "+s[i][4]+" it is not complaining about syntax error but it is not reading the actual value. I think I'm using the wrong variable inside PHP code but tried lot ways but failed. Actually I'm trying to hide paid button if the status(s[i][4]) is cancelled. Please help.
Java script code
`<script type="text/javascript">
$(document).ready(function() {
var table = $('#myTransactionitems').dataTable(); //Initialize the datatable
var user = $(this).attr('id');
if(user != '')
{
$.ajax({
url: 'transactions',
dataType: 'json',
success: function(s){
console.log(s);
table.fnClearTable();
for(var i = 0; i < s.length; i++) {
table.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
"<form method='post' action = 'donationSplit'><input name = 'donationid' type='hidden'\
value='"+s[i][0]+"'></input><input type='submit' value = 'Paid' <?php if (s[i][4]=='Cancelled'){ ?> style='display:none' <?php } ?> class='btn btn-sm btn-success pull-left '>\
</input></form><form method='post' action = 'donationSplit'><input name = 'donationid' type='hidden' \
value='"+s[i][0]+"'></input><input type='submit' value = 'Cancel' class='btn btn-sm btn-danger pull-right'>\
</input></form>"
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
}
});
</script>`
Trasaction.php code
`
<?php
include('sessionstart.php');
include('session.php');
require_once("dbcontroller.php");
$db_handle = new DBController();
$user_id=$_SESSION['login_user_id'];
$query = mysql_query("select * from mytransactions_list where userid = '$user_id'");
while ($fetch = mysql_fetch_array($query)) {
$output[] = array($fetch[0], $fetch[1], $fetch[2], $fetch[3], $fetch[4], $fetch[5], $fetch[6]);
}
echo json_encode($output);
?>
`
The below code should work fine. I have added a JS variable named disp1. It's assigned the value of "display:none;" if the if condition is matched, otherwise it will be blank.
for(var i = 0; i < s.length; i++) {
var disp1 = '';
if ( s[i][4] == 'Cancelled' ) {
disp1 = 'display:none;'
}
table.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
"<form method='post' action = 'donationSplit'><input name = 'donationid' type='hidden'\
value='"+s[i][0]+"'></input><input type='submit' value = 'Paid' style='" + disp1 +"' class='btn btn-sm btn-success pull-left '>\
</input></form><form method='post' action = 'donationSplit'><input name = 'donationid' type='hidden' \
value='"+s[i][0]+"'></input><input type='submit' value = 'Cancel' class='btn btn-sm btn-danger pull-right'>\
</input></form>"
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
}
});
You can not use a Javascript variable in PHP because PHP code is executed first.
Try this
"<form method='post' action = 'donationSplit'>\
<input name = 'donationid' type='hidden' value='"+s[i][0]+"' />\
<input type='submit' value = 'Paid' " + (s[i][4]=='Cancelled') ? "style='display:none'" : "" + "class='btn btn-sm btn-success pull-left ' />\
</form>\
<form method='post' action = 'donationSplit'>\
<input name = 'donationid' type='hidden' value='"+s[i][0]+"' />\
<input type='submit' value = 'Cancel' class='btn btn-sm btn-danger pull-right' />\
</form>"
There is a form where the user enters a number and according to the condition applied on the number, a list of addresses are displayed. I would like to store the data that is returned through AJAX. The code on the page that has a form:
index.php
<script>
$(document).ready(function() {
$("#phone").keyup(function() {
var number = $("#phone").val();
$.ajax({
url: "t_fetchaddr.php",
type: 'POST',
data: 'number='+number,
cache: false,
}).done(function(html) {
$('#results').html(html);
});
});
});
<script>
<form action="insert_temp.php" method="POST">
<input type="text" name="phoneno" id="phone" value="" />
<div id="results"></div>
<button class="button btn btn-primary btn-large" type="submit" name="submit" value="submit">Submit</button>
</form>
code on t_fetchaddr.php page
$val = $_REQUEST['number'];
$sql2 = "SELECT * FROM user_address where number='".$val."' ";
$result2 = mysqli_query($con, $sql2);
if (mysqli_num_rows($result2) > 0)
{ ?>
<div class="span6" >
<div class="span3">
<? while($row2 = mysqli_fetch_assoc($result2))
{ ?>
<input type="radio" name="old_address" value="<? echo $row2['address']; ?>" ><? echo $row2['address']; ?><br>
<? } ?>
</div>
</div>
<? } ?>
code on insert_temp.php page
$old_address = mysqli_real_escape_string($con, $_POST['old_address']);
echo $old_address;
Everything is working fine until displaying of the address through number, but when I submit the form it is not going to the back end. I tried to echo $old_address but got nothing.
other input values in index page inside the form are going to backend but value that is being fetched from t_fetchaddr.php page is not getting carried, Can anyone please tell where I went wrong
Try this and watch your console :
$(document).ready(function() {
$("#phone").keyup(function() {
var number = $(this).val();
$.ajax({
url: "t_fetchaddr.php",
type: 'POST',
data: {number:number},
cache: false,
success : function(html) {
$('#results').html(html);
},
error : function(err){
console.log(err);
}
});
});
});
<script>
$(document).ready(function()
{
$("#phone").keyup(function()
{
var number = $("#phone").val();
$.ajax({
url: "t_fetchaddr.php",
type: 'POST',
data: {number :number}, //modified
cache: false,
success:function(html)
{
$('#results').html(html);
}
});
});
});
</script>//Missing closing
<form action="insert_temp.php" method="POST">
<input type="text" name="phoneno" id="phone" value="" />
<div id="results"></div>
<button class="button btn btn-primary btn-large" type="submit" name="submit" value="submit" >Submit</button>
</form>
and in php
$val = $_POST['phoneno'];
$sql2 = "SELECT * FROM user_address where number='".$val."' ";
$result2 = mysqli_query($con, $sql2);
if (mysqli_num_rows($result2) > 0)
{ ?>
<div class="span6" >
<div class="span3">
<? while($row2 = mysqli_fetch_assoc($result2))
{ ?>
<input type="radio" name="old_address" value="<? echo $row2['address']; ?>" ><? echo $row2['address']; ?><br>
<? } ?>
</div>
</div>
<? } ?>
Note:
Missing closing tag </script>
And this line changed data: 'number='+number,
just try this code on fetchaddr.php
i have just removed the in between php tags.
<?
$val = $_REQUEST['number'];
$sql2 = "SELECT * FROM user_address where number='".$val."' ";
$result2 = mysqli_query($con, $sql2);
if (mysqli_num_rows($result2) > 0) {
echo '<div class="span6" >
<div class="span3">';
while($row2 = mysqli_fetch_assoc($result2))
{
echo '<input type="radio" name="old_address" value="'.$row2['address'].'" >'.$row2['address'].'<br>';
}
echo '</div>
</div>';
} ?>
hopefully this will solve your problem.