简体   繁体   中英

Passing JavaScript variables to anonymous function

I am using jQuery's Ajax method to asynchronously send a POST request with the user "name" and "comment" values entered in a form with IDs of name and comment respectively and the comment.php page returns an HTML message (success or error) that gets shown in the #info div.

So far, everything works perfectly and the comment gets added to the database and is shown at page refresh in the #comments table. Now I just want to add the user's name and comment directly into the comments table but I have a problem, I'm not able to access the name and comment variables from inside the anonymous function that gets called inside the .done() method.

Here's my code:

var name = $('#name').val();
var comment = $('#comment').val();

var data = "name="+name+"&comment="+comment;

$.ajax(
        {
            type: "POST",
            url: "comment.php",
            data: data // Provided form data
        }
    ).done
    (
        function(data) // Returned data from URL endpoint
        {
            // Show returned message
            $('#info').html(data);

            var newRowContent = '<tr> <td>'+name+'</td> <td>'+comment+'</td> </tr>';

            $(newRowContent).appendTo( $('#comments') );
        }
    );

Apparently, simply adding name and comment to the anonymous function's arguments doesn't work, and the variables are declared outside the scope, so I'm not sure why they result in empty strings when printed on the table. I'd appreciate the help and an explanation of what I'm not getting here.

UPDATE: Here is an example JSFiddle of what I'm trying to do and it works here.

UPDATE: I think I've identified the problem, the ID selectors I'm using to assign a value from the field's value doesn't work for some reason, which leaves the variables as empty strings and that's also what gets stored in the database.

UPDATE: I finally discovered the reason, the form I'm using is wrapped in a div block with display; none display; none so to only show the form once the user clicks a "show comments" button, and that works. The problem is the jQuery value selector $('').val(); treats "hidden" inputs differently and I've only been able to find answers dated back to 2009-2011 that work for older versions of jQuery and not this one.

I hope someone could answer me with how I can select by ID the value of an input that's inside a div with style of display: none when it gets displayed and filled by the user.

It think this is maybe caused by an "out of scope behavior" . You can try to return the data(name,comment) submitted from your URL endpoint and then get those values. Something like:

 function(data) // Returned data from URL endpoint
        {
            // First you need to parse the json data
            data = JSON.parse(data);
            // Show returned message
            $('#info').html(data['info']);

            // Then you get the data returned
            var newRowContent = '<tr> <td>'+ data['name'] +'</td> <td>'+ data['comment'] +'</td> </tr>';

            $(newRowContent).appendTo( $('#comments') );
        }

Off course, this assuming that you're returning json data. Hope it helps! ;)

I have fixed the issue, as stated in my 3rd update, the problem was the inputs were in a div with display: none that makes it hidden at page load and only shown later when a button click shows it. The problem lies in how it's shown.

My old approach was copying the HTML enclosed in a div with display: none and id #commentForm to an empty div using the append() method, which caused the input IDs to be present 2 times in the page and thus the $() selector return an empty value.

What I did is change the jQuery to just "unhide" the HTML by removing the style="display: none" as such:

$('#commentForm').removeAttr('style');

That, alone, made the input values to be successfully retrieved with the AJAX code present in my question above. I hope this helps someone who might encounter a similar situation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM