Ajax update issues (SQL and extensions) - javascript

I have an ajax update feature with some specific issues, I am sure this just needs some tweaking before it will work out 100%.
I will summarize the issues below as clearly as I can.
I have two files that interact with each other:
orders.php
orders-claimed.vc.php
my ajax is trying to update a table int value based on the button clicked. NO=0, YES=1, CANCELLED=2.
orders.php
start of the page
<?php
session_start();
require_once('orders-claimed.vc.php');
?>
table column of the buttons:
<td data-target="scheduled">
<input id='userId' type='hidden'/>
<?php
if ($rowOrder['scheduled'] == 1) {
?>
<button class="btn-success">YES</button>
<?php
} else if ($rowOrder['scheduled'] == 0) {
?>
<button class="btn-danger">NO</button>
<?php
} else if ($rowOrder['scheduled'] == 2) {
?>
<button class="btn-warning">CANCELLED</button>
<?php
}
?>
</td>
modal used for interaction with the table
<!-- Modal content-->
<div class="modal-content" style="width: 300px; margin: 0 auto;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div class="form-group">
YES<br>
NO<br>
CANCEL
</div>
</div>
</div>
</div>
ajax code
<script>
$(document).ready(function(){
// append values in input fields
$(document).on('click','a[data-role=update]',function(){
var id = $(this).data('id');
var scheduled = $('#'+id).children('td[data-target=scheduled]').text();
$('#userId').val(id);
$('#myModal').modal('toggle');
});
// now create event to get data from fields and update in database
$('#update_no').click(function(){
var id = $('#userId').val();
var scheduled = 0;
$.ajax({
url : 'orders-claimed.vc.php',
method : 'post',
data : {scheduled: scheduled , id: id},
success : function(response){
// now update user record in table
$('#'+id).children('td[data-target=scheduled]').html('<button class="btn-danger">NO</button>');
$('#myModal').modal('toggle');
}
});
});
$('#update_yes').click(function(){
var id = $('#userId').val();
var scheduled = 1;
$.ajax({
url : 'orders-claimed.vc.php',
method : 'post',
data : {scheduled: scheduled , id: id},
success : function(response){
// now update user record in table
$('#'+id).children('td[data-target=scheduled]').html('<button class="btn-success">YES</button>');
$('#myModal').modal('toggle');
}
});
});
$('#update_cancelled').click(function(){
var id = $('#userId').val();
var scheduled = 2;
$.ajax({
url : 'orders-claimed.vc.php',
method : 'post',
data : {scheduled: scheduled , id: id},
success : function(response){
// now update user record in table
$('#'+id).children('td[data-target=scheduled]').html('<button class="btn-warning">CANCELLED</button>');
$('#myModal').modal('toggle');
}
});
}); });
</script>
Note that all code above are all in the same file (orders.php)
table column UI
modal
SQL table name "order"
these are my extensions in the page. most are being stored in a folder and are being linked.
<script src="../_lib/v/jquery.slim.min.js"></script>
<script src="../_lib/v/bootstrap/js/bootstrap.js"></script>
<script src="../_lib/v/jquery-ui/jquery-ui.js"></script>
<script src="../_lib/v/jscolor/jscolor.js"></script>
<script src="js/cms.js"></script>
<link href="../_lib/v/bootstrap/css/bootstrap.min.css" rel="stylesheet">
Ajax does not function under slim.min.js and gets the "not a function error", so I changed it to the regular version of jquery from https://code.jquery.com/jquery-3.3.1.js
PROBLEM
If I switch to the full version of jquery, the column updates but the session (the logged in user) ends and logs out automatically. Why is this happening?
My second problem is in the orders-claimed.vc.php file
db.php
<?php
class config_db {
public function init() {
$db = new PDO('*MY DATABASE DETAILS GO HERE*');
date_default_timezone_set('Hongkong');
return $db;
}
}
?>
orders.claimed.vs.php
connecting to the database:
$routePath = "../";
require_once($routePath . "_config/db.php");
$dbConfig = new config_db();
$db = $dbConfig->init();
SQL update
if(isset($_POST['id'])){
$orderid = $_POST['id'];
$scheduled = $_POST['scheduled'];
$stmt = $db->prepare("UPDATE order SET scheduled = '$scheduled' WHERE orderid = '$orderid'");
$stmt->execute(); }
PROBLEM
the SQL code above does not update the table (the one shown in the screenshot, but ajax just updates the look of the button from the success functions (It goes back to its original value when the page refreshes). I would like to know what is the issue. It should be connecting to the buttons since it is using "if(isset($_POST['id']))".
I hope I have provided a clear explanation to my two problems, thank you for any help.
UPDATE
I used the following code below to check for an error on the button update:
console.log( 'scheduled: ' + scheduled + ' orderid: ' + $('#userId').val() );
when the button updates and the page refreshes that also logs out the session, i get the following error:
jquery-ui.js:1951 Uncaught TypeError: Cannot read property 'step' of undefined
at String.<anonymous> (jquery-ui.js:1951)
at each (jquery.slim.min.js:2)
at Function.color.hook (jquery-ui.js:1913)
at jquery-ui.js:1963
at jquery-ui.js:2005
at jquery-ui.js:14
at jquery-ui.js:16

From what you have listed, I think that you might have "session_destroy()" somewhere in your php files (though it might not be put up here). Try commenting that out and see if the session ends or not. Hope it helps you :).

