A step-by-step guide on incorporating a session variable from a for loop into an Onclick Javascript event and sending it via ajax

Apologies for the unclear title, my situation is a bit complex and I'm struggling to explain it correctly.

The scenario is illustrated with an image.

1.) I have a while loop processing JSON data from PHP (which includes multiple user IDs). 2.) Ajax retrieves this data and inserts it into HTML with a button assigned to each ID. 3.) When the button is clicked, it sends that specific ID to another PHP script.

I need help on how to extract data[i].userid and data[i].listingid in Ajax and send them out. Thank you for your assistance.

Image

PHP Code Snippet:

$result = mysqli_query($con, "SELECT * FROM list WHERE Listingid = '$Listingid' AND Status ='Bird'");
while($row = mysqli_fetch_array($result)) {
    $output[] = $row;
}
if (!empty($output)) {
    echo json_encode($output);
} else {
    echo json_encode([]);
}

Javascript Code Snippet:

<script>

function gup( name ) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if(results == null)
        return null;
    else
        return results[1];
}

var frank_param1 = gup('Listingid');
$("#display12").append(frank_param1);
console.log(frank_param1);

$.ajax({
    type: "POST",
    url: "list.php",
    data: {"data": frank_param1},
    dataType:'json',
    success: function(data) {
        for(var i = 0; i < data.length; i++) {
            console.log(data);

            var html1 = "<div class=two> Listingid : " + data[i].Listingid + "User id : " + data[i].userid + "</div>" +
                "<a id=newListing class=btn btn-success btn-lg1 type=button style=width:140px; href=#noteform data-toggle=modal>" + "submit " + "</a>";

            $('#display12').append(html1);
        }
    }
});

</script>

Answer №1

To access the data stored in the success-callback's data-variable, you'll need to decode the JSON format that was used in PHP by using jQuery.parseJSON(). This will allow you to retrieve and display the information as intended. If you're looking to pass this data to another script, simply include it in a new ajax request within the success-callback without the need for decoding.

Once the JSON string is decoded, it will populate the $output array in JavaScript, enabling you to iterate through its contents seamlessly.

In terms of PHP syntax, while I'm not certain if $output[] = $row actually appends rows to the array, I would suggest utilizing the array_push() function for clarity and consistency.

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

HTML Canvas resizing challenge

My goal is to resize the canvas to fit inside its parent div within a Bootstrap grid, but I'm running into an issue where the canvas keeps expanding to 2000px x 2000px. Despite successfully resizing based on console.log outputs showing the same dimens ...

The result returned by Array.isArray is false

As someone diving into the world of javascript and currently unpacking destructuring, I stumbled upon a puzzling snippet that sparked a question in my mind. After some editing, my code was identified as an array by the console, which left me scratching my ...

What is the correct way to route requests to /api/ressource in a production environment?

In my development environment, I have set up a webpack dev configuration where my front-end server runs on port 8080 and my backend server runs on port 3000. Here is how I configured my webpack dev server: proxy: { '/api': 'http://localh ...

Customize your select element's background using jQuery when the content changes

Here is a select element with different options to choose from: <select class="state"> <option value="1">Done</option> <option value="2">Closed</option> <option value="2">Open</option> <option v ...

What is the best way to adjust the timing between slide transitions?

I am utilizing the Slick slider for my website. I am looking to adjust the delay before switching slides, how can I achieve this? Below is the JavaScript code for the slider: $(".intro__slider").slick({ infinite: true, dots: true, dotsClass ...

The web application powered by Google Apps Script is transforming entered data values into an array

My website has a form that sends data to a Google App Script for processing before returning a status to the webpage. Strangely, the submitted data is being converted into an array with just the value for each property. For example: { fname: "danny& ...

Tips for seamlessly incorporating WalletConnect into your decentralized app with the help of web3-react

I have been working on integrating WalletConnect into my project by referring to the documentation provided by web3-react. The configuration settings I am using for the connector are as follows: import { WalletConnectConnector } from '@web3-react/wal ...

Encountered an issue while verifying req.params.id in an express.js route

Hi there, I'm reaching out for assistance with my first question on StackOverflow. As a newcomer to full-stack programming, I've encountered an issue while attempting to GET data from a JSON file via a GET Method on my local Node.js Express serve ...

Sinon threw an assertion error out of the blue

Just diving into using Sinon and facing a small hiccup. Let's say we have a module (named myModule.js) defined as follows: //myModule.js var _f2 = function() { console.log('_f2 enter'); return {prop1:'var1'}; }; var f1 = ...

Is it possible to add some color to the first table in the div

Is it possible to change the background color of the first table within this Div tag that contains three tables? <div id="WebPartWPQ2" width="100%" HasPers="false" allowExport="false"> <table width="100%" border="0" cellSpacing="0" cellPadding= ...

javascript function to divide text into separate elements

Currently, I am facing an issue with my front end where a string of words (item names) fetched from the database is being displayed in a loop without any separation. The output appears as: Item name1Item name2 This problem arises due to passing the value ...

Utilize try-catch or async-await within useEffect when testing with Jest

I am currently setting up my initial unit tests using JEST. I've installed Jest Fetch Mock but unfortunately, I keep encountering an error stating "The promise rejected with reason FetchError". After doing some research, it seems like I may need to i ...

What are the reasons for the slower runtime of node.js compared to the Google Chrome console

It's interesting to note that both Chrome and node.js operate on the same V8 javascript engine. Here is my take on it: Chrome, despite running internal executions, also handles additional UI tasks which could potentially slow it down On the other ha ...

Exploring the functionality of the JavaScript Date constructor in relation to

Will using new Date('2015-01-01') provide me with the exact moment equivalent to 2015-01-01T00:00:00Z? ...

Discovering the way to retrieve background height following a window resize using jQuery

Is there a way to obtain the background height once the window has been resized? div { background-image: url(/images/somebackground.jpg); background-size: 100% 90%; background-repeat: no-repeat; width: 70%; background-size: contain; ...

I am facing an issue where this loop is terminating after finding just one match. How can I modify it to return

I am currently working with an array that compares two arrays and identifies matches. The issue is that it only identifies one match before completing the process. I would like it to identify all matches instead. Can anyone explain why this is happening? ...

html The selection in the dropdown menu is not showing the expected value

When using Firefox version 46.0.1, I encountered an issue with a select element that contains a value attribute being altered by Javascript code. Despite this change being confirmed in the browser inspector window with the select element showing a new valu ...

Converting nested JSON structures from one format to another using JavaScript

I have been attempting to convert an AVRO schema into an ElasticSearch index template. Both schemas are in JSON format with some specific considerations to keep in mind during the transformation process. I initially tried using recursion to extract all nes ...

Incorporating Javascript into a Django template: best practices

Using Django templates, I am interested in embedding a Bokeh plot by using Json output. The Json output is already prepared for querying the database. The plot needs to be displayed in a div with a specific ID. According to the documentation, the followi ...

Having difficulty positioning the Divider correctly among Grid items

I am trying to add a Divider between each item in my Grid. The desired output should resemble this:- Col 1 | Col 2 | Col 3 However, I am facing difficulties as the Divider is not visible and the items are displayed vertically. import "./style ...