Using an image as an onclick trigger for a JavaScript function

I am working on a registration page as part of my university project where users can create an account and store their information in a MySQL database.

One feature I'm implementing is the ability for users to select an avatar picture. Below is the code snippet:

                        <u>Choose your avatar:</u><br>
                        <?php

                            // Open the directory
                            $image_dir = opendir("images/avatars");

                            // Get each image file
                            while( $image = readdir( $image_dir ) )
                            {
                                $dirArray[] = $image;
                            }

                            // Close the directory
                            closedir($image_dir);

                            // Count the elements in the array
                            $indexCount = count($dirArray);

                            // Loop through the files and display them in a list
                            for($index=0; $index < $indexCount; $index++)
                            {
                                $extension = substr($dirArray[$index], -3);

                                if( $extension == "jpg" || $extension == "gif" )
                                {
                                    echo("<img id='$index' onClick='SetAvatar($index)' img src='images/avatars/$dirArray[$index]' class='o'> ");
                                }
                            }
                        ?>

                        <script>
                            function SetAvatar(id) {
                            var image = document.getElementById(id);

                                if( CurSelectedImage != null && id != CurSelectedImage )
                                {
                                    var image_to_unselect = document.getElementById(CurSelectedImage);
                                    image_to_unselect.Selected = false;
                                    image_to_unselect.style.border = null;
                                }

                                if( image.Selected != true )
                                {
                                    image.style.border = 'medium solid blue';
                                    image.Selected = true;
                                    SelectedImage = id;
                                }
                                else
                                {
                                    image.style.border = null;
                                    image.Selected = false;
                                    SelectedImage = null;
                                }


                            }
                        </script>

The code allows users to select an avatar, highlights it with a blue border, and keeps track of the selected image ID. However, I'm not sure how to pass this variable containing the selected image ID back to PHP for saving. Any suggestions would be greatly appreciated.

Thank you!

Answer №1

Are you able to provide your CSS code as well?

If not, you can check it out here for a solution on jQuery select and unselect image your response

Answer №2

When considering your application design, it's important to avoid mixing PHP and JavaScript. Instead of combining these languages, opt for using an API for a cleaner approach. Utilize Ajax to call the API, which can lead to a more efficient design:

  1. Develop a getImages API in PHP: Output the data as a json array.
  2. Call this API using JavaScript and dynamically generate the DOM with the json data.
  3. Create a click handler in JavaScript, then call another API in PHP.
  4. Retreive the json data in PHP and store it in your database.

:)

Answer №3

One idea to consider is utilizing a CSS class in this scenario. Start by removing any existing occurrences of the class, followed by adding it to the chosen image.

function SetAvatar(id) {
  //Remove current border(s) using a while loop due to live node list issues
  var elements = document.getElementsByClassName("selected-avatar");
  while (elements.length > 0) {
    var element = elements.item(0);
    element.className = element.className.replace(/(?:^|\s)selected-avatar(?!\S)/g , '');
  }

  var image = document.getElementById(id);
  image.className += " selected-avatar";
}

If you need to transmit the avatar data, incorporating a form can be helpful. Ensure all registration details are sent to process_register via the form, and use a hidden input field which gets populated with data through javascript before submission.

Example HTML:

<form id="registration-form" action="process_register.php" method="put">
  <input id="registration-avatar" type="hidden" />
  <button id="registration-submit">Submit</button>
</form>

Javascript snippet:

document.getElementById("registration-submit").onclick = function(){
    var avatarValue; //Code needed to assign value based on selected avatar
    document.getElementById("registration-avatar").value = avatarValue;
    document.getElementById('registration-form').submit();
};

In PHP, retrieve the values using $_POST as outlined here: PHP Docs for POST Variables

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

Experiment with the Users.Get function available in vk-io

