Utilize JavaScript within a PHP foreach loop for submission

Modifying my query

I have a form with submit functionality without refreshing the page, however this form is embedded within a foreach loop

Where should I place the JavaScript code? Inside the foreach loop or outside?

If it's placed outside, how can I assign a unique identifier to it?

  <script>
    const myForm = document.getElementById('follow<?php echo $card['user_id']; ?>');

    myForm.addEventListener('submit', function(e){
        e.preventDefault();

        const formData = new FormData(this);

        fetch('../config/follow.php', {
            method: 'post',
            body: formData
        }).then(function(response){
            return response.text();
        }).then(function(text){
            //alert(text);
                $("#update").load(window.location.href + " #update" );            
        }).catch(function(error){
            //alert(error);
            alert('The operation could not be completed');
        });
    });
</script>
<form method="POST" id="follow<?php echo $card['user_id']; ?>">

<input type="hidden" name="target" value="php $card['user_id'] ">


<div id="update">
<!-- <button change after submit (0 or 1)-->
</div>

</form>

Answer №1

It appears that the question you presented is a bit unclear to me. I am having trouble grasping the specific details you are trying to convey. However, upon analyzing the syntax of your code, I noticed that there seems to be an issue with the missing 'php' keyword in the opening PHP tag:

<form method="POST" id="follow<?php echo $card['user_id']; ?>">
and
const myForm = document.getElementById('follow<?php echo $card['user_id']; ?>');

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

Using default language in Next.js internationalization: a step-by-step guide

I've been immersing myself in the Nextjs internationalization documentation for the past two days. My goal is to have support for two languages: en, fa. I also want to be able to switch between them with URLs structured like this: https://example.com ...

Tips for adjusting the margin of a print document in a printTask?

Is there a way to achieve a borderless print? Currently, my printed output has a border around it. I would like the image to start at the top left corner without any borders. I attempted to set a negative margin to the print-style box, but it resulted in ...

Steps to activate a particular Bootstrap tab upon clicking a hyperlink

Trying to implement a Bootstrap tab panel in the following manner: <ul class="nav nav-tabs" role="tablist"> <li class="nav-item"> <a class="nav-link active" data-toggle="tab" href ...

When the user hovers over a list item, extract the ID associated with a MySQL table and display all rows from that table in a new list

I am looking to create a dynamic submenu that pulls data directly from a MySQL table. I currently have JavaScript code that retrieves the ID of the list item being hovered over... $(document).ready(function() { $('.courseTitle').mouseover(funct ...

Mastering the Art of Parsing Complex JSON Data

I received a JSON output that looks like this. Using getjson, I'm trying to extract the datetime and value fields (italicized and bolded) such as [16:35:08,30.579 kbit/s],[16:35:38,23.345 kbit/s]. Is there any solution to achieve this? Thank you. { ...

Changing UUID from binary to text and vice versa in NodeJS

I recently started a project that transitioned to using MySQL as our database. We are working with UUID strings (such as 43d597d7-2323-325a-90fc-21fa5947b9f3), but the database field is defined as binary(16) - a 16-byte unsigned binary. Although I know th ...

Ajax requests that are delayed to the same URL with identical data

While waiting for the back end developers to add a "cancel all" function, which would cancel all tasks tracked by the system, I am trying to create a workaround by cancelling each task individually. The cancellation REST service requires an ID in the form ...

How can I change the date format from yyyymmdd to yyyy/mm/dd using an Angular pipe in HTML?

Can Angular convert a date in the yyyymmdd format to yyyy/mm/dd directly? I attempted using an Angular pipe, but it produced a different date result. The date I have is 20201029 {{date | date:'yyyy-MM-dd'}} ...

Using jQuery, remove any white spaces in a textbox that are copied and pasted

There is a textbox for entering order IDs, consisting of 7 digits. Often, when copying and pasting from an email, extra white spaces are unintentionally included leading to validation errors. I am looking for a jQuery script to be implemented in my Layout ...

What steps do I need to take to share my Node JS application on my local area network (

I have a Node.js application running on my Ubuntu machine successfully, as I can access it through localhost:8080. However, other machines on the network are unable to reach it. CODE: const portNumber = 8080 let app = express() app.use(express.static(__d ...

Different Methods for Iterating through Data when Formatting for D3.js

Struggling with an error previously discussed on StackOverflow. The issue lies in my D3.js code struggling to iterate through an object. Raw data is sourced from a RESTful web api, loaded into a variable 'dataset' using jQuery and JavaScript. Out ...

`Upkeeping service variable upon route alteration in Angular 2`

Utilizing a UI service to control the styling of elements on my webpage is essential. The members of this service change with each route, determining how the header and page will look. For example: If the headerStyle member of the service is set to dark ...

Issue with onblur and focus while returning back from external window

Instructions to reproduce the issue: Important: Set up two input fields with names and add a console.log("Test Focus In" + element.getAttribute("name")) and console.log("Test Blur" + element.getAttribute("name")) statement in the focusin and blur event f ...

Shut down jquery modal

I have successfully imported Jquery Modal using the following two links (js and css) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.1/jquery.modal.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cl ...

Guide on inserting a string to create a query using PHP CodeIgniter

I am working with a collection of strings generated by selecting multiple checkboxes, and I want to use these strings to create a query. For instance: If I select a specific combination of checkboxes, it produces this string value: "SELECT Call_Setu ...

Tips on modifying the message "Please fill out this field" in the JQuery validation plugin

Is there a way to customize the message "This field is required" in the Jquery form validation plugin to display as "このフィールドは必須です"? Changing the color of the message can be achieved using the code snippet below: <style type="tex ...

Do arrays permanently retain the strings stored within them?

As an 11-year-old who has been learning Javascript for the past month and a half, I am currently working on creating a login/register system. Right now, my focus is on the register part. I have a question: when adding a string/number/boolean to an array, d ...

Ensuring proper functionality of JQModal when displayed above an iframe with the usage of ?wmode=

Here's an interesting one... I'm currently working on a site with JQModal and everything seems to be functioning properly except for the fact that the iframe appears on top of the modal. An easy fix is to append ?wmode=opaque at the end of the ...

Issue: The object identified as #<Object> does not contain the 'toUpperCase' method

I am currently encountering the error Object #<Object> has no method 'toUpperCase' right before the POST request is initiated. Any assistance you can provide would be greatly appreciated! Thank you in advance. function ajaxeo(url, data, me ...

Having trouble with the Express-generator functionality

I think I might have changed the installation location of node modules. I globally installed express-generator. D:\chirp> npm install express-generator -g When I attempt to run D:\chirp> express --ejs An error appears in the Comman ...