PHP query runs even if button is not clicked - javascript

I have a strange problem. I have set a query to insert two names in the database. I have also used Javascript(Jquery) to run it only when the create button is clicked. But it runs evry time I reload the page...
Button:
<button id="button-create" type="button" style="float:right;">Create</button>
Script:
$(document).ready(function(){
$("#button-create").click(function(){
$('body').append('<div class="box" id="12"><div class="head">Homework<button class="button-delete" data-panelid="12" type="button" style="float:right;">Delete</button></div><div class="text">Valkommen!</div></div>').children(':last').hide().slideDown(500);
<?php
$query123 = $pdo->prepare("INSERT INTO post (head, content) VALUES ('John', 'Doe')");
$query123->execute();
?>
});
});

It is because your PHP script is executed every time your Server, for example Apache, serves that page or in trivial terms, the user reloads the page.

The reason that it does that is because it's PHP-code. When rendering the PHP-file, the server will execute ALL of the PHP. So when you run the page, it will run that php code before it goes to the browser...
All the PHP will be executed and only the output from the PHP will be sent to the browser. So your database execute will be executed already.
PHP code => Running on server
JS code => Running in browser
There is no way they can communicate directly.
If you want to do something like this, you need an ajax call to a page that will execute the SQL Query.
I would recommend to watch this introduction to the difference between PHP and Javascript: https://www.youtube.com/watch?v=dJJvK3Fre0I

Related

Run PHP function when img clicked

