Guide on adjusting PHP variable values and updating functions with ajax requests

One of my functions determines dates based on a variable

For example: $modification = "+1 Week"

function updateCalendar($change){

    $month = array("January","February","March","April","May","June","July","August","September","October","November","December");
    $dateNow = new DateTime(date('Y-m-d'));
    $dateNow->modify($change);
    $yearNow = $dateNow->format('o');
    $weekNow = $dateNow->format('W');
    // and so on...
    

I need to know how I can change $modification using buttons on a webpage and then refresh the function.

For instance: Button to Increase = +1 week and Button to Decrease = -1 week.

UPDATE: RESOLVED

PHP:

// PHP code goes here

JS:

// JavaScript code goes here

I have created two buttons, one to increase and one to decrease the week. By utilizing a hidden input field '#calMod' and checking for specific weekdays (e.g., Fridays), the calendar functionality now works as intended. The next step involves selecting days and storing them in JSON format. Thank you for all the assistance!

Answer №1

Utilizing the power of an HTML button element to trigger a PHP function without the need for a page refresh:

calendar.html

<div id="buttons_week">
  <button>+1 Week</button>
  <button>-1 Week</button>
</div>
<div id="calendar"></div>

<script>

// retrieving target display
var calendar = document.getElementById('calendar');

// selecting buttons and iterating through them
Array.prototype.forEach.call(document.querySelectorAll('#buttons_week button'), function (elem) {

    // adding function to click event
    elem.addEventListener('click', function (evt) {
        // setting up XHR object
        if ( window.XMLHttpRequest ) {
            xmlhttp=new XMLHttpRequest() // IE7+, Firefox, Chrome, Opera, Safari
        }
        else { // IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function() {
            if (xmlhttp.readyState==4 && xmlhttp.status==200) {

// here's where you manage the response received from the PHP script

                // for debugging
                //calendar.innerHTML = xmlhttp.responseText
                //console.log(JSON.parse(xmlhttp.responseText))

                // parsing JSON string from server and updating calendar
                var calendar_obj = JSON.parse(xmlhttp.responseText)
                calendar.innerHTML = calendar_obj.weekNum + '/' + calendar_obj.mName + '/' + calendar_obj.yearNum

            }
        }
        xmlhttp.open("GET","calendar.php?mod="+encodeURIComponent(evt.target.innerHTML),true);
        xmlhttp.send();
    })
})

</script>

calendar.php

<?php

echo json_encode(calendar($_GET['mod']));

function calendar($modification){
  // actual function code omitted for brevity
}

?>

If there's no necessity to reach out to the server for additional tasks, check out this JavaScript-only solution. No server calls required!

JSFiddle

<div id="buttons_week">
  <button>+1 Week</button>
  <button>-1 Week</button>
</div>
<div id="calendar"></div>

<script>

var calendar = document.getElementById('calendar');
Array.prototype.forEach.call(document.querySelectorAll('#buttons_week button'), function (elem) {
    elem.addEventListener('click', function (evt) {
        var calendar_obj = week_increment(evt.target.innerHTML)
        console.log(calendar_obj.days)
        console.log(calendar_obj.dayMonth)
        calendar.innerHTML = 
            calendar_obj.weekNum + '/' +
            calendar_obj.mName + '/' +
            calendar_obj.yearNum
    })
})

function week_increment(mod) {
    var dd = new Date()
    var week_inc = 7 * 24 * 60 * 60 * 1000
    if ( 0 === mod.indexOf('-') ) { week_inc *= -1 } // decrease week
    dd = new Date(dd.getTime() + week_inc)
    dd.setHours(0,0,0);

    var dayMonth = [], days = [], weekNum
    dd.setHours(-24 * ((dd.getDay() || 7) - 1))
    for ( ii = 0; ii < 7; dd.setHours(24), ii++ ) {
        days.push(dd.getDate())
        dayMonth.push(dd.getMonth()+1)
        if ( 3 === ii ) { // obtain weekNum on Thursday ??
            weekNum = Math.ceil((((dd-new Date(dd.getFullYear(),0,1))/8.64e7)+1)/7) // http://stackoverflow.com/a/18005464/2743458
        }
    }

    return { 
        'dayMonth': dayMonth,
        'days':     days,
        'weekNum':  weekNum, 
        'mName':    months[dd.getMonth()], 
        'yearNum':  dd.getFullYear()
    }
}

var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];

</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Gathering Servlet details from non-form elements

I am currently in the process of developing an application that is capable of parsing JSON strings. At this stage, I am able to input a JSON string using Java, write it to an HTML document, and then have a JavaScript program read and parse it before ultima ...

Utilizing the Jquery hover feature to reveal or conceal an element

