What is the best way to retrieve data using AJAX jQuery after clicking on text?

I recently used this code to send and retrieve results.

<script type="text/javascript"> 
    $(document).ready(function() {
        $('.special').click(function(){
            var info = $(this).attr("rel");
            //$(this).html(sku);
            $.ajax({
                 type: "POST",
                 url:"../ajax/addSpecialFlag.php", 
                 async: false,
                 data: {info:info},
                success:function(result){
                    $(this).html(result);
                }});       
        }); 
    });    
</script>

<b style="cursor: pointer" class="special"  rel="<?=$v['number']."/*".$v['vid']; ?>">Special</b>

addSpecialFlag.php

<?php
echo $_POST['info'];
?>

This section of the code is intended to return "Info" in "<-b class='special' ->" but it's not returning any result. Can you identify the issue here? Thank you for your help in advance!

Answer №1

The issue at hand could be that $(this) within the success callback function may not reference the same element as outside of it. To address this, try modifying your code as shown below:

$(document).ready(function() {
    $('.special').click(function(){
        var $this = $(this);
        var info = $this.attr("rel");
        $.ajax({
             type: "POST",
             url:"../ajax/addSpecialFlag.php", 
             async: false,
             data: {info:info},
             success:function(result){
                $this.html(result);
            }});       
    }); 
});    

Answer №2

<b>? Are you upset? Please use <strong>.

I've organized your code so that the parentheses match their line indents and adjusted your success handler. The problem was that the success handler was in a different scope than the click function scope, so you needed to reference it in a different way by assigning it to another variable.

$(document).ready(function () {
    $('.special').click(function () {
        var info = $(this).attr("rel");
        var _this = $(this);
        //$(this).html(sku);
        $.ajax({
            type: "POST",
            url: "../ajax/addSpecialFlag.php",
            async: false,
            data: {
                info: info
            },
            success: function (result) {
                _this.html(result);
            }
        });
    });
});

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

What is the best way to send a POST request with parameters to a PHP backend using AJAX?

This is an updated version of a previous question that was identified as a duplicate (How can I send an AJAX POST request to PHP with parameters?) I am currently sending an AJAX request to a PHP backend. Here are the JavaScript functions used to make and ...

Dynamic dropdown in Bootstrap automatically closes upon selecting an item from the list

I am encountering an issue with a dynamically created dropdown on a page. The HTML code for the dropdown is injected into the page after an AJAX call. While I can open the dropdown by clicking on a special anchor, I am unable to interact with any elements ...

Using the JQuery template with $.get function does not produce the desired result

Working on populating a table using a Jquery Template can be tricky. One challenge is incorporating a json file via an ajax call for the population process. $(document).ready(function() { var clientData; $.get("/webpro/webcad/lngetusuario", funct ...

Is there a way to dynamically set the active panel of a JQuery Accordion when making a call?

Currently, I am faced with a scenario where I need to implement a greybox popup window using jQuery Accordion from the main page via links. I am curious to know if it is doable to specify a default active panel for the accordion when calling it. Below is ...

What is the best way to apply a class to a jQuery element only if a specific condition is met, and then remove it if the condition is no longer

Is there a more concise method to accomplish the same task? const selectAllCheckbox = $("input.select_all"); const isChecked = selectAllCheckbox.prop("checked"); isChecked ? selectAllCheckbox.parent().addClass("selected") : selectAllCheckbox.parent().r ...

What steps can be taken to implement a code generation feature on our website?

I need to provide the HTML code of my order form to third parties. After they register and pay, they should be able to copy and paste the HTML code from my site onto their own site. The date will then be saved on my site with a reference to the reseller. ...

Encountering an issue with the PHP login page

Currently, I am working through a tutorial at mybringback. In particular, I am examining the code in register.php v.02 and have set up a Wamp server. However, when attempting to run the code, I encounter an error. I have made adjustments to $cfg['Ser ...

Using the power of AJAX, retrieve data from a PHP script and showcase the response within

Within my HTML file, I have implemented a feature that allows users to input a value. To validate this input, I created a PHP script that checks if the entered value exists in the database. The script returns the following JSON response: {"active":true} ...

Extracting a token from a JSON response using Python

I'm currently delving into Python and exploring the API for MediaFire to automate some basic tasks. However, I've hit a roadblock after sending a POST request to obtain the Session Token. Extracting the token from the response is where I'm f ...

What is causing the jqplot meter gauge problem with the error message "c.jqplot is undefined

I'm encountering an issue and seeking some guidance. I am relatively new to this, so navigating the problem proves challenging. I'm attempting to utilize jqplot's meter gauge according to the documentation, but it doesn't seem to be fun ...

Prevent rapid event triggers with a jQuery slider

I am currently working with an event function in JavaScript that involves a slider and a tooltip element. Here is the code snippet: //Hide the Tooltip initially tooltip.hide(); //Initialize the Slider slider.slider({ ...

The event listener $(window).on('popstate') does not function properly in Internet Explorer

$window 'popstate' event is not functioning properly in IE when using the browser back button. Here is the code snippet used to remove certain modal classes when navigating back. $(window).on('popstate', function(event) { event.pre ...

Having difficulty naming the request while using ajax to send data to a local server

I have set up an AJAX request to be sent to my PHP server: var xml = new XMLHttpRequest(); xml.open("POST", "request.php", true); xml.setRequestHeader('query','test'); xml.send(); Upon receiving the AJAX data in PHP, I am facing some ...

Is it feasible to make Twitter's Typeahead plugin have an initial slide down or fade in effect?

Does anyone have an easy way to make the dropdown from Twitter's typeahead jQuery plugin initially slide down or fade in? I'm trying to animate the size of the dropdown menu when it adjusts, but even a simple fade or slide in would be fine. I pre ...

"Unlocking the power of event handling with jQuery plugins: A beginner's

Hey there, I'm new to plugin development and diving in head first. The documentation has left me a bit confused, so I'm opting for a trial-and-error approach... My current project involves creating a basic form validation plugin. (function($){ ...

PHP - Sending a JSON response from a class

I am working with a class: class A { protected $name; public function getName() { return $this->name . " example"; } public function setName($name) { $this->name = $name; } } When I run the following code: $r ...

What causes the DOM's appendChild() to trigger on('load', ...) while jQuery's append() does not fire?

I have two snippets of code that I am working with: $(document).ready(function() { document.head.appendChild( $('<script />').attr('src', 'source.js').on('load', function() { ... ...

Displayed hours may not be complete on the Dhtmlx timeline

I'm experiencing an issue with the cell timeline feature in DHTMLX. I want to ensure that the cell size is consistent and displays the full hour, or horizontally scrolls if the hours extend beyond the device screen. Despite my efforts to consult the ...

Best event for Angular directive to bind on image onload

I'm currently working on incorporating this particular jQuery plugin into my Ionic application. Although I have a good grasp of creating an Angular directive to encapsulate the plugin, I am encountering difficulties in successfully implementing it. B ...

Looking for assistance with an Angular2 post request?

I'm having an issue with a post request to obtain a token granting access to another access token. Each time I attempt to make the post request, I encounter an error stating that the access_token property is trying to read something undefined. It seem ...