...

View Full Version : Resolved Web Application multiple PHP button functions



RonnyNishimoto
08-20-2012, 12:46 AM
For a web application, I'm trying to create buttons that puts either 0 or 1 into a file. However, for some reason it only works once on the page (only works once for one button, then it doesn't work). (I'm guessing because you are only allowed to have 1 php request?).
Even when I add a window.location(); to reload the page, it submits old data. When I click the button for "0" (then it reloads), then I click the button for "1", it still writes to the file "0" for some reason.

Is there a way to make this work? (Reloading is fine, but if there is a way without, I would love to learn).



<?php
$test = "test.txt";
?>



<script>
$(document).ready(function(){
$('#0-button').click(function(){
<?php
$test1 = "0";
file_put_contents($test, $test1);
?>
});
$('#1-button').click(function(){
<?php
$test2 = "1";
file_put_contents($test, $test2);
?>
});
});
</script>
<button type="button" id="0-button">0</button>
<button type="button" id="1-button">1</button>


I really appreciate any help I can get, this is uncharted territory for me! :D

AndrewGSW
08-20-2012, 01:39 AM
IDs should not begin with a number (preferably) although HTML5 is tolerant of this.

However, a more significant problem is that you cannot embed PHP within JS in this way:


$('#1-button').click(function(){
<?php
$test2 = "1";
file_put_contents($test, $test2);
?>
});

The PHP is executed once as the page is constructed.

JavaScript/jQuery cannot directly access files - either on the server or locally. (Local file access is possible under some very specific circumstances.)

You either need to post the data back to a php script via a form, and the php script can write this data to a file; or investigate AJAX requests.

DrDOS
08-20-2012, 03:11 AM
I would put all the button data into a javascript array, using a function to 'push' the data into the array, each time a new button is pushed make the entire array the value for a hidden input to the form, then when everything is completed submit the form. At the _POST end the input data will need to be exploded by the , because the array will be a string separated by the , .


<button type="button" class="button1" onclick="pushData(this,0);">0</button>
dataArray = [];
function pushData(T,num)
{
dataArray.push(T.className+"="+num)
myinput.value = dataArray;
}

so your array will look like this
dataArray = ["button1=0",button2=

You can have as many buttons as you want with the same class/className. This is much more scalable than what you are doing now.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum