How to Increment variable in html / php - php

I want to increment variable in html .. the variable is declared in php and I need to increment it in php ... I write the code bellow :
global $indice_array_contact;
$indice_array_contact=0;
<img src="images/back1.png" onclick='left_clik()'>
<img src="images/back2.png" onclick='right_clik()'>
<SCRIPT LANGUAGE="JavaScript">
<?php $indice_array_contact=$indice_array_contact+1; ?>
function left_clik()
{ document.getElementById("im1").src = "profiles_stored/executive.png";
document.getElementById("td1").innerHTML = "<?php echo $indice_array_contact ?>";
<?php $indice_array_contact=$indice_array_contact+1; ?>
}
function right_clik()
{ document.getElementById("im1").src = "profiles_stored/<?php echo $array_contact[0]->profile ?>";
document.getElementById("td1").innerHTML = "<?php echo $indice_array_contact ?>";
<?php $indice_array_contact=$indice_array_contact+1; ?>
}
When I click on the right_click button , the value is 1 ,and when I click on the left_click button , the value is 2 ... but if I click second time on right_click button the value doesn't change to 3. Why?

Your code will never work the way you want it - you are mixing server-side scripting ( php ) with client-side scripting ( javascript ).
What really happens in your example:
Your $indice_array_contact is incremented by one during page load on the server
Your function left_click() and right_click() receive the value of ( presumably ) 2 in the document.getElementById().innerHTML during page load, as calculated on the server -> this will never change on your already loaded page!
You hit a button and trigger either the left_click() or right_click() function -> the innerHTML DOM property receives value of 2, as the server calculated during page load -> this happens each time you execute the function
Try to re-work your implementation with only javascript as it looks you are looking for something that should change without the page being reloaded.

PHP is not necessary for this is it? Shouldn't something like this work:
<img src="images/back1.png" onclick='left_clik()'>
<img src="images/back2.png" onclick='right_clik()'>
<SCRIPT type="text/javascript">
var indice_array_contact = 0
function left_clik()
{
document.getElementById("im1").src = "profiles_stored/executive.png";
document.getElementById("td1").innerHTML = indice_array_contact;
indice_array_contact++;
}
function right_clik()
{
document.getElementById("im1").src = "profiles_stored/executive.png";
document.getElementById("td1").innerHTML = indice_array_contact;
indice_array_contact++;
}

Related

Issue with displaying PHP code in HTML

I am using a slider in one HTML page and sending its value to the next page using a hidden textbox like this :
Page1.html
<script type="text/javascript">
var flowPercent = document.querySelector('#flow');
function sliderFunc()
{
var f = function(){
var x = flowPercent.value;
window.open('Page3.html?val=x','_parent');
};
f();
};
</script>
And then I would like to display this in the next HTML page using PHP echo like this :
<?php
$val=$_POST['val'];
echo "Value is $val";
?>
But neither the value nor "Hello" is being displayed. Why is this ?
How do I fix this ?
Thanks !
If your PHP-Code is contained in Page3.html, that page should have a .php-extension in order to execute the code. And also you are not posting anything, so $_POST will be useless...
Try window.opener.getElementById('textbox') instead to query the value...
Just change your page3.html to page3.php because you can't use php code in html file but you can use html code in php

How do I reload a input after 3 seconds with javascript

