I have a button that runs a PHP function after the user onClicks. This is achieved using the POST method (as illustrated below). The user clicks on the button and the PHP function runs correctly, however, I want the user to be able to click the button multiple times and for the function to run multiple time. The function cannot over-ride its last result/outcome (so basically the result is echoed/printed each time the user clicks the button and the previous results are not overwritten).
Here is a section of my code, as follows:
<?php
function onClickArchive($detail_locator){
for ($x = 0; $x <= 34; $x++) {
echo "<li><br />";
kal_generator($detail_locator);
echo "</li>";
}
}
if(isset($_POST['load_more'])){
onClickArchive($detail_locator);
}
?>
</ul>
<div id="reload_section">
<center><br />
<form method="post">
<input type="submit" value="Load More" name="load_more" class="load_more_content" />
</form>
</center>
</div>
There are multiple methods to potentially solve this. One option would be to make the client send the existing data back when the button is pressed so you can append the new data to it without overwriting it.
The other option is to use AJAX to call the method and append to the existing data client side.
Use/Try this PHP Function:
function setInterval($f, $milliseconds)
{
$seconds=(int)$milliseconds/1000;
while(true)
{
$f();
sleep($seconds);
}
}
Usage:
setInterval(function(){
echo "I will echo many times!";
}, 1000);
It is like in setInterval in JavaScript
setInterval(Function(), seconds);
you need to make use of Jquery.
firstly use .load() method which will loads the data from server then use
.append() method which will add the resulting data to the selected element.
$('.load_more_content').click({
$('#reload_section').append($('<div />').load('sample.php'));
});
Related
I am making a exam portal in which i have option conducting exam/quiz. Now i have added 2 buttons namely Next and Previous . I wanted to fetch Question and its option on button Click.
My database has following structure: Question(qid,question,option1,option2,option3,option4,right_option)
What I am tryin to do:
<input id="first" type="button" value="NEXT" onClick = "show_next()">
<input id="second" type="button" value="PREV" onClick = "show_prev()">
<script>
function show_next()
{
<?php
$question_no; //my global php variable to keep track of question id
$question_no = $question_no + 1;
show_question($question_no); //php function which shows data according to question no
?>
}
function show_prev()
{
<?php
if($question_no>0)
{
$question_no = $question_no-1;
show_question();
}
else
{
?>
alert("Wrong Operation");
<?php
}
?>
}
</script>
I am new to php and javascript, please suggest the correct method and if possible coding snippet for my question
Use jQuery/AJAX.
All you have to do is manage Offset and Limit dynamically.
e.g.
lets consider you are showing 1 question at a time and its options.
your html file will be.
<input id="first" type="button" value="NEXT" onClick = "show_next()">
<input id="second" type="button" value="PREV" onClick = "show_prev()">
<input id="offset" type="hidden" value="0">
In your javascript file
function show_next()
{
var offset=$('#offset').val();
$.post('GetQuestion.php',{offset:offset},function(data){
$('#question_answer').html(data);
$('#offset').attr('value',offset+1);
})
}
function show_prev()
{
var offset=$('#offset').val();
$.post('GetQuestion.php',{offset:offset},function(data){
$('#question_answer').html(data);
$('#offset').attr('value',offset-1);
})
}
In your GetQuestion.php file you can access offset value using $_POST. All you have to do is use that value in your query.
mysql_query("SELECT * FROM questions LIMIT ".$_POST['offset'].",1");
echo your query result in php file so that it could be available to var data in javascript.
As far as i know, PHP is executed on the server and the JS is executed Client-Side, so you can't mix it.
You have to Options.
Load all Questions in different divs and hide them. Then you can show one by one with the next and the previous buttons.
Build the page with a parameter like this: http://myapp.com/question/1 And make the Next BUtton /question/2 The question page should now contain only 1 question.
Edit:
Here is a fiddle for the 1. method:
http://jsfiddle.net/zj7ts/
$('.question').hide()
$question_shown = $('.question').first().show();
$('.next').click(function(){
$('.question').hide()
$question_shown = $question_shown.next().show();
});
$('.prev').click(function(){
$('.question').hide()
$question_shown = $question_shown.prev().show();
});
I have a column that has a button that when pressed, links to a URL set in PHP. I want to add a checkbox next to that button so that if it's checked when a user presses the button, it will take them to an alternate url. The PHP code setting the url:
<?php
$link = 'http://www.example.com';
?>
I realize that the code needs to be in javascript, which I don't know. I know only a tiny bit of php, so any help would be apprciated.
To clarify: (and of course I know this code will never work)
What I want to do is this:
<?php
If (checkbox is checked) {
$link = 'http://www.google.com';
} else {
$link = 'http://www.example.com';
}
?>
There is probably another way to do what you want to achieve. The value of the checkbox should be sent to a single php script on the server with the rest of the form's fields' values. Then you can use the checkbox's value (boolean) in php and do what you need to do accordingly, possibly requiring external scripts.
Checkbox value is not sent to server with form submit if it is not checked.
So, you can use something like this:
<?php
if (isset($_POST['checkbox_name'])) {
$link = 'http://www.google.com';
}else{
$link = 'http://www.example.com';
}
?>
Include the jQuery from Google:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
Then write the redirect function which you call after clicking the button;
<script>
function foo() {
if ($('#checkbox').is(':checked')) {
//redirect to google.com
window.location = "http://www.google.com/";
} else {
window.location = "http://www.example.com/"
}
}
</script>
And finaly your button should look like this:
<button onclick="foo();" >Your button</button>
This code assumes your checkbox has an id "checkbox".
Also, I don't think that what you're trying to do should be done with PHP - so you should learn Javascript/jQuery straight away instead of writing code the way it shouldn't be written.
Example: http://jsfiddle.net/5bdae/
Using jQuery this is fairly simple. You bind a function to the link, this function works out whether the checkbox is checked, if it is it links to one place, otherwise it links to another.
For an HTML structure like this:
<input id='myCheckbox' type="checkbox" name="box" value="box" />
<a href='#' id='myLink'>My Link</a>
The jQuery would be:
$('#myLink').click(function(event){
event.preventDefault();
if ($('#myCheckbox').is(':checked')){
window.location.href='http://www.example.com';
} else {
window.location.href='http://www.ask.com';
}
});
This could would go outside of the PHP tags, and you would need to include jQuery in your code.
I am trying to create a button, that whenever it is clicked (Onclick)
<button onClick="showUser(<?php echo $b?>)">Back</button>
it changes a value (number) so that the number can be retrieved by a function that will
be able to display information. Example I am calling the buttons next and back- if the button next is clicked, I want it to keep increasing it's value everytime I click it so that when it's number increases, different information will be accessed depending from that number, example when I first click the button (it would be value 1) information will be visible then when I click again it will increase to (2) and I will be able to see other information, the problem is that whenever I try to increase the value, the value increases only once.
I am doing this so that I will have information displayed and everytime the user clicks these buttons next and back, information sequentially will be shown- taken from a database.
I am using javascipt, php and sql.
Is what I am saying possible?
You could use an object, in which you set the two variables that you need to update on click:
var obj = {
nextClicked : 0,
prevClicked : 0
};
function buttonClick(type) {
if(type == "prev") {
obj.nextClicked++;
}
if(type == "next") {
obj.prevClicked++
}
}
<button type="button" onclick="buttonClick('next')">Next</button>
<button type="button" onclick="buttonClick('prev')">Prev</button>
Since you are using ajax, the variables would not reset, unless you refresh the page
You could use a php session to store the "page" number you're currently on and then increase or decrease based upon which button is clicked (you could use ajax or a simple form to send the event data).
use a hidden field to hold the value, and an onclick function to increase it and submit the form.
<?
if(!isset($_GET['count'])) {
$count = 0;
} else {
$count = $_GET['count'];
}
?>
<script type='text/javascript'>
function submitForm(x) {
if(x == 'prev') {
document.getElementById('count').value--;
} else {
document.getElementById('count').value++;
}
document.forms["form"].submit();
}
</script>
<form action='hidfield.php' method='get' name='form'>
<input type='hidden' name='count' id='count' value='<?php echo $count; ?>'>
</form>
<input type='submit' name='prev' value='prev' onclick="submitForm('prev')">
<input type='submit' name='next' value='next' onclick="submitForm('next')">
Add this to your webpage and refresh a few times.
<?php
session_start();
echo $_SESSION['count']++;
Can be tested here:
http://codepad.viper-7.com/qXdj8M
I am making a web page which will allow users to input and view data for different dates, and to change the date, there are two buttons, one of which will display the previous day, and one which will show the next day. I know that I can do this by submitting forms and reloading the page every time they press one of these buttons, but I would rather use javascript and not have to submit a form, but I am having troubles getting it to work. Currently, I have the two buttons, and the date stored in a PHP variable, as shown in my code below:
<script>
function init() {
<? $nutrDate = $this->parseDate(date('m/d/Y')); ?>
}
function nutrPrevDay() {
<? $nutrDate = mktime(0, 0, 0, date('m',$nutrDate), date('d',$nutrDate)-1, date('Y',$nutrDate)); ?>
alert("<? echo(date("m/d/y", $nutrDate)) ?>");
}
function nutrNextDay() {
<? $nutrDate = mktime(0, 0, 0, date('m',$nutrDate), date('d',$nutrDate)+1, date('Y',$nutrDate)); ?>
}
window.onload = init;
</script>
<p style="text-align:center; font-size:14px; color:#03F">
<button onclick="nutrPrevDay()" style="width:200px" >< Show Previous Day</button>
<? echo(date('m/d/Y', $nutrDate)) ?>
<button onclick="nutrNextDay()" style="width:200px">Show Next Day ></button>
</p>
I have the alert in the nutrPrevDay() only as debugging. What happens is when I click on the button, the alert shows that the day is correctly decreased (for example from May 17 to May 16), but only decreases one day, and not one day for every click. Also, I do not know how to make the text on the page (created by the line ) change to display the new date after a button is clicked.
So here are my questions:
1) Is it possible to dynamically change data (such as text, and in the future, SQL queries) on a page using javascript without having to reload a page when clicking on a button?
2) If possible, how can I make those changes?
3) How can I fix this so that it will increment and decrement through dates every time a button is clicked?
Q1:
Yes, it is possible, AJAX is probably what you're looking for.
Q2:
Well, first of all you have to learn that JavaScript works at client side while PHP works at server side. With that in mind, you can't expect that php scripts are executed when you click a button just because you wrote them inside javascript functions.
The most you can do is print something from a PHP script into a JavaScript script. And your script fails in that, except for the alert part. Example:
<script>
function javascriptFunction(){
// This php script, will be executed when you call your page, however $nutrDate is an assigned php variable, javascript will never know about it;
<?php $foo = 'bar'; ?>
// This will give you a javascript error because $foo is a string
var foo = <?php echo $foo; ?>;
// This is the code which will do the expected, notice the quotes.
var foo = '<?php echo $foo; ?>';
// If you have a single quote inside $foo, it will break javascript
<?php $foo = "ba'r";
var foo = '<?php echo $foo; ?>';
}
</script>
Q3:
The idea is to make an AJAX request every time your buttons click event is triggered... This is the same as saying, when you click a button, you call a javascript function which will make a request to some other page and get something from it if the request is successful. Here the example:
<script>
var current = <? echo time(); ?>;
function requestSomething(action){
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
// readyState info: http://www.devguru.com/technologies/xmldom/quickref/httpRequest_readyState.html
if (xmlhttp.readyState==4 && xmlhttp.status==200){
// this is where we tell where the result will appear
document.getElementById("current").innerHTML=xmlhttp.responseText;
current = xmlhttp.responseText;
}
}
xmlhttp.open("GET","somescript.php?action="+action+'&curday='+current,true);
xmlhttp.send();
}
</script>
<p style="text-align:center; font-size:14px; color:#03F">
<button onclick="requestSomething('decrease')" style="width:200px" >< Show Previous Day</button>
<!-- this is where the result will appear -->
<span id="current"></span>
<button onclick="requestSomething('increase')" style="width:200px">Show Next Day ></button>
</p>
Now, at your somescript.php file,
<?php
if(isset($_GET['action'])){
if($_GET['action'] == 'increase'){
// your increasing day logic here
} elseif ($_GET['action'] == 'decrease'){
// decreasing logic here
} else {
// whatever...
}
}
?>
Note: This is almost written from scratch and with some copy/past from here and there, and didn't check if the code actually works... It is just a guideline...
Hope it helps.
You don't need Ajax for this. There is very little you can do with PHP that you can't do with Javascript - you should only use Ajax when you absolutely need to communicate with the server (ex: need something from the database, etc.). Even if you may be using Ajax a later point you shouldn't use it everywhere, especially when a simple script may be able to solve your problems.
As it so happens Javascript has a number of built-in date functions that are every bit as powerful as PHP's.... and if they don't do what you need out of the box you can easily write your own.
http://www.w3schools.com/jsref/jsref_obj_date.asp
Keep it simple.
<input type="button" name="continue" id="continue" value="Continue" onclick="<?
if($_POST['rules']==null) {
echo "hello();";
}
elseif($_POST['rules']!=null) {
echo "myRedirect();";
}
?>" >
i have a form with a textarea. when the user hits the button when the textarea is null it should do the function hello() and if the textarea is not empty it should do the function myRedirect(). the function hello() and myRedirect() generates different dialog boxes. but it doesn't seem to work. what's wrong with this code?
It's not possible like that. JavaScript (onlick) executes in client browser while PHP executes on your server. IF you really need to execute PHP code you should use AJAX to send another request for your server to do PHP part.
If you're simply checking the value of the box, you just need Javascript... This should work fine:
<script type="text/javascript">
function check(obj_id){
var result = document.getElementById(obj_id).value;
if(result == ""){
is_null();
}else{
is_not_null();
}
}
function is_null(){
alert("null");
}
function is_not_null(){
alert("not null");
}
</script>
<input type="text" id="test" />
<button onclick="check('test')">Test</button>
Pass the id of the textbox you want to check into the check() function, and it finds whether anything has been entered into the box. If it has, it calls the function "is_null()" and "is_not_null()" if there is something in the textbox.
I think it will not work at all because you are trying to call a PHP code from javascript.
In other words PHP is a server side scripting language and you are trying to execute a server side code that needs to be submitted in order to get executed.
To achieve this functionality you can simply write this code
if($_POST['rules']==null)
{
echo "hello();";
}
elseif($_POST['rules']!=null)
{
echo "myRedirect();";
}
at the top of your PHP page and you will get what you want. or make the input type as "submit"
You probably need a postback to the server to execute whatever you want to run in the onclick event.
Another work around is to use AJAX.
Are you mixing up client side and server side? Is this what you're after?
<?php
if($_POST['rules'] == null) {
echo "hello";
} else {
myRedirect();
}
?>
<input type="submit" name="continue" id="continue" value="Continue">
<script>
function hello(){}
function myRedirect(){}
function ifnullz(el){
if($(el)!=0){
hello();
}else{
myRedirect();
}
}
function $(el){
document.getElementByID(el).length; //.value?? idk.. something like that.
}
</script>
<input onlcick="ifnullz('lolz');">
<textarea id="lolz"></ta>