As the title states, I seem to be having an issue with incrementing a variable in my .php file code, it modifies the value in the database, acc_points, to 1 after I increment acc_points by one in the variable above. What the code does is send an ajax request to the php which then updates the data in the mysql database and then returns the data to the js and the js will then alert the data.
The incrementation somehow changes the value of acc_points from 5 to 1. I also considered if the problem had something to do with sessions. I've looked around for relevant information but couldn't find a solution. Would like to find out the real cause of this issue. Thanks!
Here are the codes:
.php file
<?php
require 'dbcon.php';
session_start();
$acc_points = $_SESSION["acc_points"];
$acc_id = $_SESSION["acc_id"];
if(isset($acc_points))
{
$acc_points++;
}
$result = $con->prepare(" UPDATE `points` SET `acc_points` = ? WHERE `acc_id` = ? ");
$result->bind_param("ii", $acc_points, $acc_id);
$result->execute();
if($acc_points != null)
{
$response = $acc_points;
echo $_GET['callback'] . '(' . json_encode($response) . ')';
}
else
{
$response = "'Failed. Please try again.'";
echo $_GET['callback'] . '(' . json_encode($response) . ')';
}
//connection closed
mysqli_close ($con);
?>
js file
$(document).ready(function() {
$("#qrtest").click(function() {
{
$.ajax({
type: "GET",
url: "http://127.0.0.1/MP/appqrcode.php?callback=?",
dataType: 'JSONP',
async: false,
jsonp : "callback",
jsonpCallback: "jsonpcallback",
success: function jsonpcallback(response)
{
alert(response.acc_points);
}
})
}
});
});
The first problem is that you are checking the value of $acc_points in the code below, but you are executing the query regardless of whether it's null or not null
if(isset($acc_points))
{
$acc_points++;
} // if condition ends here. Insert command will always be executed.
Then after the comand has been executed you check the value again
if($acc_points != null) /// insert has already happend.
{
}
So you should restructure your code, but better still, you don't need this approach at all. Why not just?
$result = $con->prepare(" UPDATE `points` SET `acc_points` = acc_points+1 WHERE `acc_id` = ? ");
This increments the value already in the database.
Related
From the selected value (from the form) I create a variable (var parcela).
var parcela;
$(document).ready(function(){
parcela = localStorage.getItem("parcela");
if (parcela !== '') {
$('#parcela').val(parcela);
}
$("#parcela").on('change',function() {
selectBoxVal_1 = $('#parcela').val();
if (typeof(Storage) !== "undefined") {
localStorage.setItem("parcela", selectBoxVal_1);
} else {
alert('Sorry! No Web Storage support..');
}
location.reload();
});
});
From the created variable (parcela), I create a session variable in PHP.
$.post("phpscripts/session.php", {"parc_id": parcela});
PHP (session.php)
<?php
session_start();
$parcela = $_POST["parc_id"];
$parcela_int = (int)$parcela;
if($_POST){
$_SESSION['parcela_id'] = $parcela_int;
}
?>
After that, the created session variable urge to another php script
query.php
<?php
session_start();
require("common.php");
$user_id = htmlentities($_SESSION['user']['id_korisnika']);
$parc = $_SESSION['parcela_id'];
try
{
$stmt = $db->prepare("SELECT y_cent, x_cent FROM parcele WHERE id_korisnika='$user_id' AND id_parcele='$parc' ");
$stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
....
This all works perfectly!
However, when I call a php script with query (query.php) in javascript, there is a problem. JS takes the previous session variable instead of the last selected.
$.ajax({
url: 'phpscripts/query.php',
type: 'GET',
success : function(data) {
chartData = data;
//console.log(chartData);
...
Does anyone know what the problem is? I'm trying for two days to solve this ...
Note: The javascript code is contained in a single script.
I solved the problem. I had to extract part of javascript code that calls the php script into a separate script. I called the new JS script with jQuery getScript() Method.
Thank you #knets.
So, I've been looking for a variety of sources to answer my question the last few day and thus have found nothing that's worked for me. I'll preface this further by saying that in regards to PHP and Javascript I started learning them like a week ago. I also understand that there will likely be better ways to format/write the code I'm about to post so please bear with me! :)
Essentially, I am trying to use a page name play.php in combination with AJAX to echo MYSQL queries back onto the page inside certain page elements.
So the code for main.js which is linked directly to play.php. I've tried about three different way that I've seen in various answers and have not gotten the information I wanted. I either get no response or I get undefined in all of them.
function selectChar(uname, cname)
{
var data = {
username : uname,
charname : cname
};
$.ajax({
data : data,
type : 'Get',
url : 'start.php',
dataType:"json",
success : function (result) {
var data_character = JSON.parse(result);
var cnamediv = document.getElementById('charactername');
cnamediv.innerHTML = "";
cnamediv.innerHTML = data_character[0].name;
}
});
}
The one above I see most often and the one below I just found earlier today. I get undefined when I attempt to call the array.
function selectChar(uname, cname)
{
$.get("start.php?username="+uname+"&charname="+cname).done(function(data_character){
var cnamediv = document.getElementById('charactername');
cnamediv.innerHTML = "";
cnamediv.innerHTML = data_character[0].name;
});
}
and finally the PHP code that queries the database and echos the data back.
<?php
$conn = new mysqli($hostname,$username,$dbpassword, $dbname);
if(!$conn) {
die('Could not connect: ' . mysql_error());
}
$username = $_GET['username'];
$charname = $_GET['charname'];
$sql = "SELECT `id`, `username` FROM `users` WHERE `username` ='$username'";
$result = mysqli_query($conn,$sql);
//Send the array back as a JSON object
echo json_encode($result);
?>
I'm not looking for someone to do work for me but I do require some guidance here. What would be an appropriate way to make this work? Is my code terribly incorrect? Am I missing an aspect of this altogether? Please, I would really seriously appreciate any help someone could give me!
P.S. I did just get done reviewing several other similar questions none of which seemed to help. Either there was never a conclusive outcome as to what worked for them or the solution didn't work when I attempted it.
try this:
php get post and return json_encode
if(!$conn) {
die('Could not connect: ' . mysql_error());
}
$username = $_POST['username'];
$charname = $_POST['charname'];
$sql = "SELECT `id`, `username` FROM `users` WHERE `username` ='$username'";
$result = mysqli_query($conn,$sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
//Send the array back as a JSON object
echo json_encode($rows);
?>
JS ajax response and request
$.ajax({
data : data,
type : 'POST',
url : 'start.php',
dataType:"json",
success : function (result) {
console.log(result);
document.getElementById('charactername').innerHTML = result[0].username;
}
});
Hey Logan the issue may be with how the AJAX request is being sent. Try adding the processData property to your request and setting it to false. It just means the data won't be read as a query string and it is as raw data.
$.ajax({
data : data,
type : 'POST',
url : 'start.php',
dataType:"json",
processData: false,
success : function (result) {
console.log(result);
document.getElementById('charactername').innerHTML = result[0].username;
}
});
I would also try echo json_encode($_POST) to see if the you get the following response back :
{username: "hello", charname: "hl"}
I have following code which is working in localhost in windows. But in the server same code fails.
It's the if condition which is not getting executed write even if data==found; I checked the returned data value which is found but cant figure out why the code is not executing properly
function checkAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "ajaxcheck.php",
data:'tran_id='+$("#tran_id").val(),
type: "POST",
success:function(data){
console.log(data);
//var x=data;
$("#loaderIcon").hide();
//console.log((data=="found"));
if(data=="found")
{
$("#singlebutton").prop('disabled', false);
console.log("fail");
$("#tran_id-status").html("Found");
}
else
{
console.log(data);
$("#singlebutton").prop('disabled', true);
$("#tran_id-status").html("");
console.log("ss");
}
},
error:function (){}
});
}
Here is ajaxcheck.php
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
$space=" ";
if(!empty($_POST["tran_id"])) {
$result = mysql_query("SELECT count(*) FROM bank WHERE tran_id ='" . $space.$_POST["tran_id"] . "'");
$row = mysql_fetch_row($result);
$user_count = $row[0];
if($user_count>0) {
// echo "<span class='status-not-available' id=\"stat\"name=\"stat\" value=\"ok\"> Transaction Details Found.</span>";
echo"found";
}else{
//echo "<span class='status-available' id = \"stat\" name =\"stat\"value=\"not\"> (Enter Valid transaction id to submit)</span>";
echo"notfound";
}
}
?>
The issue is that your data variable is coming back with a new line character. There are two solutions to this 1. trim the returned value. 2. figure out why the php is serving a new line.
Solution 1:
if(data.trim()=="found")
This uses the JS trim function, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim.
Solution 2:
Try removing the ?> from the end of your PHP file (the PHP file will still be valid). This way if there are extra lines after it they won't be served as output and the JS wont receive them.
From the manual:
If a file is pure PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script.
I am trying to implement a timer. I learned this idea from a SO post.
<?php
if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['username']))
{
//secondsDiff is declared here
$remainingDay = floor($secondsDiff/60/60/24);
}
?>
This is my php code. My php,html and JS codes are in the same page. I have a button in my html. When a user clicks on the html page, It will call a Ajax function
//url:"onlinetest.php",
//dataType: 'json',
beforeSend: function()
{
$(".startMyTest").off('click');
setCountDown();
}
It will call setCountDown() method, which contains a line at the very beginning
var days = <?php echo $remainingDay; ?>;
When i run the page, it says[even before clicking the button] "expected expression, got '<'" in the above line. My doubt is
Why this php variable get replaced before i am triggering the button. Please let me know hoe to solve this or how to change my idea.
The problem is, since initial load, $_POST values aren't populated (empty on first load),
That variable you set is undefined, just make sure you initialize that variable fist.
<?php
// initialize
$remainingDay = 1;
if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['username']))
{
//secondsDiff is declared here
$remainingDay = floor($secondsDiff/60/60/24);
echo json_encode(array('remaining_day' => $remainingDay);
exit;
}
?>
<script>
var days = <?php echo $remainingDay; ?>;
$('.your_button').on('click', function(){
$.ajax({
url: 'something.php',
dataType: 'JSON',
type: 'POST',
beforeSend: function() {
// whatever processes you need
},
success: function(response) {
alert(response.remaining_day);
}
});
});
</script>
That is just the basic idea, I just added other codes for that particular example, just add/change the rest of your logic thats needed on your side.
You can pass a php variable into JS code like
var jsvariable ="<?php echo $phpvariable ?>";
NOTE:
If you ever wanted to pass a php's json_encoded value to JS, you can do
var jsonVariable = <?php echo $json_encoded_value ?>; //Note that there is no need for quotes here
Try this,
var days = "<?php echo $remainingDay; ?>";
I am facing some trouble in passing a simple variable from a php to javascript file.
I have a form which submits through a php file which basically updates the record at the server end. And if the updation is succesful, I just want to pass the message back to the javascript where I can update it on a certain section of the page.
My codes are:
Javascript code - abc.js
function expand_cards(project, SlNo)
{
name = project['project_name'];
j = "ShowForm-"+SlNo+"";
s = "<div class='edit_project_card'>";
s += "<form method='post' action='Edit_Project.php'><div class='project_form'>
// Form Contents
s += "<div class='Form_button'> <input type='submit'> </div>";
s += "</form></div>";
$("#"+j+"").html(s);
response = $.parseJSON(data);
$("#"+j+"").html(response);
}
PHP file - Edit_Project.php
<?php
//The updation stuff at the server end
if (!mysqli_query($connection,$sqlquery)) {
$response = "'Error in your code: ' . mysqli_error($connection)";
}
else {
$response = "1 record updated";
}
echo json_encode($response);
mysqli_close($connection);
?>
But the problem is the screen is printing $response variable as it is and not exactly passing it back to the javascript function as wished. I know I can use a $.post function which can can receive argument but it's a long form and passing parameters would be difficult in that.
Can anybody help me out here ?
Thanks
Dirty, but it will work:
<script type="text/javascript">
var my_var = <?php echo $some_variable; ?>
// Do something with the new my_var
some_func(my_var);
</script>
I wouldn't do too much detailed stuff with this though, if you can use AJAX that is better.
Note, this can only work on a .php file or one being read as such.
you'll want to do some variable handling in your php side because if the string is empty you'll end up with a
var my_var = ;
which will break the script. so something like:
var my_var = <?php echo "'" . $some_variable . "'";?>
if it's a string or if it's a number:
var my_var = <?php echo (empty($some_variable) ? null : $some_variable);
This is int specific, I'm sure you can come up with a function that will handle it better.
References:
empty function http://php.net/manual/en/function.empty.php
shorthand if http://davidwalsh.name/php-ternary-examples
Since you're submitting the form to the PHP file directly the browser loads the Edit_Project.php file as it would a normal page. If you want a json response to the already loaded page you'll have to use $.post or $.ajax
You can post the whole form simply by using serialize() like this:
$('#form_id').on('submit', function(e) {
// Stop the browser from posting the form
e.preventDefault();
// Post the form via Ajax
$.ajax({
url : 'Edit_Project.php',
type : 'POST',
data : $(this).serialize(),
success : function(response) {
// Here you do the HTML update
$("#"+j+"").html(response.reply);
}
});
});
The Edit_Project.php needs to be changed as well:
//The updation stuff at the server end
if (!mysqli_query($connection,$sqlquery)) {
$response = "'Error in your code: ' . mysqli_error($connection)";
}
else {
$response = "1 record updated";
}
mysqli_close($connection);
/*
* As SuperDJ suggested, you need to tell the browser that it's
* receiving a JSON ojbect although he did use the wrong content type:
*/
header('Content-Type: application/json');
/*
* According to php.net most decoders should handle a simple string as
* json object but to be safe always encode an array or an object since
* you can't know how the decoder will respond.
*/
echo json_encode(array('reply' => $response));