I'm wondering if there's a way to perform a function when an image is clicked in PHP? I know it can be done in Javascript. For example, when foo.png is clicked, the following function will run.
function example() {
header('Location: example.php');
}
PHP is run on the server, and is used before and while creating the page -- and then it is submitted to the browser for rendering.
Once the page is rendered and displayed to the user, all PHP processing has stopped and the page has been served to the client. Server code no longer runs - its time has passed.
Once in the browser, only client-side code can run (javascript). Particularly when interacting with the user, client side code is all you can use.
However, you can also use client-side code (javascript/jQuery) to interact with the user (detect a click or mouse movement) and then use AJAX to send data over to another server-side PHP file. The PHP file will "wake-up" as it receives the data, and it can do some additional server-side stuff -- such as use the received data to perform a DB look-up, then take the new DB data and create some HTML code and send that back to the page. This new HTML code can be injected onto the page in the success (or .done() ) function of the AJAX code block and new data can appear on the page without refreshing or navigating away from the current page.
But for actually detecting the user click, it's javascript/jQuery.
Note that PHP can also inject javascript along with the HTML - but once the code has been served to the browser for display, it is only the javascript that can interact with the user, not the PHP.
With javascript/jQuery, you can do what you want like this (the code is correct but the example will not work properly - SO will not navigate to the Google webpage):
$('#myImg').click(function(){
window.location.href = 'http://google.com';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>Click below for Google</p>
<img id="myImg" src="http://placeimg.com/50/50/animals" />

Sending data from a HTML page to a PHP script and picking the data in PHP

My HTML page
<html>
<body>
<form action="myScript.php" method="POST">
Enter a transceiver ID:
<br><br>
<input type="text" name="id" >
<br><br>
<input type="submit" value="Submit">
</form>
</body>
My PHP script which is running on my server
<?php
$id_array = array("101");
while(1)
{
if (isset($_POST['id']))
{
$id = $_POST['id'];
echo ("ID is ".$id."\n");
array_push($transceiverID_array, $id);
}
print_r($id_array);
usleep(5000000);
// lot of processing will be done
}
?>
My PHP script is in a forever while loop. If I post some data from my HTML page, my PHP script is doing something else (which takes quite a lot of time), and not necessarily processing the line where it is checking if the variable from HTML page is set. So, even if I posted something from my HTML page, due to the long duration between posting data and the PHP script going on the isset line, my PHP script is unable to pick up data.
Is there any time limit in which I need to pick up the variable in my PHP script posted from the HTML page? Is there any better way of doing this?
Also, after posting, my HTML page, keeps waiting for my PHP script to respond. Is there any way to stop loading my HTML page?
As the other commentors asked. What is the point of having an infinite loop? The server will do the task of listen for requests in your behalf!
It is natural that the HTML page doesn't receive anything, as the flow in your PHP script never ends. Remove that loop and try the request.
The problem is that you get your HTTP Parameters only once every call. If you create a infinite loop you won't get a response from the server.
Even your parameter will not change because you PHP Script is called separately every time you do a request.
Why do you need to run forever? Isn't it better to do the work somewhere else e.g starting a cronjob?
Your php does have a time limit:
http://php.net/manual/en/function.set-time-limit.php
However it is not clear why you want this to loop forever.
your while 1 loop will always state true and therefor run "infinitely"
this infinity however is limited. (see link above)
EDIT: From this comment: I cannot restart my script due to the processing that it is doing. If I use a cronjob, won't my script start from the beginning every time? It will re-initialize all the variables (which I did not show here), which I do not want
I'm not sure using PHP alone is enough to achieve what you want. You need to consider a persistence layer (memory, database) to keep your variables alive throughout multiple requests. while(1) is not how you do this.
From reading through your post, it sounds like you're misunderstanding HTTP/PHP. It looks as if you're trying to create a loop that will keep "listening" for a POST value to come through from the HTML form as if you're writing a web server itself or something.
That's not how HTTP works.
The client will make a GET request to get your HTML, your script then ends.
The client will then make a POST request with the data, your script processes it and then ends.
This happens every time, your script will run once per set of POST values that it receives. Note that your HTML isn't "waiting", your HTML was "done" in the GET request, your browser is now making a request to your PHP script and, until you have output, it will not display anything.
Now, you say it's a long running process and you don't care ie. fire-and-forget, where you're saying that you don't In this case, it may be better to simply use an AJAX request that you can fire and not care about the response. Another alternative would be to start a request into an iFrame or similar.
Either way, removing the while loop will allow you to verify that your request is going through, like so:
<?php
$id_array = array("101");
if (isset($_POST['id']))
{
$id = $_POST['id'];
echo ("ID is ".$id."\n");
array_push($transceiverID_array, $id);
}
print_r($id_array);
?>
An option for what you're trying to do, if you want to provide feedback to the browser, is to flush content to the browser as you go.
Try POSTing to this script and see what happens:
<?php
for($i = 0; $i < 5; $i++)
{
echo $i;
flush(); // Send processing so far to the browser
ob_flush(); // For good measure
sleep(1);
}

how to access JavaScript variable in php i have tried following but doesn't work [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 6 years ago.
i have try to perform select query from tag with JavaScript variable but it is not work.
What wrong with it
function method12()
{
var value12=document.getElementById('period').value
<?php
$con=mysql_connect("localhost","root","");
if(!$con)
{
die('could not connect:'.mysql_error());
}
mysql_select_db("db_loan",$con);
$sqlstr="select bankcode from tbl_master where loanaccountnumber='".value12."'";
$result=mysql_query($sqlstr);
$row=mysql_fetch_array($result);
echo $row['bankcode'];
?>
alert(value12);
}
PHP is run server-side. JavaScript is run client-side in the browser of the user requesting the page. By the time the JavaScript is executed, there is no access to PHP on the server whatsoever. Please read this article with details about client-side vs server-side coding.
What happens in a nutshell is this:
You click a link in your browser on your computer under your desk
The browser creates an HTTP request and sends it to a server on the Internet
The server checks if he can handle the request
If the request is for a PHP page, the PHP interpreter is started
The PHP interpreter will run all PHP code in the page you requested
The PHP interpreter will NOT run any JS code, because it has no clue about it
The server will send the page assembled by the interpreter back to your browser
Your browser will render the page and show it to you
JavaScript is executed on your computer
In your case, PHP will write the JS code into the page, so it can be executed when the page is rendered in your browser. By that time, the PHP part in your JS snippet does no longer exist. It was executed on the server already. It created a variable $result that contained a SQL query string. You didn't use it, so when the page is send back to your browser, it's gone. Have a look at the sourcecode when the page is rendered in your browser. You will see that there is nothing at the position you put the PHP code.
The only way to do what you are looking to do is either:
do a redirect to a PHP script or
do an AJAX call to a PHP script
with the values you want to be insert into the database
You can't use JS variables in PHP. JS code is run on the client and PHP code is run on the server.
To do what you want you have to send the JS value via a GET or POST request to the server and then get that value via $_POST["varname"] or $_GET["varname"]

Clickable html button counter using php or js

I am very new to php and javascript and I was wondering how I could make a global counter that adds 1 to it every time a user presses a button. The number would stay the same even if someone is on a different computer or refreshes the page. I had this using javascript:
<script type="text/javascript">
var clicks = 0
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
</script>
<button type="button" onClick="onClick()">Click me</button>
<footer>Clicks: <a id="clicks">0</a></footer>
But when ever someone refreshes the page, it resets the number, and it is not global. I tried making something in php which is:
<?php
$clicks = 0
public function clickButton()
{
$clicks = $clicks + 1
}
?>
but I have no idea what I'm doing and how to call the php function or display the php variable.
Your current problem is that your Click variable is only storred on the one computer clicking.
You need to do 2 things:
Store the click variable.
Read the click variable.
(Live updates.)
Store the click variable:
As Vinicius Maia said you need a connection between the users and this can be done with a database, read about MySQL.
Or you can use a more simple method and use php to read and create / write the Click variable into a file named Clicks.txt. See PHP Filesystem Functions on W3C
Read the click variable:
If you chose the MySQL method you should use the commands as so, else if you chose the primitive method you can use the following command: Php File Get Content
Live updates:
To show the variable live and not making your users refresh you should be able to use AJAX so make sure to take a look at that. This question might be usefull.
You should make a interval loop which should constantly check for updates in the variable. This question might be usefull
Together:
Take a good look at Jonas w's answer, he gives a good example on how you could make this and he follows your request. Only downside by using this tactic is that everytime you click you refresh, which might be annoying for some users.
But what he does is:
He reads the variable.
When you click the button he runs the PHP code by opening it.
When done with the code he send you back to index and refresh the side
Repeat...
But for your users, maybe you should add the live function by using this system:
Read the variable.
Make a loop with AJAX that calls a php function that checks and return updates
When you click the button use AJAX to run another php function to update the variable
Repeat...
You have the right JavaScript logic, now you just need to store your clicks somewhere that won't be affected by a browser refresh!
My first suggestion would be to utilize HTML5's localStorage object.
The examples are pretty good on the link. See if you can make something work!
Javascript or PHP will not solve your problem. Just because what you need is some connection between all users that will access your website. For that, you must use some kind of database. I recommend you starting learning MySQL.
Check this: http://php.net/manual/en/book.mysqli.php
The php variables just work inside of one request. So if two people request your site, the script runs twice in two different versions. You have to store the variable on the server.
You could store it into a mysql database ( good articles about that on php.net)
or you could make a counter.txt and edit it with php. ("Fopen" on php.net)
The php runs on the server and cannot interact with the clients side js. You need to send this "button click" to the server. You can do this with AJAX ( google that) or reloading the site and passing gets and posts to the server
Update.php:
<?php
$file=fopen("counter.txt","c+");//open or create counter.txt
$counter=fread($file, 10);//read content
$counter=(int)$counter+1;//add one
fwrite($file,$counter);//save counter
fclose($file);//close file
Header("Location: index.php");//go back to index.php
?>
Index.php:
<?php
$file=fopen("counter.txt","c+");
$counter=fread($file, 10);
fclose($file);
Echo $counter;
?>
Click me
if you need that different users see the same counter, then you will need save the counter in a database.
Regards.

Is it possible to use a javascript variable inside of a javascript variable that contains php?

I'm trying to use a JS variable inside of php code that executes a function. Based on the selected radio button, Javascript gets a string of code from a data attribute of the radio button (trimcode) and I need to set this as the key in my PHP function where one of the variables requires an array key.
The result will be, whenever a radio button is selected, the PHP function inside this function will execute using the 'code' variable and thus return it's return value as the inside content of the "byo" class div via javascript innerhtml. However, I can't figure out how to use a javascript variable inside of PHP code that is inside another javascript variable. Can someone point me in the right direction?
<script type='text/javascript'>
$(document).ready(function(){
var code;
var colorsavailable;
$("input:radio[name=trimlevel]").click(function() {
code = $(this).data("trimcode");
colorsavailable = ("<?=byoTrimImageColors($modelMap["+code+"],$hexcolors)?>");
$('#byo').html(colorsavailable);
});
});
});
</script>
I think you're confusing the notions of server-side code and client-side code.
The PHP code runs once, in its entirety, when the page is requested. Then, after it's executed, the resulting page is sent to the browser where the JavaScript code runs. And that line of PHP code isn't going to execute for each click event. It's going to execute once, and only once, and emit only one result to the page.
Given what it looks like you're trying to do, you probably have two options:
Include the functionality you're invoking in JavaScript code and just invoke it there instead of in PHP code. Whatever that array is, whatever that function is, implement those in JavaScript. Then there's no need to involve PHP at all.
If the functionality needs to be in server-side code, then you're going to need to use AJAX to invoke it. Essentially you'd create a separate PHP "page" (which emits JSON data, not an actual page) to accept the value, invoke the functionality, and emit the result. The JavaScript code would make an AJAX request to that resource and use the result.
Client-side, that AJAX call might look something like this:
code = $(this).data("trimcode");
$.post('someNewPage.php', { code : code }, function (result) {
$('#byo').html(result);
});
Server-side (and I'm mostly guessing here), someNewPage.php might have something like:
$code = $_POST['code'];
// you'll want to sanitize the $code value here, since it's user input
$result = byoTrimImageColors($modelMap[$code],$hexcolors);
echo json_encode($result);
Your idea is not possible since for PHP code to execute it requires a page refresh. The best solution would be using Ajax to send the data to PHP asynchronously and changing your HTML, using JS, with the data that comes back from PHP.
To learn how Ajax/PHP works visit this site: http://www.w3schools.com/php/php_ajax_php.asp.
It is not possible to call a PHP function from Javascript. PHP is a pre-processor and ALL PHP code will finish executing before the page loads. Once the page loads, the browser will load your Javascript files and JS will take it from there.
In order to "call a PHP function" again after the page has loaded, you will need to make a new request to the page. This is typically handled in Javascript via AJAX. Using ajax, Javascript can send a new request to the server, PHP will read it and send a response back to Javascript.
If you really need that PHP function to execute on the Javascript level synchronously, then consider porting that function to Javascript.
Right now what you are doing is constructing a string that resembles some PHP code. It looks like you are doing that part just fine.
However, you cannot execute PHP code on the client side. There is no interpreter available on the client (the browser) that knows what to do with your PHP code.
What I would recommend doing is if you need to run some PHP code, create a controller method or some script that you can execute on the server, make an AJAX request to that (passing the JS code variable), have the PHP method return the value of your byoTrimImageColors method, and then handle that data however you please.

Categories

Resources