javascript href function usage

There's an issue I'm facing when using a link click to update a database field and redirect to another page. Here's the code I have:

<a href="#" onclick="<?php  

                        $sql="UPDATE MyDB.mytable SET Date = '".date("Y-m-d H:i:s")."' 
                                WHERE ID='" . $id . "'";
                        if (!mysql_query($sql)) ///Cannot query
                        {
                            $logger->error(mysql_error()); 
                        }

                        if ($sql)
                        {
                             $logger->debug('OK');
                        }
                        else
                        {
                             $logger->debug( 'NOt OK');
                        }
                      ?>"> </a>

Can I include a path to redirect to after the php end tag '?>' like this:

<a href="#" onclick="<?php  

                        $sql="UPDATE MyDB.mytable SET Date = '".date("Y-m-d H:i:s")."' 
                                WHERE ID='" . $id . "'";
                        if (!mysql_query($sql)) ///Cannot query
                        {
                            $logger->error(mysql_error()); 
                        }

                        if ($sql)
                        {
                             $logger->debug('OK');
                        }
                        else
                        {
                             $logger->debug( 'NOt OK');
                        }
                      ?> ../index.php"></a>

Is this approach feasible? What would be the correct way to achieve this? Thank you!

Answer №1

There are various approaches to achieve this task. However, I recommend placing the DB update code in the target page (such as index.php). If you only want the DB update code to execute upon clicking a link, you can create a middleman page to redirect the flow.

Here is the suggested page flow:

Current Page (Link Clicked, simple href to middleman.php) ==> middleman.php (execute the DB update code and use header Location syntax to redirect to index.php) ==> index.php

Code snippets:

Page with the link source.php

<.... html contents ....>
<a href='middleman.php'>Visit the page</a>
<.... more html contents ....>

middleman.php

<?php  

$sql="UPDATE MyDB.mytable SET Date = '".date("Y-m-d H:i:s")."' WHERE ID='" . $id . "'";
if (!mysql_query($sql)) ///Cannot query
{
   $logger->error(mysql_error()); 
}

if ($sql)
{
 $logger->debug('OK');
}
else
{
 $logger->debug( 'NOt OK');
}

header("Location: index.php"); //redirects to index.php
?>

index.php

do whatever you want

Answer №2

Each time a webpage is loaded, the php code will only run one time. Despite seeing a webpage's content as html, you do not have live access to the underlying php code. This means you cannot directly trigger php code execution from something like a javascript event. In your scenario, the sql query will be executed once when the page is initially loaded.

There is a suggested solution by user kishu27, which is considered the best approach in this situation. If your goal is to update the database without redirecting to another page, using an ajax call to a separate php file containing the database code would be a suitable alternative.

Answer №3

Implementing location.pathname

<a href="#" onclick="location.pathname='<?php ... ?>'"></a>

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

Transform your HTML audio player into a Vue component

I am in the process of converting an HTML player into a Vue component. Half of the component has been successfully converted, but the time control slider is still missing. Below is the original HTML code for the player: // JavaScript code for the audi ...

Only perform the Rails ajax call once initially

I'm currently working on creating a drop down menu that contains a substantial amount of content, and I would like to use an ajax get call to load everything upon mouse enter. Here is my code written in coffeescript: class @SecondaryMenu construct ...

Obtaining a cookie in Vue.js independently: a step-by-step guide

After setting a cookie using laravel, I'm looking to retrieve it in vue.js without relying on or installing any external dependencies. Can anyone please suggest a way to achieve this without extra tools? Your guidance would be greatly appreciated! ...

A guide to incorporating external CSS files in Angular 5 components using styleUrls

I have a unique setup where my Angular 5 application resides in a subdirectory within another parent application. The parent application consists of JSP and other AngularJS applications among other things. My goal is to include a CSS file from the parent ...

Transform basic list into a two-dimensional array (grid)