My Hover function is designed to display and hide sub menus when a person hovers on them. The issue I'm facing is that the menu disappears when I move the mouse down towards it. Can someone help me identify what I am doing wrong here? ...

Having a parameter that contains the characters '&' and '&' can potentially disrupt an AJAX call

Even though there is a similar question here: Parameter with '&' breaking $.ajax request, the solutions provided do not apply to my specific issue. This is because both the question and answers involve jQuery, which I am not familiar with. I ...

How can I utilize a filter or pipe to populate product categories onto screens within Ionic 2?

I am considering creating an Ionic 2 app with 6 pages, but I'm unsure whether to utilize a Pipe or a Filter for the individual category pages and how to implement the necessary code. Each category page should be able to display products from the "app ...

`Sending PHP variables to AJAX - A Step-by-Step Guide`

I've been trying to access session variable data within an ajax call, but I'm facing a roadblock. Here's my code snippet. $('#update').click(function(){ var number = $('#num').val(); ...

Unable to smoothly expand Div in React using Tailwind

I'm facing a challenge in animating a div that contains input elements. I want it to expand smoothly - initially, the text area is small and the other two inputs and buttons are hidden. When clicking on the text area, the input and button should be re ...

Using database queries to populate a series of interconnected drop-down menus

Currently, I am facing an issue with my 2 drop-down menus. The first one is populated with possible continents, and the second should display countries based on the continent selected in the first menu. However, all countries are showing up in the dropdown ...

Guide on utilizing PHP DOM to display the file size for files included in the table of an HTML webpage

example.html (contains an extensive table with hundreds of files making it impossible to list all as arrays):- <table> <tbody> <tr> <td class="book"><a class="booklink" href="../file1.pdf" >Book1</a></td ...

Is there a way to customize the selected option in the autocomplete feature of Material UI components?

Is it possible to customize the CSS of selected options in Material UI autocomplete? Can this be achieved by utilizing the theme? ...

What is the best way to obtain the current route name within a Component?

Is it possible to retrieve the current route name in a controller? I have attempted using this.route, this.currentRoute, and this._routerRoot, but none of them seem to work. computed: { currentRoute:{ get(){ console.log(this.__routerRoo ...

Guide to extracting name and email address from a string in PHP, with the option to use regular expressions

The text below contains a list of names and emails: "Test, User" < <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="582c3d2b2c182c3d2b2c763b373b">[email protected]</a> >, "Another, Test" < <a href="/cdn ...

Retrieving information and implementing condition-based rendering using React's useEffect

I am currently developing a MERN stack application that retrieves information regarding college classes and presents it in a table format. The CoursesTable.js component is structured as follows: import React, { useState, useEffect } from 'react'; ...

Struggling with TypeScript and JsObservable? Let us assist you!

Having previous experience with JSRender, JSViews, and JSObservables, I recently embarked on a new project using TypeScript. Unfortunately, I am struggling to understand how to properly utilize TypeScript in my project, especially when it comes to referenc ...

Does jQuery's click event not successfully hide an element on Internet Explorer?

In my dropdown menu, I have the following options: <div class="my_div"> <select name="selection" id="select_id"> <option value="0">A</option> <option value="5">B</option> ...

Tips on maximizing efficiency in number game coding

Seeking to create a number using a specified set of 6+ inputs. For instance, aiming for the number 280 with inputs [2,4,5,10,30,50,66], the desired output format would be something like this: ((2+5) * 4 * 10). Each input number can only be used once per s ...

I'm struggling with my project called "Number TSP" and I can't seem to figure out why it's not working properly

Upon reaching the end of my code, I am encountering an issue where instead of seeing the expected output of "Done!", it displays undefined. This is the code in question: const container = document.querySelector(".container") const table = document.querySe ...

Changing the theme of a toggle button in Jquery Mobile when the button is pressed

I have a group of buttons with a specific class <div class="prog-day"> <div class="prog-clear" data-role="controlgroup" data-type="horizontal> <a href="#" data-role="button" data-mini="true" data-theme="b">Clear</a> ...

Enhancing Prestashop with eye-catching subcategory images in the top menu

One feature in Prestashop is the ability to add images (thumbs) to subcategories menu if ((int)$category['level_depth'] > 1 && !$is_children) { $files = scandir(_PS_CAT_IMG_DIR_); if (count(preg_grep(& ...

Select one href by clicking and apply addClass

I have a one-page HTML document with links in the header. I want to make it so that when I click on a link (<a>), only that specific link changes its class to (.links). I've tried various methods, but the current jQuery method I'm using ad ...

Strategies for combining objects with varying structures on a map

SUMMARY: Looking to merge the data from Students into the corresponding values of Employees, where the value from Students should be included in the same array as Employees['avg_rate' and 'expense']. The updated object array should be ...