I am having an issue with a create command: Ban [@durov] and I encountered an error. Here is how I attempted to solve the problem: let uid = `${message.$match[1]}` let rrr = uid.includes('@') if(rrr == true){ let realid = uid.replace(/[@]/g, &ap ...

Issue with integrating Razorpay into a Node.js Express application

I am currently working on setting up a checkout page using nodejs and express with Razorpay as the payment gateway. The issue arises when trying to run the checkout() function by clicking the "Checkout" button within my shopping-cart.hbs file. Despite havi ...

Fetch a document from a NodeJS Server utilizing Express

Is there a way to download a file from my server to my machine by accessing a page on a nodeJS server? I am currently using ExpressJS and I have attempted the following: app.get('/download', function(req, res){ var file = fs.readFileSync(__d ...

The jQuery.ajax request encounters issues within a Chrome extension

I'm in the process of migrating one of my Firefox browser extensions to Chrome, and I've encountered an issue related to an AJAX query. The code snippet provided functions correctly in the Firefox extension but fails with a status of "0" when exe ...

What happens when an AJAX request doesn't have a success field?

Is it possible to execute an ajax call without specifying a success function? $.ajax({ type: "POST", url: "/project/test/auto", data: data, // no success function defined here }); My reasoning for this is that I have PHP code that insert ...

Is there a way to compel Google Maps to load within my Angular application by implementing an Angular Directive?

I am encountering an issue where my Google Map fails to display most of the time. It seems that the map is not fully rendered when the rest of my data is populated in my Angular view. Is there a way to force the map to load? I have done some research and ...

Hiding and showing div elements using CSS, JavaScript, and PHP

Here is the current code snippet: <? while ($row1 = mysql_fetch_object($result1)) { echo '<a href="#" onclick="showhide("'.$row1->id.'");">Name</a>'; while ($row2 = mysql_fetch_object($result2)) { ...

Different ways to provide user feedback on a SPA website following AJAX requests

I have a single-page application website developed using React.js. What are some options for notifying the user of successful/failed/pending AJAX calls resulting from various user interactions? I am aware of Toastr-style messages that appear in the corner ...

I am having trouble getting the border-radius to display properly in my email table

I'm in the process of designing a responsive email template. For the white content area, I've applied border-radius: 5px;. While it's working fine on the bottom corners of the table, the top corners don't seem to display the border-rad ...

Troubleshooting Next.js server actions with ESLint error detection

I encountered eslint errors while developing a basic server component with server action: // /app/search/page.tsx export default function Search() { async function updateResults(formData: FormData) { "use server"; await new Promise((r ...

Exploring the world of interactive storytelling through a basic PHP text adventure

I recently completed coding a text adventure using functions like fgets(STDIN) that works in the command line. Now, I want to convert it to run on HTML (internet browser) but I'm facing a challenge. I am unsure how to transition from this: $choose=0; ...

When URL string parameters are sent to an MVC controller action, they are received as null values

Are You Using a Controller? public class MyController : Controller { [HttpGet] public ActionResult MyAction(int iMode, string strSearch) { return View(); } } Within my view, I have a specific div with the id of "center" I am runn ...

Hide the burger menu when a link is clicked

Is there a way to make my Bootstrap burger menu automatically close when the user clicks on a menu link, rather than having to click on the burger itself? I've tried using some JavaScript code but it ends up disabling the burger menu entirely. Can any ...

What is the method to determine the overall size of a webpage using the Google PageSpeed API?

"analytics": { "cssResponseBytes": "333 kB", "htmlResponseBytes": "269 kB", "imageResponseBytes": "3.35 MB", "javascriptResponseBytes": "2.29 MB", "numberCssResources": 2, "numberHosts": 80, "numberJsResources": 72, "numberR ...

Whenever I execute the 'ng serve' command, I encounter an issue with ineffective mark-compacts close to the heap limit, resulting in an allocation failure and a JavaScript

I'm currently using Angular 9 and Node.js 12. When I input ng serve, I encounter the following problem: C:\Users\homz\my-app>ng serve 93% after chunk asset optimization SourceMapDevToolPlugin vendor.js generate SourceMap <--- ...

Issue with triggering jQuery .submit() function on Bootstrap 3 modal form

I've been attempting to use a Bootstrap 3 modal form to trigger a form.submit() in jQuery, but despite my efforts, I can't seem to get it to work as intended. <div class="modal fade" id="modal-signup" tabindex="-1" role="dialog" aria-labelled ...

Getting URL parameters in NextJS when using Custom Document can be achieved by accessing the `ctx`

Currently, I am utilizing NextJS for generating SSR pages that are language-specific. I want to specify the lang property to indicate the language of the text. Here's what I have done so far: import Document, { Html, Head, Main, NextScript } from &qu ...

Adjusting the array when items in the multi-select dropdown are changed (selected or unselected)

I am looking to create a multi-select dropdown in Angular where the selected values are displayed as chip tags. Users should be able to unselect a value by clicking on the 'X' sign next to the chip tag, removing it from the selection. <searcha ...

Tips for resolving the error message "TypeError: Cannot access property 'category' of undefined" while working in a React environment

Hey there, I encountered an issue while trying to destructure in react and can't figure out why the title is appearing as an error message. Below is the code snippet: const {correct_answer, incorrect_answers} = data[0] const arr = [correct_answer, ... ...

transferring data from ejs template

In my app.js file, I have an array that stores files. To display these files on a website, I use a for-loop in ejs: <% for(let i = 0;i<posts.length; i++){ %> <li class="listtitle"> <%= posts[i].title %> </li> ...