Sending two values from an HTML form using Ajax

Looking to transfer two values from my HTML code to the PHP code: one for 'up' or 'down', and the other for the post ID.

I have a system where users can vote on posts by clicking either 'up' or 'down' arrows next to the post ID.

<script>
    function vote(val)
    {
        var params = {"vote":val.id};
        $.ajax({
            data:  params,
            url:   'vote.php',
            type:  'post',
            success:  function (response) {

            }
        });
    }
</script>
<a id='up' class='fas fa-angle-up' onclick='vote(this);'></a>

vote.php

if(!empty($_POST['vote'])) {
    if ($_POST['vote']=='up')
    {
        // Need to somehow retrieve the second value, possibly using $_POST['id']
    }
    if ($_POST['vote']=='down')
    {
        // Need to somehow retrieve the second value, possibly using $_POST['id']
    }
}

Unsure of how to include the post ID as the 'id' attribute in the anchor tag is already used.

Answer №1

If you want to add voting functionality to your function, you can modify it to accept a parameter for up and down votes.

<script>
    function vote(voteType, element)
    {
        var params = {"vote": voteType, "id": element.id};
        $.ajax({
            data:  params,
            url:   'vote.php',
            type:  'post',
            success:  function (response) {

            }
        });
    }
</script>
<a id='up' class='fas fa-angle-up' onclick='vote("up",this);'></a>
<a id='down' class='fas fa-angle-down' onclick='vote("down",this);'></a>

Now in your PHP code, you can access the ID using $_POST['id'] and determine the type of vote with $_POST['vote'].

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

Methods for passing JavaScript variables to PHP

I have encountered this problem on Stack Overflow before, but I couldn't find a solution that worked for me. I am using Codeigniter and have a form where users can rate a product. What I need to achieve is to insert the user's rating into the dat ...

The issue with Angular-gettext is that it fails to update dynamically generated strings in the code

Whenever I try to set the language using the code gettextCatalog.setCurrentLanguage(langString);, it doesn't seem to affect my side-nav menu. My side menu has two possible states: expanded or collapsed, and I use ng-include to control its content base ...

Displaying a component after retrieving a value from AsyncStorage in a React Native application

I have developed a React Component that saves user settings in the AsyncStorage and retrieves them upon loading. The functionality of storing and retrieving data is working fine, but I am facing an issue where the component renders before the values are ...

The styles from the npm package are not being properly applied to the class

After creating my react npm package using webpack, I encountered an issue where the styles from the package were not being applied to classes when installed in my react project. I used style-loader in my webpack configuration, but kept getting errors sayin ...

Unraveling AngularJS: Mastering the Art of Interpolating Interpol

Trying to interpolate a string retrieved from the database, such as "Users({{users_count || 0}})", poses a problem. Using {{}} or ng-bind for interpolation does not work properly. The HTML code written is {{data.usersCount}}, but instead of ren ...

Is it detrimental to have lengthy jQuery chains?

After extensively utilizing jQuery for quite some time, I recently developed a slideshow plugin for my professional projects. Interestingly, without fully intending to, approximately 75% of the code was written in a single chain. Despite being meticulous ...

Add the onclick() functionality to a personalized Angular 4 directive

I'm facing an issue with accessing the style of a button in my directive. I want to add a margin-left property to the button using an onclick() function in the directive. However, it doesn't seem to be working. Strangely, setting the CSS from the ...

Creating dynamic dropdown menus using JSON files in jQuery mobile is a useful technique for enhancing user experience on

I am working with a massive table (8 MBytes) that I need to filter using a small JavaScript application. The process works as follows: Countries Regions Skills I want the user to select one country, one region, and multiple skills as filters. Based on ...

Preventing simultaneous ajax requests

Similar Question: How to stop a jquery.load() request? So I'm dealing with an autocomplete field that's sending an ajax request every time a key is pressed, causing significant slowdown. If you check out this link and log in with the details ...

Learn how to update image and text styles using Ajax in Ruby on Rails with the like button feature

I'm working on implementing a Like button in Rails using Ajax, similar to this example: Like button Ajax in Ruby on Rails The example above works perfectly, but I'm interested in incorporating images and iconic text (such as fontawesome) instead ...

"Although the ajax request was successful, the post data did not transfer to the other

i am working with a simple piece of code: var addUser = "simply"; $.ajax({ type: 'POST', url: 'userControl.php', data: {addUser: addUser}, success: function(response){ alert("success"); } }); on the page use ...

Incorporate a new item into an array within DynamoDB that does not currently

I am attempting to update an attribute called items, which is a list of strings. Is it possible to update (append) the attribute only if it does not already exist? Something like a combination of list_append and if_not_exists. var params = { ... Upda ...

JavaScript popup cannot be shown at this time

I'm encountering an issue with displaying popups using JavaScript. Currently, only the div with class "popup" is being shown. When a user takes action, both popup and popup2 should be displayed but for some reason, it's not working as expected. ...

JS: delay onClick function execution until a page refresh occurs

Currently, I am working on a WordPress site that involves a form submission process. Upon successful submission, a new post is created. After the user submits the form, I have implemented JavaScript to prompt them to share a tweet with dynamically prepopu ...

Creating a spacious text box for an enhanced Ajax search feature

I'm currently working on an AJAX application that allows users to input the name of a movie, and then loads results from the database through jquery using a PHP API. However, I'm facing a challenge in implementing a text box with the following re ...

Is there a way to incorporate the Indian rupee symbol into a Google chart?

I've been trying to incorporate the Indian Rupee symbol into a Google chart using the code below: var formatter = new google.visualization.NumberFormat({ prefix: '&#8377;' }); However, I'm encountering an issue where ...

Is there a way to identify when a radio button's value has changed without having to submit the form again?

Within this form, I have 2 radio buttons: <form action='' method='post' onsubmit='return checkForm(this, event)'> <input type = 'radio' name='allow' value='allow' checked>Allow ...

Controller experiencing peculiar AJAX response in CodeIgniter

I recently embarked on a Codeigniter project and now I'm faced with the task of making an AJAX call to a specific controller. Here is the scenario: - I have two dropdown menus: one for selecting counties and the other should populate with cities with ...

Removing data from the controller with JQUERY AJAX in a Spring MVC application

Could someone assist me with this issue? I am trying to implement ajax and sweetalert.js using the following repository: So far, everything is working well when I use onclick = "" to call my function. However, I need guidance on how to properly utilize th ...

How can you retrieve newly added DOM elements from a PartialView using Ajax.BeginForm?

Below is a snippet of code that loads a Partial View within a div element: <div id="_customerForm"> @Html.Partial("~/Views/Customer/_customerForm.cshtml", Model.customerForm) </div> The Partial View contains an Ajax Form as shown ...