Increasing value of PHP variable with onclick function - javascript

I have a variable $count = 10;that I want to increase by 10 each time a user clicks <a id="load-more" href="#">Load more</a>
I have tried setting this up with onclick, variable equations and functions but I cannot seem to get it to increase.
Ultimately, I want the $count = 10; to increase to $count = 20; and so forth each time the user clicks.
Any help is appreciated.

If I understand your question properly, you're looking for a solution that makes use of AJAX. Something like this:
On the client:
$('#load-more').click(function () {
$.ajax({
type: 'POST',
url: "http://example.com/stuff.php",
async: true,
success: function(data) {
// Success! Do something with `data` here:
},
error: function (jqXHR, textStatus, errorThrown) {
// Error! You should probably display an error message here:
}
})
})
On the server (stuff.php):
<?php
$value = retrieveValue(); // Replace this with whatever means you are using to get the persisted value.
$value += 10; // Increment the value by 10 each time.
saveValue($value); // Replace this with whatever means you are using to save the persisted value.
?>
Keep in mind that in order to keep the value incrementing with each request you will have to persist the value in PHP by some means (database, session, file, etc.).
You will also need to load JQuery libs in your HTML file to use the above JavaScript code.

It's not possible to change PHP variable's value (server side) by JavaScript (client side).
You can define a JavaScript variable and initialize it using PHP. But after that you can work only with your JavaScript variable.
<script>
var jsVar = <?php echo $phpVar; ?>;
jsVar++;
</script>
This is the way. For more information, the above code is sending PHP variable value to JavaScript(and the conversely is not possible).
You can also send a JavaScript variable's value to a PHP script using AJAX commands.
And if you want to use AJAX command, you can do it via pure JavaScript or using jQuery or other libraries. jQuery usage is easier but you need to load the library. I do prefer pure JavaScript AJAX. Here is an example:
<script>
var xhr = new XMLHttpRequest();
xhr.open('POST', 'php_script.php');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
// do something
}
};
xhr.send('value=' + jsVar);
</script>
And you can use value as $_POST['value'] in php_script.php file.