How do I reload this input once after 3 seconds has passed after the webpage has loaded. using javascript
<input type="text" name="steamID" id="steamID" value="<?php echo $steamid; ?>">
Try looking at this answer on SO:
Reload random div content every x seconds
If that doesn't work for you, you will have to use ajax to get new content. Look at jQuery's API here:
http://api.jquery.com/jQuery.ajax/
Or if you're not using jQuery, look at this for a tutorial on AJAX:
http://www.w3schools.com/ajax/default.asp
Otherwise, for more help, please post more of your code -- but ajax will have to be used
If you want the PHP in your code to be run again, you need to make you code a little more complicated.
You will need the following components
a php file that will lookup and print $steamid only.
a javascript function that uses AJAX to get the information from the php file, sets the value of your input
call the javascript on page load, then set an interval for 3 seconds and call it again.
But based on this...
The problem i have that the PHP var $steamid are set after the input has been created so all i need todo is reload the input so the $steamid will show.
... I think you just need to re-order your PHP code.
By reset, I am assuming you mean set the value to null.
$(window).load(function(){
setTimeout( function() {
document.getElementById("steamID").value = "";
},3000);
});
EDIT: Based on your further description, wait until steamID is set, then put this on the page:
<script type="text/javascript">
document.getElementById("steamID").value = "<?php echo $steamid; ?>";
</script>
<?php
echo "<script type='text/javascript'>";
$steamid = "testing 1,2,3";
echo " var sID = '".$steamid."';";
?>
function setupRefresh() {
setInterval("refreshVal()", 3000);
}
function refreshVal() {
var e = document.getElementById('steamID');
e.value = sID;
}
</script>

How to execute PHP code within JavaScript