Related

"Like" system PHP, using AJAX

i want to make like/unlike system with PHP and jQuery/AJAX..
Here is my form in PHP foreach... Here i have own id's for every form;
<?php foreach ($vid as $var) { ?>
<form class="classform" action="functions/videolike.php" method="post">
<input type="text" name="id" value="<?php echo $var['video_id'];?>">
<button class="submitbuttonclass"type="submit">Like</button>
</form>
<?php } ?>
Here is my Ajax script;
<script>
// this is the id of the submit button
$(".submitbuttonclass").click(function() {
$.ajax({
type: 'post',
url: "functions/videolike.php",
data: $(".classform").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
the codes are working but not correctly;
When i click "like" button is working good, i cheked the database, caunting, inserting, deleting , working good...
But I want to make this with AJAX becouse, refreshing page is stopping the video when user watching video if he click the like button. Video is preloading becouse page refresh...
After i add my ajax script its working. But when i am clicking the like button, AJAX is posting to PHP, only the last id in the foreach loop,
THE Question?
How to make AJAX to get all of the id's in PHP foreach loop ??
And this is my videolike.php if you want to check;
<?php
session_start();
if($_POST['id'] && #$_SESSION["userid"]){
require_once "connectdb.php";
$id = $_POST["id"];
$VLcheck = "SELECT count(*) FROM `videolikes` WHERE user_id = ? AND liked_vid_id=?";
$reslike = $conn->prepare($VLcheck);
$reslike->execute(array($_SESSION["userid"],$id));
$VLrow = $reslike->fetchColumn();
echo $VLrow;
if ($VLrow > 0){
$VLcheck = "DELETE FROM `videolikes` WHERE user_id = ? AND liked_vid_id=?";
$reslike = $conn->prepare($VLcheck);
$reslike->execute(array($_SESSION["userid"],$id));
} else {
$curentsess= $_SESSION["userid"];
$INSlike = $conn->prepare("INSERT INTO videolikes(user_id, liked_vid_id)
VALUES('$curentsess','$id')");
$INSlike->execute();
}} else {die;}
?>
As you have a lot forms with class .classform, so how do you think your script should select the proper one?
The asnwer is - script can't, you should help it). Use .closest function to find closest <form> for a clicked button:
$(".submitbuttonclass").click(function() {
var form = $(this).closest("form");
// or find closest element with class `classform`
//var form = $(this).closest(".classform");
$.ajax({
type: 'post',
url: "functions/videolike.php",
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});

Insert multiple label fields using for loop in a form

I'm using jquery ajax in codeigniter framework to load a pop up modal on button click. I pass ajax request to a function in controller and receive some data which should be shown in my pop up modal. Number of labels of the modal is depend on the size of the array received by the ajax request.
I have no idea how to do this. But I tried of passing the size of the received array to a hidden type input field in form created on the pop up modal.
Following is my javascript.
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click','#btn_more', function() {
empId = $('#employeeId').html();
fiter_employees(empId);
});
function fiter_employees(empId){
var empSet ={
empId: empId,
method: 'ajax'
};
var empSentUrl = 'http://localhost/eventmanagementsystem/index.php/employee/get_emp_positions';
$.ajax({
type: 'POST',
dataType: 'json',
url: empSentUrl,
data: empSet,
success: function(data){
$('#modal_pkg1').html(data.empPosition.length)
$('#employeePositions').modal();
}
});
}
});
In my pop up model I used the following codes which is not succeeded.
<div id="employeePositions" class="modal fade">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Employee Name :</h4><br/>
<form>
<?php
for ($i=0; $i < ?>
<input type="hidden" id="modal_pkg1" value="modal_pkg1" />
<?php
; $i++) { ?>
<h4 class="modal-title" id="event_name"></h4>
<?php
} ?>
</form>
Can someone tell me the correct me of doing this please...
Your PHP code has executed the moment you load the page, so when you change the modal_pkg1 value, nothing will happen.
Also, the foor loop itself will not work on load, as it's expecting a number that is not there.
I suggest you do it fully in JS, remove all php code from your script; something like below :
in your Ajax success function :
.success(function(data){
var htmlStr = ''
for(var i=0;i<data.empPosition.length;i++){
htmlStr+='<whatever html element you want to display>'
}
$('form').html(htmlStr) // add the generated html string to the <form> element
$('#employeePositions').modal();
}

How to pass dynamically generated div id to ajax?

Hey i've got some problem.
My website is divided into two columns. On the left is sidebar which contains list of users dynamically generated from database, on the right-hand side should be unique chart generated by javascript framework (ajax) based on user_id. And this chart should be shown after choosing some user from list. The php file live-data.php which is used by this javascript/ajax needs GET parameter. Now it's:
url: "php/live-data.php"
and
$.get("php/live-data.php?Consultar=1", function(UltimosDatos)
but it should be
url: "php/live-data.php?user_id=2"
and
$.get("php/live-data.php?user_id=2&Consultar=1", function(UltimosDatos)
Where 2 is user_id got after clicking some user name from dynamically generated list. The php script live-data.php is ready for GET variable and returns proper json for chart framwork (this javascript shown below). I dont know how to pass div id to this ajax code.
HTML+PHP:
<div id="left" class="pre-scrollable col-lg-3">
<div class="list-group">
<?php include("php/dbSettings.php");
$result = $conn->query("SELECT * FROM user ORDER BY user_id");
if (!$result) {
die(mysqli_error($conn));
}
while ($user = mysqli_fetch_array($result)){
echo '' . $user['firstName'] . " " .$user['lastName'] . '';
}
?>
</div>
</div>
<div id="right" class="col-lg-9">
<div class="tab-content">
<?php include( "php/dbSettings.php");
$result=$ conn->query("SELECT * FROM users ORDER BY user_id");
if (!$result) {
die(mysqli_error($conn));
}
while ($user = mysqli_fetch_array($result)){
echo '<div class="tab-pane" id="'.$user['user_id'].'">
<div id="chart" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
</div>';
} ?>
</div>
</div>
Javascript/Ajax:
<script>
$(function() {
$(document).ready(function() {
var ultimox;
var ultimoy;
$.ajax({
url: "php/live-data.php", //i want this line to be "php/live-data.php?user_id=2" and 2 is variable got from user list onlick
type: 'get',
success: function(DatosRecuperados) {
$.each(DatosRecuperados, function(i, o) {
//some deleted code - unimportant
});
//some deleted code - unimportant
$('#chart').highcharts({
//draws chart
});
}
});
});
setInterval(function() {
$.get("php/live-data.php?Consultar=1", function(UltimosDatos) { //i want this line to be "php/live-data.php?php/live-data.php?Consultar=1&user_id=2" and 2 is variable got from user list onlick
//updates chart
}
});
}, 1000);
//some deleted code - unimportant
});
</script>
I hope someone can help me on my way.
Thanks, Paul
It looks like the hash will be set to the user id when the anchor is clicked, based on this <a href="#'.$user['user_id'].'" so you could read the hash value and pass it as data on the request. Either this:
$.ajax({
url: "php/live-data.php?user_id=" + window.location.hash.substr(1),
type: 'get',
success: function(DatosRecuperados) {
// ...
}
});
or this:
var dataObj = {};
dataObj['user_id'] = window.location.hash.substr(1); //create a data object to pass on query string, set user id value
$.ajax({
url: "php/live-data.php",
type: 'get',
data: dataObj, //pass object with request
success: function(DatosRecuperados) {
// ...
}
});

Button for php function doesnt work after ajax call

I am attempting to add, or subtract a pts field in a database based on if you press a button and then update the content on the page, I also have the fields that the pts are being display in , on a timer with Ajax to auto-refresh.
I am using this script to call the page:
$(document).ready(function(){
var timer, delay = 1000; // 1 second(s) counted in milliseconds
var Pts = ''; //ID value of users answer
var info = {'userPts': Pts}; //naming POST for php
timer = setInterval(function(){
$.ajax({
url: "inc/ans.php", //sends to ans page where php function updates DB
type: "POST",
data : info, //stuff being sent to php
success:function(data)
{
$("div #ans").html(data); //Retrieves answers made by user
}
});
}, delay);
My issue is when I make this call the only way currently to click the buttons is to manually refresh the entire page and then I am able to click the buttons and update the users pts value. I am able to do one or the other but not at the same time, I can have it where it auto-refreshes the content but I can’t have the button press complete the action. And I can have the buttons be able to be pressed but I can’t have the content auto-refresh.
The PHP functions to add and subtract are about the same they are like this:
function addPoint($mysqli, $id)
{
$stmt = $mysqli->prepare('
UPDATE tbl_user
SET user_pts = user_pts + 1
WHERE user_id = ?');
$stmt->bind_param('i', $id);
$stmt->execute();
$rows = $stmt->affected_rows;
$stmt->close();
if($rows == 1)
{
return true;
}
else
{
return false;
}
}
Only difference between the two functions is the fact that its -1 or +1. Any ideas on why this happens? Is it the Ajax call this is interfering with the PHP function or vic. versa?
EDIT: This is the code that is being displayed to the instructor with the buttons
function getScore_I($mysqli)
{
$stmt = $mysqli->prepare('
SELECT user_name, user_pts, user_id
FROM tbl_user');
$stmt->execute();
$stmt->bind_result($user, $pts, $id);
$O ="";
$x = 1;
$O.="<table style=\"text-align:center;width: 100%\"><form action=".$_SERVER['PHP_SELF']." method=\"POST\">";
while($stmt->fetch())
{
if($x%2)
{
$O.= "<tr style=\"text-align:center;width: 100%\">
<td>".$user."</td>
<td>
<button name=\"userIDmiunus\" type=\"submit\" value=\"".$id."\">-</button>
</td>
<td>".$pts."</td>
<td>
<button name=\"userIDplus\" type=\"submit\" value=\"".$id."\">+</button>
</td>
</tr>";
$x++;
}
else
{
$O.= "<tr style=\"text-align:center;width: 100%\">
<td>".$user."</td>
<td>
<button name=\"userIDmiunus\" type=\"submit\" value=\"".$id."\">-</button>
</td>
<td>".$pts."</td>
<td>
<button name=\"userIDplus\" type=\"submit\" value=\"".$id."\">+</button>
</td>
</tr>";
$x++;
}
}
$O.= "</form></table>";
// close statement
$stmt->close();
return $O;
}
Is it the case that the button elements are included in the code brought in via AJAX? If so, you need to use .on(), as in:
$(document).on('click', '.buttonClassName', function(){
//do your click code here
});
Reviewing your code, it looks like you are just doing a .load(), which is a shortcut version of $.ajax(). I also prefer using $.ajax() in all circumstances - use $.load(), $.get() and $.post() are not as well structured as the full $.ajax()
When the new data is injected into the DOM via .html(), any controls are not bound to javascript code, since the binding code was run prior to their injection. Two solutions: you can also inject some additional javascript and recreate those bindings -- which means much duplicate code in the DOM -- or you can use .on() which works for the elements currently in the DOM, but also for all future elements injected into the DOM that have that specific class or ID or whatever jQuery selector you use.
Another possibility could be that you need to use AJAX to access your PHP function. See this post and the post it references/links to regarding AJAX. Check out the examples.
Yes, you can call another AJAX function inside the .on(), and that is probably what you need to do.
Recall that AJAX is just a method for running PHP code after the web page has been rendered, and without refreshing/leaving the current page.
Code could look something like this:
$(document).on('click','.buttonClass', function(){
var Pts = ''; //ID value of users answer
var uid = $('hidden_input_where_you_stored_userID').val();
var info = {'userID': uid, 'userPts': Pts}; //naming POST for php
$.ajax({
url: "inc/another_file.php",
type: "POST",
data : info,
success: function(data) {
//whatever you need to do after updating point score
}
});
});
another_file.php:
<?php
$id = $_POST['userID'];
$pts = $_POST['userPts'];
//do your DB update

data-attribute wont submit content

I'm busy developing my first Twitter application. However, I'm stuck at something basic which I cant solve for some reason. I used to use data-attributes alot, but I just cant get it to work. It just wont submit the content of my data-attribute
Part of my HTML.
<div id="invTweet" class="_invitation-tweet-inner no-select" data-tweet="Here comes the content of the tweet which will be submitted">Here comes the content of the tweet</div>
<div id="post-invitation-tweet" class="button blue post-tweet">Post Tweet</div>
Part of my Javascript
var tweet = $("#invTweet").attr("data-tweet");
$(document).on('click',"#post-invitation-tweet",function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "../includes/db-requests/db-postInvitationTweet.php",
data: {tweet:tweet},
success: function(data){ finishInvitationTweet(data); }
});
});
function finishInvitationTweet(data) {
alert(data);
}
I use alert(data) for debugging purposes. When I click on the Post Tweet button, an alert will open with the echo "Undefined index: tweet emptyTweet". Look below for a snippet of my db-postInvitationTweet.php:
//Get Tweet data
$tweetMsg = safe($mysqli,$_POST['tweet']);
//Check if $tweetMsg is empty. No > post tweet.
if ($tweetMsg != '') {
$post_tweet = $connection->post('statuses/update', array('status' => $tweetMsg));
if (187 == $connection->http_code) {
echo "statusDuplicate";
die();
}
if (!$post_tweet) {
echo "tweetError";
} else {
//Update the invitation_sent column in database
$stmt = $mysqli->prepare("UPDATE members SET invitation_tweet = '1' WHERE oauth = ? ") or die (mysqli_error($mysqli));
$stmt->bind_param('s', $access_token['oauth_token']);
$stmt->execute();
$stmt->close();
echo "tweetSuccess";
}
} else {
echo "emptyTweet";
}
What am I missing :')
What version of jQuery are you using? As of around version 1.4 the appropriate way to access a data attribute would be through the data() method, see method signature and docs here.
If you change that you may be able to get it to work just fine. See jsFiddle with working solution as proof of concept.
Changed
var tweet = $("#invTweet").attr("data-tweet");
To
var tweet = $("#invTweet").data("tweet");

Categories

Resources