Lars Mertens
Lars Mertens

Reputation: 1439

Add +7 to variable $i each time button is pressed, no page reload

My Problem: I don't know how to add +7 to variable $i each time a button is pressed. I tried with isset($_POST) but than you can only execute the code block to add +7 to $i once i want it to be unlimited.

The function below uses variable $i to determine how many days you want to go forward, so in my case when $i = 7 it jumps 7 days forward. This function works fine.

Timeschedule.php

// UPDATED: Used other function instead to show what desired results i want to achieve

public function getDate($i){
        date_default_timezone_set('Europe/Amsterdam');
        $datetime = new DateTime('today');
        $datetime->modify('+' . $i . 'day');
        $output = $datetime->format('d-m-Y');

        return $output;
}

Orderstep_1.php

// This file includes timeschedule.php
include timeschedule.php

<input name="testbutton" class="testbutton" id="testbutton" type="submit" value="=>" />

Now i used isset with post but that can only execute the code once on the page and i need i to be unlimited.

if(isset($_POST['testbutton'])){
   $i = $i + 7;
}

Hope you guys can send me in the right direction.

UPDATED:

This code outputs the data

$testObject = new TimeSchedule();
$date1 = $testObject->getDate(0); echo $date1;

Output result

02-02-2015

Output i want to achieve after button clicks

09-02-2015
16-02-2015 
23-02-2015
etc...

Upvotes: 0

Views: 104

Answers (1)

holgac
holgac

Reputation: 1539

You're trying to implement client side logic with PHP. PHP is run once, on the server side, and the output (page) is sent to the client. After that, the variables in php do not exist anymore.

For client side logic, you'll probably need javascript instead. Javascript is run on client side, unlike PHP.

You'll need to rewrite getDay in javascript, use a context or some global variable for i, and pass that i to getDay each time the button is clicked.

Another option would be storing i in javascript but keeping getDay as PHP code, then whenever i changes, send an ajax request to a url that you're going to create that calls getDay, like getDay.php?i=0. getDay returns the date, and you update your date in javascript.

Your logic is simple and it'd probably better to keep it in client side, but for complex algorithms, you might want to run your methods in server side instead, since client side codes are visible.

Upvotes: 2

Related Questions