<button type="button" id="okButton" onclick="funk()" value="okButton">Order now </button>
<script type="text/javascript">
function funk(){
alert("asdasd");
<?php echo "asdasda";?>
}
</script>
When the button is pressed I want to execute PHP code (at this point to echo asadasda)
You could use http://phpjs.org/ http://locutus.io/php/ it ports a bunch of PHP functionality to javascript, but if it's just echos, and the script is in a php file, you could do something like this:
alert("<?php echo "asdasda";?>");
don't worry about the shifty-looking use of double-quotes, PHP will render that before the browser sees it.
as for using ajax, the easiest way is to use a library, like jQuery. With that you can do:
$.ajax({
url: 'test.php',
success: function(data) {
$('.result').html(data);
}
});
and test.php would be:
<?php
echo 'asdasda';
?>
it would write the contents of test.php to whatever element has the result class.
Interaction of Javascript and PHP
We all grew up knowing that Javascript ran on the Client Side (ie the browser)
and PHP was a server side tool (ie the Server side). CLEARLY the two just cant interact.
But -- good news; it can be made to work and here's how.
The objective is to get some dynamic info (say server configuration items) from the server into the Javascript environment so it can be used when needed - - typically this implies DHTML modification to the presentation.
First, to clarify the DHTML usage I'll cite this DHTML example:
<script type="text/javascript">
function updateContent() {
var frameObj = document.getElementById("frameContent");
var y = (frameObj.contentWindow || frameObj.contentDocument);
if (y.document) y = y.document;
y.body.style.backgroundColor="red"; // demonstration of failure to alter the display
// create a default, simplistic alteration usinga fixed string.
var textMsg = 'Say good night Gracy';
y.write(textMsg);
y.body.style.backgroundColor="#00ee00"; // visual confirmation that the updateContent() was effective
}
</script>
Assuming we have an html file with the ID="frameContent" somewhere,
then we can alter the display with a simple < body onload="updateContent()" >
Golly gee; we don't need PHP to do that now do we! But that creates a structure for
applying PHP provided content.
We change the webpage in question into a PHTML type to allow the server side PHP access
to the content:
**foo.html becomes foo.phtml**
and we add to the top of that page. We also cause the php data to be loaded
into globals for later access - - like this:
<?php
global $msg1, $msg2, $textMsgPHP;
function getContent($filename) {
if ($theData = file_get_contents($filename, FALSE)) {
return "$theData";
} else {
echo "FAILED!";
}
}
function returnContent($filename) {
if ( $theData = getContent($filename) ) {
// this works ONLY if $theData is one linear line (ie remove all \n)
$textPHP = trim(preg_replace('/\r\n|\r|\n/', '', $theData));
return "$textPHP";
} else {
echo '<span class="ERR">Error opening source file :(\n</span>'; # $filename!\n";
}
}
// preload the dynamic contents now for use later in the javascript (somewhere)
$msg1 = returnContent('dummy_frame_data.txt');
$msg2 = returnContent('dummy_frame_data_0.txt');
$textMsgPHP = returnContent('dummy_frame_data_1.txt');
?>
Now our javascripts can get to the PHP globals like this:
// by accessig the globals
var textMsg = '< ? php global $textMsgPHP; echo "$textMsgPHP"; ? >';
In the javascript, replace
var textMsg = 'Say good night Gracy';
with:
// using php returnContent()
var textMsg = '< ? php $msgX = returnContent('dummy_div_data_3.txt'); echo "$msgX" ? >';
Summary:
the webpage to be modified MUST be a phtml or some php file
the first thing in that file MUST be the < ? php to get the dynamic data ?>
the php data MUST contain its own css styling (if content is in a frame)
the javascript to use the dynamic data must be in this same file
and we drop in/outof PHP as necessary to access the dynamic data
Notice:- use single quotes in the outer javascript and ONLY double quotes in the dynamic php data
To be resolved: calling updateContent() with a filename and
using it via onClick() instead of onLoad()
An example could be provided in the Sample_Dynamic_Frame.zip for your inspection, but didn't find a means to attach it
You can't run PHP with javascript. JavaScript is a client side technology (runs in the users browser) and PHP is a server side technology (run on the server).
If you want to do this you have to make an ajax request to a PHP script and have that return the results you are looking for.
Why do you want to do this?
If you just want to echo a message from PHP in a certain place on the page when the user clicks the button, you could do something like this:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
document.getElementById('resultMsg').innerHTML('<?php echo "asdasda";?>');
}
</script>
However, assuming your script needs to do some server-side processing such as adding the item to a cart, you may like to check out jQuery's http://api.jquery.com/load/ - use jQuery to load the path to the php script which does the processing. In your example you could do:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
$('#resultMsg').load('path/to/php/script/order_item.php');
}
</script>
This runs the php script and loads whatever message it returns into <div id="resultMsg">.
order_item.php would add the item to cart and just echo whatever message you would like displayed. To get the example working this will suffice as order_item.php:
<?php
// do adding to cart stuff here
echo 'Added to cart';
?>
For this to work you will need to include jQuery on your page, by adding this in your <head> tag:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
Any server side stuff such as php declaration must get evaluated in the host file (file with a .php extension) inside the script tags such as below
<script type="text/javascript">
var1 = "<?php echo 'Hello';?>";
</script>
Then in the .js file, you can use the variable
alert(var1);
If you try to evaluate php declaration in the .js file, it will NOT work
put your php into a hidden div and than call it with javascript
php part
<div id="mybox" style="visibility:hidden;"> some php here </div>
javascript part
var myfield = document.getElementById("mybox");
myfield.visibility = 'visible';
now, you can do anything with myfield...
We can use php in JavaScript by creating a form element and put the action as a .php page.
Then we use JavaScript to submit that form.
EX:
<!doctype html>
<html>
<head>
<title>PHP Executed with JS</title>
</head>
<body>
<form action="phpCode.php" id="phpCode">.
</form> <!-- This is the form-->
<script>
function runPhp() {
var php =
document.getElementById("phpCode")
php.submit() //submit the form
}
</script>
</body>
The PHP file name would be phpCode.php.
In that file would be your PHP code.
May be this way:
<?php
if($_SERVER['REQUEST_METHOD']=="POST") {
echo 'asdasda';
}
?>
<form method="post">
<button type="submit" id="okButton">Order now</button>
</form>
If you do not want to include the jquery library you can simple do the following
a) ad an iframe, size 0px so it is not visible, href is blank
b) execute this within your js code function
window.frames['iframename'].location.replace('http://....your.php');
This will execute the php script and you can for example make a database update...
Use ajax to send request and echo the response
when successfully executed. Like this:
$.get("site.com/ajax", function(status,data){
alert(status);
});
This can be achieved with jquery library.
You could run PHP at the start of the Page and grap the results from inputs
<?php
c = a * b;
?>
<input type="hidden" name="c" value="<?php c ?>"/>
<button type="submit">Submit</button>
</form>
<script>
let cValue = $('input[name="c"]').val();
alert(cValue);
</script>