Here it is.
<input type="number" value="10" id="data">
<a id="load-more" href="#" onClick="increment()">Load more</a>
<script>
function increment(){
var count = parseInt(document.getElementById("data").value);
count = count+=10;
document.getElementById("data").value = count
$.post('backend.php?count='+$("#data").val(),function(val){//alert});
}
</script>

Related

What is wrong with the way I am handling these variables in PHP?

Originally I wanted to use node.js, but after an entire day of frustration, I switched to using jquery and mySQL. The logins seem to be working, but something is wrong in the way it is handling variables. All I want to do is update the database with two things: score and name. Here is the code I modded for my project in PHP:
<?php
$db = "myDatabaseNameIsCorrect";//Your database name
$dbu = "soIsMyUsername";//Your database username
$dbp = "AndMyPassword";//Your database users' password
$host = "localhost";//MySQL server - usually localhost
$dblink = mysql_connect($host,$dbu,$dbp);
$seldb = mysql_select_db($db);
if(isset($_GET['name']) && isset($_GET['this.score'])){
//Lightly sanitize the GET's to prevent SQL injections and possible XSS attacks
$name = strip_tags(mysql_real_escape_string($_GET['name']));
$score = strip_tags(mysql_real_escape_string($_GET['this.score']));
$sql = mysql_query("INSERT INTO `$db`.`scores` (`id`,`name`,`score`) VALUES ('','$name','$score');");
if($sql){
//The query returned true - now do whatever you like here.
echo 'Your score was saved. Congrats!';
}else{
//The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
echo 'There was a problem saving your score. Please try again later.';
}
}else{
echo 'Your name or score wasnt passed in the request. Make sure you add ?name=NAME_HERE&score=1337 to the tags.';
}
mysql_close($dblink);//Close off the MySQL connection to save resources.
?>
And here is the JS! that runs the PHP:
let gameoverScene = new Phaser.Scene('GameOver');
gameoverScene.create = function(){
this.laughSound=this.sound.add('laughSound')
this.gameW = this.sys.game.config.width;
this.gameH = this.sys.game.config.height;
this.goToTitle=function(){
var name = prompt('Enter your name');
jQuery.ajax({
type: "POST",
url: 'savescores.php?name=' +name +'&score=' + this.score,
dataType: 'text',
data: {functionname: 'add', arguments: [name, this.score]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
this.scene.start('Title')
};
I also tried changing the data type and that didn't work, but I'm not ruling it out yet as a problem.
Here are links to the project and the database:
www.igglepud.com/DeerDefender/Testing
www.igglepud.com/DeerDefender/Testing/getscores.php
This is the error I get:
gameover.js:20 Uncaught TypeError: Cannot use 'in' operator to search for 'error' in
Your name or score wasnt passed in the request. Make sure you add ?name=NAME_HERE&score=1337 to the tags.
at Object.success (gameover.js:20)
at fire (jquery.js:3268)
at Object.fireWith [as resolveWith] (jquery.js:3398)
at done (jquery.js:9305)
at XMLHttpRequest.<anonymous> (jquery.js:9548)
So, the error you're getting is because, in the JavaScript, obj (or the parameter in obj's position) is a string, not an array.
You can see some examples here of how you can properly check for and catch errors.
Edit:
So, in regards to your question about the score variable.
It's important to note that there are 2 types of variables at play here.
The first one is PHP GET variables. PHP GET variables are set via the following format:
var=value
You can set these variables by calling a PHP script like this:
script.php?var1=value1&var2=value2&var3=value3 // etc...
You can access them like this:
echo $_GET["var1"];
echo $_GET["var2"];
echo $_GET["var3"];
Which produces the result:
value1
value2
value3
The second variable at play is a JavaScript variable. Those can only be accessed in JavaScript. a JavaScript variable means nothing in PHP.
So, let's examine what you're doing from the JavaScript:
url: 'savescores.php?name=' +name +'&score=' + this.score,
For the purpose of explaining let's say name = Chipster, and this.score = 123.
What this code will do is try to open the following file:
savescores.php?name=Chipster&score=123
Remembering that PHP GET variables are set by the format script.php?var1=value1&var2=value2&var3=value3 // etc... we can see that there are 2 GET variables available from the PHP script called name and score. Thus, to access score from PHP you need to do it like this:
echo $_GET["score"];
This will output 123 in our example.
This may not solve your problem, but one issue I see with your code is calling strip_tags (or another function that alters the string) after it has already been quoted for insertion with mysql_real_escape_string may defeat the purpose of mysql_real_escape_string. It should be the very last function called on data before it's inserted.
Also, if score is an integer string, intval serves just as well as mysql_real_escape_string for sanitizing integers for insertion.
EDIT: You're also checking for GET variables in the PHP when the submission method used in the jQuery is POST. Try looking at $_POST instead of $_GET on the PHP side. You don't need to put variables in a query string if you're putting them in the request body via POST either.

Live data update with PHP

I have an API which works well, however I would like it to be live (get data periodically from API and show it in my html code).
I just need some hint that from where I most start. Javascript, Ajax?
Any clue would be appreciated.
My PHP / HTML:
<h4>Cpu Load</h4>
<span class="text-muted"><?php
echo "" . $first['cpu-load'] . " %" . "";
?></span>
Which outputs 2% or whatever. On refresh the page updates the new value.
My PHP API:
<?php
require('includes/routeros_api.class.php');
$API = new RouterosAPI();
$API->debug = false;
if ($API->connect('MYIP', 'USER', 'PASS')) {
$ARRAY = $API->comm("/system/resource/print");
$first = $ARRAY['0'];
$API->disconnect();
}
?>
To keep things simple you could create a function that has your ajax call.
You should look up the .ajax jquery usage, but this gives you an idea.
function ajaxQuery(){
// some stuff inside here to perform call
$.ajax({
url: 'your-file.php',
dataType: 'what ever data type you expect from server...',
success: function(data) {
// this is where i would normal have an id setup to update
// a specific textbox or form field...
}
});
}
You will then have to use the javascript timer function setInterval() somewhere on your page:
setInterval(ajaxQuery(), 2000);
Use setInterval function to query the API every certain time:
https://www.w3schools.com/jsref/met_win_setinterval.asp
The convenient way for me is using Vue and Vue-resource via data-binding, after querying API and change data, the page will be re-rendered without refresh the whole page.

Sub Total is not getting the changed value from database to input box

I am trying to get the sub total updated, when adding the items to the database from java-script. But, currently it displays the first amount and not updates when adding items. (But when runs the query from phpMyAdmin it works correctly)
java-script code
function showSubTotal() {
<?php $resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
?>
document.getElementById("txtSubTotal").setAttribute('value','');
document.getElementById("txtSubTotal").setAttribute('value',"<?php echo $rowT[0]; ?>");
}
HTML code
<input name="txtSubTotal" type="text" id="txtSubTotal" size="15" / >
<button type="button" name="btnSave" id="btnSave" onclick="submitdata(); check_qty(); showSubTotal();">ADD</button></td>
The problem is, that when you declare the function with PHP, the function cannot be refreshed by using PHP again... because everything that PHP does, happens before the page is loaded, therefore, let's say as an example:
function showSubTotal() {
<?php $resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
?>
document.getElementById("txtSubTotal").setAttribute('value','');
document.getElementById("txtSubTotal").setAttribute('value',"<?php echo $rowT[0]; ?>");
}
this 'value' from $rowT[0] = 10 from the first query, it will always be 10, because that is what PHP read from the database when it checked upon page load. You will have to use something like jquery or ajax to read the contents of another php file that contains the value (the mysqli_fetch_row).
PHP is literally named hypertext preprocessor, meaning everything that is processed before the html is printed to the user. (before the page has finished loading)
try experimenting with this: https://api.jquery.com/jquery.get/
ShowSubTotal() will bring only the value when the page loads. Dynamic actions will not make any changes, because php needs an server request to operate.
You should bring the subtotal through a dynamic request (ajax) call.
Or:
Use javascript to sum the values and set the value in your txtSubTotal field. If you go for this option, remember to not rely on this value on your server side processing, as it may be adulterated by users.
I found the solution, added the do_onload(id) to calculate the total on loadComplete event which is triggered after each refresh (also after delete)
function do_onload(id)
{
//alert('Simulating, data on load event')
var s = $("#list").jqGrid('getCol', 'amount', false, 'sum');
jQuery("#txtSubTotal").val(s);
}
And changed the phpgrid code accordingly.
$opt["loadComplete"] = "function(ids) { do_onload(ids); }";
$grid->set_options($opt);
try this code
$("#btnSave").click(function(){
$.ajax({
url : file_url.php,
type : 'post',
data : {
get_subtotal:"subtotal",
},
success : function( response ) {
alert(response);
$("#txtSubTotal").val(response );
},
error: function(response) {
console.log(response);
}
});
});
file_url.php
if(isset($_POST['get_subtotal'])){
$resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
echo $rowT[0];
}

Setting php session variable from HTML form input field

I have a page that has a javascript date picker, the result of which goes into an input box on an HTML form (see image below). This works fine.
I would also like the chosen date to be stored in as session variable. Can anyone point to how I should do this? Can a session variable be assigned within javascript?
Code so far:
<?php
session_start();
Datepicker
....
<script type="text/javascript">
window.onload = function(){
g_globalObject1 = new JsDatePick({
useMode:2,
target:"inputFieldStart",
dateFormat:"%Y-%m-%d",
cellColorScheme:"armygreen"
});
};
</script>
HTML Form
<form action="https://website" method="Post">
<input name="StartDate" type="text" id="inputFieldStart">
<input type="Submit" value="Update" class="button">
</form>
The session variable needs to be set as a php variable, on the server. Your HTML form, which calls your server with a Post method passes this variable to the php page, and it can be read and set as a session variable using
<?php
$start_date = $_POST["StartDate"];
$_SESSION['start_date'] = $start_date;
?>
Set it to session with
$_SESSION["date"] = $_POST["StartDate"];
to "set it with javascript" use AJAX. For instance jQuery's $.ajax
A session variable cannot be assigned with JavaScript directly, you can however use AJAX to send a request to a PHP document to create/change the session variable if you must insist on using JavaScript.
In your PHP document (we'll call it date_assign.php) write the following:
$date = $_POST['date'];
$_SESSION['date'] = $date;
Then in your JavaScript use this function (with the jQuery library included, of course) to send the request to the PHP document.
// Function to call in order to change session variable.
function sessionVariable() {
// Get date from picker.
var date = $('#inputFieldStart').value();
// Create data string.
var datastr = 'date=' + date;
// Create the AJAX request.
$.ajax({
type: 'POST',
url: 'date_assign.php',
data: datastr
});
}
Of course this is a long way around of doing it but it means you can accomplish it with JavaScript. You can call the function whenever you need to set the session variable, this can be done on an interval or you can bind a click listener to the Submit button to send the data, your call.

Send variable that contains an equation through ajax and return it to jquery fully computed

im trying to write a code where i will be able to send a variable that contains a mathematical equation through ajax and have it computed using php
the problem that i am getting is that once the php it returns the variable to jquery it doesnt compute it and still returns it as an equation
this is how i made it
jquery
$(".equals").click(function(e){
e.preventDefault();
var firstnum= $("#firstnum").val();
var secnum= $("#secnum").val();
var operator= $('#operator').val();
var compute = firstnum+operator+secnum;
content = {compute:compute}
$.ajax({
url:'compute.php',
type:'POST',
data:content,
success:function(response){
console.log(response);
}
});
});
php
<?php
$compute =$_POST['compute'];
echo $compute;
?>
for example the content of my variable compute is...
10+10
the php will still return it as is
what i want to happen is once it comes back from php it will return as
20
is there a way to make this happen?
thanks
If you want PHP to compute it, you should write something like this. Because when you send 10+10, PHP sees it as a string.
Javascript:
$(".equals").click(function(e){
e.preventDefault();
var firstnum= $("#firstnum").val();
var secnum= $("#secnum").val();
var operator= $('#operator').val();
content = {first_number:firstnum,second_number:secnum,operator:operator}
$.ajax({
url:'compute.php',
type:'POST',
data:content,
success:function(response){
console.log(response);
}
});
});
And at the PHP:
<?php
$content = $_POST['content'];
if( '+' == $content['operator'] ){
echo $content['first_number'] + $content['second_number'];
}
else if( '-' == $content['operator']){
//extraction
}
// so on..
?>
You must have a calculator script on server side in PHP.
The mathematical expression must be parsed. You could use something like this
http://20xxproductions.com/code-samples?s=phpsc
for parsing more complex expressions.
If you have to process simpler ones you can specifiy an operator and give both numbers as extra POST variables.

Categories