Picture a scenario where we have an array: A = Array(1, 2, 3, 4, 5, 6, 7, 8, 9); We aim to transform it into a 2-dimensional array (a matrix of N x M), similar to this representation: A = Array(Array(1, 2, 3), Array(4, 5, 6), Array(7, 8, 9)); It's ...

Top solution for live chat between server and client using jQuery, Java, and PHP on a localhost setup

Seeking recommendations for the best chat solution to facilitate communication between client PCs and a server in my private network. Specifically interested in an Ajax/Java solution similar to the chat support feature found in GMail. ...

What exactly does the combination of {on, attrs} create within Vue/Vuetify?

Although this question may have been asked before, I am still struggling to grasp its meaning. Can you help me understand it better? <v-dialog v-model="dialog" width="500" > <template v-slot:activator=&quo ...

Continuously replicate SVG horizontally without limit

In search of the perfect visual effect, I am eager to develop an infinite animation featuring a car moving horizontally with various landscape layers passing by in SVG format. Struggling to find a way to seamlessly repeat my SVG landscape layers along the ...

The Enum object in TypeScript has not been declared or defined

For my TypeScript application, I am utilizing WebPack to transpile and bundle the code. The final result is intended to be used in a pure JavaScript website. One of the components in my application is an enum defined as follows: export const enum ShapeTyp ...

Mastering the flow of control in Node.js programs

Attempting to grasp control flow within Node.js applications. Specifically, does control loop back to the original function once the callback method completes, similar to a callback stack in recursive calls? A simple program was crafted to make a GET call ...

JavaScript code is functioning properly on Chrome and Internet Explorer, however, it may not be working on FireFox

Despite searching through the console, I am unable to find a solution to this issue. There are two images in play here - one is supposed to appear at specific coordinates while the other should follow the mouse cursor. However, the image intended to track ...

Automatically trigger a popup box to appear following an AJAX request

I am currently working on a time counter script that triggers a code execution through ajax upon completion. The result of the code should be displayed in a popup box. Below is the code snippet I am using: var ticker = function() { counter--; var t = ...

Utilizing Node and Express to promptly respond to the user before resuming the program's

I am accustomed to receiving a user's request, handling it, and providing the outcome in response. However, I am faced with an API endpoint that requires about 10 tasks to be completed across various databases, logging, emailing, etc. All of these ta ...

"Exploring the world of TypeScript Classes in combination with Webpack

If I create a TypeScript class with 10 methods and export a new instance of the class as default in one file, then import this class into another file (e.g. a React functional component) and use only one method from the class, how will it affect optimizati ...

Guide on adding a personalized table or Div section in a datatable

I am looking to add a custom table above a datatable, specifically I want the custom table to be displayed above the header columns. Here is the code I have tried: columns: [ { "data": "WorkFlowType" }, { "data": "WorkflowInstanceId" } ...

Using destructuring repeatedly for a single object property

At times, I engage in nested destructuring, where I go more than one level deep. It can be risky, but I always make sure the property exists to avoid encountering an error of undefined. Recently, I came across this scenario: const { match: { ...

The data being transmitted by the server is not being received accurately

Hey there! I've recently started using express.js and nodejs, but I've encountered an issue where my server is sending me markup without the CSS and JS files included. const express = require('express'); const app = express(); const htt ...

Looking for help understanding a basic piece of code

$('#ID').on('click', function() { if(!CommonUtil.compareDateById('startDt','endDt',false, false, true)) { return false; } var cnt = 0; if(!CommonUtil.isNullOrEmptyById('startD ...

Preserving scroll position when updating a partial page template using Rails and AJAX

When I am utilizing long polling, I encounter an issue where every time I use AJAX to refresh a page partial inside a scrollable div, the contents automatically scroll to the top. Is there any way to load the partial while maintaining the current scroll ...

Learn how to prevent two-finger swipe forward/backward on a trackpad using JavaScript or HTML

My app includes a functionality where the URL changes when transitioning from one state to another, for example from home/#state to home/#state2. However, I noticed that when I perform a two-finger swipe using the trackpad from home/#state2, the page navig ...