Dynamic data retrieval with the power of JavaScript and AJAX

When attempting to send data using AJAX in PHP, I encountered an issue with my jQuery click function on a button that sends data only when the quantity is greater than 1. The error arises because PHP does not recognize the variables 'name' and 'nb'.

Below is my JQUERY/AJAX code:

$('.btn-circle').on('click', function(){
    var name = $('.quantite').attr('name');
    var nb = $('.quantite').text();
});

$('#form_top_ten').submit(function() {
    if(nb>=1){
        $.ajax({
            type: "POST",
            url: "handle_form/commande.php",
            data: {nb:nb,name:name}
        });
    }
    return false;
});

And here is the corresponding PHP code:

<?php
    session_start();
    require_once '../includes/config.inc.php';

    $id_user = $_SESSION['id_user'];
    $quantite = $_POST['nb'];
    $article = $_POST['name'];

    if(isset($quantite)){
        $req = $connection->prepare('INSERT INTO commande_articles(id_user,quantite,article) VALUES(:id_user,:quantite,:article)');
        $req->execute(array(
            'quantite' => $quantite,
            'article' => $article,
            'id_user' => $id_user
            ));
    }   
    else {
        echo('erreur');
    }
?>

Answer №1

To establish the variables at a broader scope, consider this approach:

let username, quantity;
$('.btn-circle').on('click', function()
{
     username = $('.quantite').attr('name');
     quantity = $('.quantite').text();
});

Answer №2

When working with javascript, it's important to remember that variables have function scope. This means that your variable names are contained within an anonymous function and are not accessible outside of it. To make these variables global, simply remove the "var" keyword from their declarations. This will broaden the scope of the variables and allow your code to function properly.

Another, more organized approach would be to declare the variables outside of the anonymous function and then reference them within it. By doing this, you can have better control over the scope of the variables (as mentioned in Siamak's answer above).

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

Creating an empty input field with a predetermined default output in ReactJS

My current challenge involves navigating form data between various components in a React application. I am looking to pass data from child components to parent components and vice versa, creating a seamless flow of information. The key requirement is to ha ...

Does the built-in waiting mechanism in Protractor automatically handle promises?

While browsing through Stack Overflow, I stumbled upon this response in a discussion about Protractor tests and asynchronous solutions: 'AFAIK expect waits internally for the related promises.' I have tried looking through the official Protract ...

Are you experiencing problems with JSON formatting?

Currently, I am facing an issue with populating an HTML table using JSON data. The problem arises when I try to populate the table with the JSON data that was provided to me. After careful examination, I suspect that the issue might lie in the formatting o ...

Closing the JQuery login popup form by clicking on the submit button

I have successfully created a popup login form using jQuery. However, I am facing an issue where, upon clicking the submit button, the popup closes and displays an error message stating "wrong username and password". Ideally, I would like the popup form ...

Save a newly uploaded image to Github utilizing NodeJS and the Github API

Struggling to upload an image to my Github repo using NodeJS and Github API has been a challenge for me. I have managed to create the SHA, Commit Tree, and all necessary steps, but the final hurdle is passing the image to the API and saving it as an actual ...

Pressing the non-responsive button automatically chooses the following item

This example demonstrates how to create a disabled button: import { Grid, IconButton } from "@material-ui/core"; import ArrowBackIosIcon from "@material-ui/icons/ArrowBackIos"; export default function App() { const handleClick = (e) ...

Sending response from controller to AJAX jQuery

I am working with ASP.net MVC and I am receiving an "Error" from my JavaScript code below: Here is the AJAX jQuery code snippet: $(document).ready(function () { var dataId; $(".item2 .small-img").click(function () { dataId = $ ...

Tips for avoiding Netlify's error treatment of warnings due to process.env.CI being set to true

Recently, I encountered an issue with deploying new projects on Netlify. After reviewing the logs, I noticed a message that had never appeared during previous successful deployments: The build failed while treating warnings as errors due to process.env.CI ...

I have received a JSON multi-line string after entering information in a textarea

I've been working on a small social network project where users can create and share posts. However, I encountered an issue with formatting when storing and displaying the posts. When a user enters text with line breaks in the post creation form, it ...

What is the process for retrieving data from a mysql database and presenting it to the user using PHP?

Being relatively new to PHP, I have successfully created a login/registration area. However, I am facing an issue where the automated email sent after a user registers does not include the username. How can I retrieve this information from my MySQL databas ...

I am looking to save the session value into the search box of the appTables application by utilizing jQuery

Is there a way to save the session value in the search box of appTables by using jQuery? <?php $session = \Config\Services::session(); ?> <script type="text/javascript"> $(document).ready(function () { var searc ...

Ensure that any requests to www.domain.com are consistently redirected to domain.com

My website is experiencing an unexpected redirect issue where it keeps directing from www.mydomain.com to mydomain.com. Despite being a Wordpress Multi User installation, there is nothing in the .htaccess file that would trigger such redirection. I have t ...

The start "NaN" is not valid for the timeline in vis.js

Whenever I attempt to make a call, an error message pops up saying Error: Invalid start "NaN". I've looked everywhere online for a solution with no success. Below are the timeline options: timeline: { stack: true, start: new Date(), end: ...

The function .css() in jQuery is malfunctioning

This task should be a piece of cake... All I want is to hide the buttons when a user is logged in and display the log out button instead. jQuery().ready(function($) { if ($("body").hasClass("logged-in")) { $(".logged-out-button").css("display", " ...

Using the Upload feature in ReactJS

I have been searching high and low for assistance in creating a component within React that can handle file uploads to a specific endpoint I have established. I have experimented with various options, including trying to integrate filedropjs. However, I u ...

Error in PHP email header causing sending issue

I am attempting to send an HTML email through PHP. Here is the code I have written: $to = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="760213050236021305025815191b">[email protected]</a>"; $from = "$senderEmai ...

When using v-for to render components and <selection>, is there a way to customize it for just one specific instance of the component?

How can I modify the selection in each instance separately when rendering elements of an array obtained from the backend using v-for? Currently, changing one selection affects all instances due to the v-model. Is there a way to target only one selection ...

Differences between JavaScript's window.onload and body.onload functionsWhen

My inquiry is similar yet slightly distinct from the one queried here: window.onload vs <body onload=""/> The comparison in that prior query was between utilizing window.onload and inline js. My question pertains to the disparity between ...

Extract distinct values along with their respective counts from an array containing objects

Upon receiving a JSON request containing an array of objects with two properties, the task at hand is to extract the unique values along with their respective quantities. The following JSON data is being sent through Postman: [ {"name": "First value" ...

Update user login status in database following a forced browser closure or expiration of session

I have a user login data in MySQL, where users are only allowed to login once per session. The logout button works fine, but if the user closes the browser // user_table in MySQL user_id user_username user_password is_login 1 ...