How to make the JS function get the data from the database everytime I call it?

I am using a code look like this:
<script>
function getdata()
{
var employee =
<?php
//connect to database and get employee name
echo "'" . $row['empnm'] "'";
?>;
}
</script>
print them
It works, but the function is running the PHP code only on the page loading and not every time I call the function. So, if the target employee name is changed the JS function will show the old name untill the page is reloaded. How to make the JS function get the data from the database everytime I call it?
look into a library like jQuery
Then using the following code
function getdata(){
$.post("path/to/file.php", function(data) {
var employee = data;
// do whatever with the data.
});
}
and you can still use your same html
print them
and file.php
<?php
// connect to your db, get your results, echo them back
echo $row['empnm'];
?>
When you first request the page, PHP renders out a whole string of html, then your browser executes that generated HTML, not the original PHP. i.e. your server is going to send something like
<script>
function getdata()
{
var employee =
"hello world";
}
</script>
print them
So, as far as the web browser knows, "hello world" is just hardcoded there.
You'll need to look into AJAX for how to make it work. Check out this beginners' tutorial on using jQuery for ajax: http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
Define a global variable
<script>
var employee = <?php echo "'" . $row['empnm'] "'";?>;
function getdata(){
return employee;
}
</script>
Now keep on changing variable employee whenever it is changed
print them
If you're in a PHP loop -- it does looks like you are, since -- you can use PHP to define the parameter to be passed into getdata() in your loop; e.g.
<script type="text/javascript">
function getdata(employee) {
// connect to database and get employee name
}
</script>
<?php
foreach ($loopData as $row) {
print 'print them';
}
?>

How do I use externalInterface to allow Flash to call javascript to update a value on the screen?

I have a Flash movie that is embeded in a PHP page. The PHP page displays a value to the user (the number of images they have uploaded). When the user uploads a new image I want the value on the PHP page to reflect the change without refreshing the page.
This value is retrieved from database using MySQL. So heres what Ive done so far -
On the PHP page where I want to show the value I have a div
<div id="content_info"><script type="text/javascript" src="getInfo.php?group= <?php echo($groupid); ?> "></script></div>
This calls an external PHP file that queries the database and outputs the result like this
Header("content-type: application/x-javascript");
//do the query with PHP and get $number and then output
echo "document.write(\" (".$number.")\")";
When the page loads for the first time the correct number shows in the div and so all works fine. The next step is to call something to update the contents of this div when the value changes. So I will set up externalInterface in flash to call a javascript function to do this.
This is where Im stuck, I want to be able to do something like this -
function ReplaceContentInContainer(id) {
var container = document.getElementById(id);
container.innerHTML = getInfo.php?type=new&group= <?php echo($groupid) ?>;
}
and call this by
ReplaceContentInContainer(content_info)
I realise this isnt going to work but can anyone show me how to get this result?
many thanks
group= <?php echo($groupid); ?> will be executed only when PHP creates the page. You should store that value inside a variable in the javascript. See if this works.
<div id="scriptDiv">
<script type="text/javascript">
<!-- store the group id -->
var groupID = <?php echo($groupid); ?>;
function getGroupID()
{
return groupID;
}
function updateValue(value)
{
document.getElementById("content_info").innerHTML = value;
}
</script>
<div id="content_info">
<!-- for initial value -->
<script type="text/javascript"
src="getInfo.php?group= <?php echo($groupid); ?> ">
</script>
</div>
</div>
Now you can use flash's URLLoader:
var ldr:URLLoader = new URLLoader();
var gid:String = ExternalInterface.call("getGroupID");
var req:URLRequest = new URLRequest("getInfo.php");
req.data = {type:"new", group:gid};
ldr.addEventListener(Event.COMPLETE, onLoad);
ldr.addEventListener(IOErrorEvent.IO_ERROR, onError);
ldr.load(req);
private function onLoad(e:Event):void
{
var data:String = URLLoader(e.target).data;
ExternalInterface.call("updateValue", data);
}
private function onError(e:IOErrorEvent):void
{
trace("ioError");
}

Categories