I will describde the problem as straight as I can, so:
I've got website, on which I have button, by clicking which I want to run AJAX, which would run .php code which will update database records.
Right now, with code below Im not getting any errors, and also database is at the same state as it was before clicking button. What's more I guess that ajax doesnt works properly, as the website refreshes as I click update button.
Any 1? Anything?
Here goes main php (updated):
<form role='form' method='post' action='' autocomplete='off'>
<input type='submit' id='addBidSlow' name='addBidSlow' value='Slow bid' class='btn btn-inline-block btn-success auctionDetails' tabindex='1'>
</form>
</td>
</tr>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$("#addBidSlow").click(function(){
var bidAuthor = "<?php echo $_SESSION['username']; ?>";
var itemID = <?php echo $_GET['id']; ?>;
$.post(
"addBidSlow.php",
{bidAuthor: bidAuthor, itemID: itemID},
false
);
});
</script>
And updater php:
<?php
require('includes/config.php');
$bid = 1000;
$bidAuthorPoints = "";
$finalPoints = "";
$finalDate = "";
$todayDate = date("Y-m-d H:i:s");
$stmt = $db->prepare("SELECT itemID, endTime FROM items WHERE itemID = :itemID");
$stmt->execute(array(':itemID' => $itemID));
while($row = $stmt->fetch(PDO::FETCH_OBJ)) {
$finalDate = $row->endTime;
}
$addedTime = strtotime($finalDate) + 60*10;
$finalDate2DB = date('Y-m-d H:i:s' , $addedTime);
$stmt = $db->prepare("UPDATE items SET endTime = :finalDate2DB WHERE itemID = :itemID");
$stmt->execute(array(
':itemID' => $itemID,
':finalDate2DB' => $finalDate2DB
));
?>
Related
I need to send a value from a form to php, get data from a database based on the posted value, store all the data in json and then change an input value to the value of the json. All that without reloading the page because I can't lose the stuff that user has input already in the form.
Here is the select where I get the value from:
<select name="groupName" id="groupName" class="form-control message" onchange="group_select()">
<?php
$user_id = $_SESSION["id"];
$sql = mysqli_query($link, "SELECT group_name FROM SMAILY_groups WHERE user_id = '".$user_id."'");
while ($row = $sql->fetch_assoc()){
echo "<option value='".$row['group_name']."'>" . $row['group_name'] . "</option>";
}
?>
</select>
The changing of the value is handled by this function:
function group_select(){
$.ajax({
url:'send.php',
type:'post',
data:$('#smsForm').serialize(),
success:function(data){
}
});
}
And php that handles it is this:
$groupName = $_POST["groupName"];
$user_id = $_SESSION["id"];
$stack = array();
$sql = "SELECT phone FROM SMAILY_groups_numbers t1 INNER JOIN SMAILY_groups
t2 ON t1.group_id = t2.group_id WHERE t2.user_id = '".$user_id."' AND
t2.group_name = '".$group_name."'";
$result = mysqli_query($link, $sql);
while($row = $result->fetch_array(MYSQLI_ASSOC))
{
array_push($stack, $row["phone"]);
}
$stack = json_encode($stack);
$result->free();
Now I need to get the phone numbers that I got from the database, and assign them as a value to one of my input fields. I need to do this without refreshing the page. I'm pretty sure it's somehow done in the ajax success function but I just don't know how.
You are correct, it is done in the success callback. Actually it's pretty simple: Create a <input type="hidden" name="phonenumbers" id="phonenumbers"> element in your HTML.
<select name="groupName" id="groupName" class="form-control message" onchange="group_select()">
<?php
...
?>
</select>
<input type="hidden" name="phonenumbers" id="phonenumbers" value="">
Then, on each request, append the returned value(s) to the value of that <input> element. Don't forget to add a separator though! I use comma.
For example:
function ajaxSuccessHandler (data) {
var hiddenInput = document.querySelector('#phonenumbers');
if (hiddenInput.value.length >= 1) {
// if there are already one (or more) numbers in the hidden input
hiddenInput.value += ',' + data.join(',');
} else {
hiddenInput.value = data.join(',');
}
}
You can either call that function inside the success callback or as your success callback. So this:
function group_select(){
$.ajax({
url:'send.php',
type:'post',
data:$('#smsForm').serialize(),
success: ajaxSuccessHandler
});
}
or this:
function group_select(){
$.ajax({
url:'send.php',
type:'post',
data:$('#smsForm').serialize(),
success: function (data) {
ajaxSuccessHandler(data);
}
});
}
should produce the same result.
You Can try this
<select name="groupName" id="groupName" class="form-control message" onchange="group_select()">
<?php
$user_id = $_SESSION["id"];
$sql = mysqli_query($link, "SELECT group_name FROM SMAILY_groups WHERE user_id = '".$user_id."'");
while ($row = $sql->fetch_assoc()){
echo "<option value='".$row['group_name']."'>" . $row['group_name'] . "</option>";
}
?>
</select>
Javascript Code Dont Forget to Include jquery in your page head
<script>
function group_select(){
let groupName = document.getElementById('groupName').value;
$.ajax({
url:'send.php?groupName='+groupName,
type:'GET',
success:function(data){
var obj = jQuery.parseJSON(data);
//Field to which you want to sent value
document.getElementById('fieldName').value = obj.variableName;
}
});
}
</script>
send.php will look some what like this
$groupName = $_GET["groupName"];
$user_id = $_SESSION["id"];
$stack = array();
$result = mysql_query("SELECT phone FROM SMAILY_groups_numbers t1 INNER JOIN SMAILY_groups
t2 ON t1.group_id = t2.group_id WHERE t2.user_id = '".$user_id."' AND
t2.group_name = '".$group_name."'");
$row = mysql_fetch_assoc($result);
echo json_encode($row);
I am updating a span using below script but it is working if condition is false and if condition is true it does not update.
What i observed that it executes the same false condition and when i click the second time it updates the quantity but less 1 number than the actual quantity of records in the database.
Like total records are 2 and when i click submit the script runs and if condition is true in the database records are updated = 3 but in the span it shows 2.
When i click 2nd time and in the database records are = 4 and in the span it shows 3.
Button where i click and run the script
<input onclick='updateTitems("1");' type="submit" class="btn-style-2 mg-left-5" value="ADD TO CART">
script
<script>
function updateTitems(id) {
var uid = "<?php echo $ses_mem; ?>";
$.ajax({
type: "GET",
url: 'inc/menu_update_total_items.php',
data: "id=" + id + "&uid=" + uid,
success: function(data) {
$('.summary12').html(data);
}
});
}
</script>
menu_update_total_items.php
$user_id = $_GET['uid'];
$item = "select count(*) as records
from orders_temp
where user_id = '".$user_id."'
";
$itemq = $dba->query($item);
$itemr = $itemq->fetch_assoc();
$count = $itemr['records'];
---------------------------------
$itemx = "select count(*) as records
from orders_temp
where date = now()
and user_id = '".$user_id."'
";
$itemqx = $dba->query($itemx);
$itemrx = $itemqx->fetch_assoc();
$check = $itemrx['records'];
<span class="summary12"><!-- class of javascript -->
<?php
if ($check == 1){
echo $count+1;
}else{
echo $count;
}
?>
Items
</span>
After trying lot of things i came up with the following solution and the issue has been solved.
Please need your opinion on this. Thanks
Button
<input onclick='updateTitems();' type="submit" class="btn-style-2 mg-left-5" value="ADD TO CART">
Script
function updateTitems(){
$.ajax({
url: "menu_update_total_items.php",
cache: false,
success: function(data){
$(".summary12").html(data);
//div or span reload script after success
setInterval(function () {
$('.summary12').load('inc/menu_update_total_items.php');
}, 1000);
}
});
}
menu_update_total_items.php
<?php
#session_start();
include ("inc/db.php");
$ses_mem = session_id();
$items = "select count(*) as trecords
from orders_temp
where user_id = '".$ses_mem."' ";
$item = $dba->query($items);
$count = $toitemszx->fetch_assoc();
?>
<a href="cart/review" class="cart-link">
<i class="fa fa-shopping-basket"></i>
<?php echo $count['trecords']; ?>
Items
</a>
i am working on a project and come across a module.
page1
user have to search from search bar which will take him to page 2.
page2
On page 2 all fetched results will get displayed to user in div's. Each result has a checkbox associated with it.
when i click on add to compare check box ,ajax call is executed and fetched selected result should appear in hidden div.
my problem is it is only shows first result in hidden div and not working with another result.
My code of page 2
<script type="text/javascript">
$(document).ready(function()
{
var check = $('#compare').val();
$("#compare").change(function() {
if(this.checked) {
$.ajax({
type: 'POST',
url: 'compare.php',
dataType : 'JSON',
data:{value : check},
success: function(data)
{
console.log(data);
$('#compare_box').html(data);
}
});
$("#compare_box").show();
}
else
{
$("#compare_box").hide();
}
});
});
</script>
</head>
<body>
<?php
$query = $_GET['search_bar'];
$query = "call fetch_data('$query')"or die(mysqli_error($conn));
$result = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($result))
{
$id = $row['course_id'];
$title = $row['course_title'];
$description = $row['course_description'];
$course_url = $row['course_url'];
$video_url = $row['course_video_url'];
$fee = $row['course_fee'];
$duration = $row['course_duration'];
$start_date = $row['course_start_date'];
$university = $row['university_name'];
$course_provider = $row['course_provider_name'];
$instructor = $row['instructor_name'];
$_SESSION['result'][$id] = Array('id'=> $id,'course_title' => $title,'course_description'=> $description,'course_url' => $course_url,'video_url' => $video_url,'fee' => $fee,'course_duration'=>$duration,'start_date'=>$start_date,'university' => $university,'course_provider'=>$course_provider,'instructor'=>$instructor);
?>
<div id='compare_box'>
</div>
<div class="col-md-3 photo-grid " style="float:left">
<div class="well well-sm">
<a href="final.php?id=<?php echo $id;?>&name=<?php echo $title;?>" target="_blank">
<h4><small><?php echo $title; ?></small></h4>
</a>
<br>
<input type ='checkbox' name="compare" id="compare" value="<?php echo $id;?>">add to compare
</div>
</div>
<?php
}
?>
page3 compare.php
<?php
session_start();
include 'includes/dbconfig.php';
$check = $_POST['value'];
$sql = "SELECT * from course_info_table where course_id = '$check' " or die(mysqli_error($conn));
$result = mysqli_query($conn,$sql);
$index = 0;
while($row = mysqli_fetch_array($result))
{
$title = $row['course_title'];
?>
<?php
}
echo json_encode($title);
?>
You can change
<input type ='checkbox' name="compare" id="compare" value="<?php echo $id;?>">
to
<input type ='checkbox' name="compare" class="compare" value="<?php echo $id;?>">
^you can only have one unique 'id' value in your html doc, which means your first id="compare" will work fine and others with id="compare" will be ignored by the DOM tree
Reference:
http://www.w3schools.com/tags/att_global_id.asp
I am having a little problem with this, every delete button is supposed to delete the record of its own id. If we click 164 it must delete the record of 164. It works fine if I remove the ajax and ask the form to validate directly, but if I use AJAX it only deletes the record of 1st record regardless of what button I press e.g. in current scenario it will always delete the record of 159 even if I press 164 button. My code gives the following output: Remember it works fine if I ask the form to validate directly from other PHP file.
This is my output please have a look at it. Its quite simple!
if(is_numeric($lumens) && $lumens < 5000 && $lumens >250){
if(is_numeric($THD) && $THD <= 20 && $THD >=0){
if(is_numeric($scaled_power_factor) && $scaled_power_factor >=0.9){
if(is_numeric($scaled_cct) && $scaled_cct <=5700){
if(is_numeric($scaled_cri) && $scaled_cri >=65){
if(is_numeric($scaled_input_power)){
$con = new mysqli(localhost, asd, myp, rec);
if(!$con){
echo "Couldn't connect to the database";
}
else{
$id = $_SESSION['user_id'];
$query = "INSERT INTO scaling_performance_data SET
MODEL_NUMBER = '$model_number',
LUMENS = '$lumens',
scaled_luminaire_efficacy = '$lm_w',
scaled_input_power = '$scaled_input_power',
THD = '$THD',
SCALED_POWER_FACTOR = '$scaled_power_factor',
SCALED_CCT = '$scaled_cct',
SCALED_CRI = '$scaled_cri',
HOUSING_VARIATION = '$housing_variation',
user_id = '$id'
";
if($con->query($query)){
$sql = "SELECT * FROM scaling_performance_data WHERE user_id='$id';";
$result = $con->query($sql);
if($result){
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
?>
<form>
<table>
<tr>
<th>adsf</th><th>adsf</th><th>adsf</th><th>adsf</th><th>adsf</th><th>adsf</th><th><input type="button" name ="delete_id" id="delete_id" value="<?php echo $row['ID'];?>" onclick="vlid();"/></th>
</tr>
</table>
<script type="text/javascript">
function vlid(){
var delete_id = $('#delete_id').val();
alert(delete_id);
$.post('validator.php',{
postdelete_id : delete_id
},
function(data){
$('#del').html(data);
}
)
}
</script>
</form>
<?php
}
}
validator.php is:
$id = $_POST['postdelete_id'];
$con = new mysqli(localhost, asd, myp, rec);
if(!$con){
echo "Couldn't connect to the database";
}
else{
$query="DELETE FROM scaling_performance_data WHERE ID='$id';";
if($con->query($query)){
echo "Your Result was deleted successful";
echo $id;
}else{
echo "There was a problem Please try again later";
}
}
The problem is that in your vlid() function, JQuery is only selecting the first element with id = delete_id. I would try passing the ID to the vlid() function like this:
<input type="button" ... onclick="vlid(<?php echo $row['ID'];?>)"/>
And then modify your vlid() function to accept the ID parameter.
Try var delete_id = $(event.target).val(); instead of: var delete_id = $('#delete_id').val();
1st ID must be unique so use
class="delete_id"
instead of
id="delete_id"
2nd remove onclick="vlid();" and use
$(document).ready(function(){
$('body').on('click','.delete_id',function(){
var getValue = parseInt($(this).val());
$.post('validator.php',{postdelete_id : getValue},function(data){
$('#del').html(data);
});
});
});
and to remove the tr which deleted use
$(document).ready(function(){
$('body').on('click','.delete_id',function(){
var thisBtn = $(this);
var getValue = parseInt(thisBtn .val());
$.post('validator.php',{postdelete_id : getValue},function(data){
$('#del').html(data);
thisBtn.closest('tr').remove();
});
});
});
I have a project where a user can have his own VirtualDiary online. He/She registers logs in and all that and is brought to a entry page with the date and a text area. The idea is that they will be able to click on two buttons on the top of the page titled NextPage and PreviousPage. These will call a jquery ajax function which will in turn change the value of EntryID + 1 or EntryID -1. This should change the value of pretty much everything on the page. But nothing happens even though the ajax call logs success. I am very new to ajax so I have probably Done something really stupid. Thanks in advance
PHP
<?php
session_start();
//error_reporting(E_ERROR|E_WARNING);
mysql_connect("localhost","root","") or die ("cannot");
mysql_select_db("virtualdiary") or die ("db");
$JoinDateQuery = mysql_query("SELECT * FROM users WHERE UID = '".$_SESSION['UID']."' ");
if($JoinDateQuery === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row = mysql_fetch_array($JoinDateQuery))
{
$JoinDate = $row[4];
}
$TodayDate = date("Y/m/d");
$today = strtotime($TodayDate);
$joinTime = strtotime($JoinDate);
$datediff = $today - $joinTime;
$_SESSION["EntryID"] = floor($datediff/(60*60*24));
$EntryID = $_SESSION["EntryID"];
$_SESSION['EntryDate'] = date('Y-m-d', strtotime($JoinDate. ' + '.$EntryID .'days'));
$EntryDate = $_SESSION['EntryDate'];
$id = $_SESSION["UID"] ;
if (isset($_POST["entry"])){
$entry = $_POST["entry"];
$deletion = "DELETE FROM entries WHERE UserID = '".$_SESSION['UID']."' and EntryID = '".$EntryID."' ";
mysql_query($deletion);
$submission = "INSERT INTO `virtualdiary`.`entries` (`Entry`, `UserID`,`EntryID`) VALUES ('". $entry . "', '".$_SESSION['UID']."', '".$EntryID."')";
mysql_query($submission);
}
$ThePost = 'SELECT * FROM entries WHERE UserID = "'. $_SESSION['UID'] .'" and EntryID = "'.$EntryID.'"';
$result = mysql_query($ThePost);
if($result === FALSE) {
die(mysql_error());
}
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="Entry.css"/>
<title>Home</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function(){
$('#NextDay').click(function(){
$.ajax({
type: "GET",
url: "Home.php",
data: "$EntryID = $EntryID + 1",
success: console.log("success")
}); //ajax call
});//on click next day
});//document ready</script>
</head>
<body>
<section>
<button id="previousDay" class="day">Previous Day</button>
<button class = "day" id = "date">Joined: <?php echo $JoinDate; ?></br>
Entry Number: <?php echo $EntryID + 1; ?></br>
EntryDate: <?php echo $EntryDate ; ?>
</button>
<button class="day" id = "NextDay">Next Day</button>
<h1>Entry: </h1>
<form method="post" action="Home.php">
<textarea name="entry" rows="24" cols="80">
<?php
while($row = mysql_fetch_array($result))
{
echo $row['Entry'];
}
?>
</textarea>
</br>
</br>
<input name="submit" type="submit"/>
</form>
<button id="calender" class = "day"><h1>Calender</h1></button>
<button id="LogOut">Log Out</button>
</section>
</body>
</html>
By the way EntryID returns result of 4 (or the default for the user on this day) so its pretty obvious the problem has something to do with the Data: part of the ajax or that I am not using ajax in the right context to achieve what I want.
EDIT: I have just been made aware that $EntryID = $EntryID + 1 has to be defined somewhere but where and I can't just plonk it down somewhere cause that would change the first instance of entry id I think.
First of all, I think you should be making an AJAX "POST" request, not a "GET" request. (Just industry standard, since you're sending a value through to a server).
Second, I'm not sure, where you got the syntax to create a data value for that GET request (really weird) however!, in the ajax call where I edited your code, there should now be the correct way of creating & sending de-serializable data.
EDIT
Forgot to mention, that the values sent from the AJAX, can be retrieved using $_REQUEST['xyx'] or $_POST['xyz'].. If you are using get, you can use $_GET['xyz']
UNTESTED
//error_reporting(E_ERROR|E_WARNING);
mysql_connect("localhost", "root", "") or die ("cannot");
mysql_select_db("virtualdiary") or die ("db");
$JoinDateQuery = mysql_query("SELECT * FROM users WHERE UID = '" . $_SESSION['UID'] . "' ");
if ($JoinDateQuery === FALSE) {
die(mysql_error()); // TODO: better error handling
}
while ($row = mysql_fetch_array($JoinDateQuery)) {
$JoinDate = $row[4];
}
$TodayDate = date("Y/m/d");
$today = strtotime($TodayDate);
$joinTime = strtotime($JoinDate);
$datediff = $today - $joinTime;
$_SESSION["EntryID"] = floor($datediff / (60 * 60 * 24));
$EntryID = $_POST["EntryID"];
$_SESSION['EntryDate'] = date('Y-m-d', strtotime($JoinDate . ' + ' . $EntryID . 'days'));
$EntryDate = $_SESSION['EntryDate'];
$id = $_SESSION["UID"];
if (isset($_POST["entry"])) {
$entry = $_POST["entry"];
$deletion = "DELETE FROM entries WHERE UserID = '" . $_SESSION['UID'] . "' and EntryID = '" . $EntryID . "' ";
mysql_query($deletion);
$submission = "INSERT INTO `virtualdiary`.`entries` (`Entry`, `UserID`,`EntryID`) VALUES ('" . $entry . "', '" . $_SESSION['UID'] . "', '" . $EntryID . "')";
mysql_query($submission);
}
$ThePost = 'SELECT * FROM entries WHERE UserID = "' . $_SESSION['UID'] . '" and EntryID = "' . $EntryID . '"';
$result = mysql_query($ThePost);
if ($result === FALSE) {
die(mysql_error());
}
?>
<html>
<head>
<link type="text/css" rel="stylesheet" href="Entry.css"/>
<title>Home</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function () {
$('#NextDay').click(function () {
$.ajax({
type: "POST",
url: "Home.php",
data: {
EntryID: '1' //not sure (this is quite conditional I guess)
},
success: console.log("success")
}); //ajax call
});//on click next day
});//document ready</script>
</head>
<body>
<section>
<button id="previousDay" class="day">Previous Day</button>
<button class="day" id="date">Joined: <?php echo $JoinDate; ?></br>
Entry Number: <?php echo $EntryID + 1; ?></br>
EntryDate: <?php echo $EntryDate; ?>
</button>
<button class="day" id="NextDay">Next Day</button>
<h1>Entry: </h1>
<form method="post" action="Home.php">
<textarea name="entry" rows="24" cols="80">
<?php
while ($row = mysql_fetch_array($result)) {
echo $row['Entry'];
}
?>
</textarea>
</br>
</br>
<input name="submit" type="submit"/>
</form>
<a href="Calender.php">
<button id="calender" class="day"><h1>Calender</h1></button>
</a>
<button id="LogOut">Log Out</button>
</section>
</body>
</html>
From http://api.jquery.com/jquery.ajax/
data
Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
You're trying to happened "$EntryID = EntryID + 1" to "home.php"
"home.php$EntryID = EntryID + 1" doesn't seem like a correct url ?
You should try with the error callback set if you want more informations on the request status.