user3227899 user3227899 - 3 months ago 7
Ajax Question

Define function's variable to another function

I have many buttons and its values is contain usernames (jason,chan,brad etc..) and user click the button and this button appended to specific div. Example:

<input type="button" onClick="nano();" id="name1" class="names" name="jason" value="jason" />


and it is converted to

<div id="name_selected"><input type="button" id="name1" class="added_name" name="jason" value="jason" /></div>


when user clicks button then nano function is running

function nano(){
$("#name1").click(function(){
$(this).appendTo("div#name_selected").removeClass("names");
$(this).addClass("added_name");
var name_value=$(this).attr("value");

});
}


and real question is i want to get value of selected button and save to database using ajax and how do i define name_value variable to function ajaxSubmit()?

Uncaught ReferenceError: name_value is not defined


error occur

function ajaxSubmit(){
$.ajax({
type:"POST",
url:"z.php",
cache:false,
data:name_value,
success:function(data) {
window.location.href="show.php";
}
});

}

Answer

First of all declare a function that is going to be called on button click:

/**
*   Function that performs various operations on button click
*   @param btn {jQuery object}: The button that triggered the click event
*/
function nano(btn) {   
   // Do your stuff here...       
   btn.appendTo("div#name_selected")
      .removeClass("names")
      .addClass("added_name");

   // Get the value attribute
   var name_value = btn.attr("value");

   // Make ajax call
   if (name_value) {
      ajaxSubmit(name_value);
   }       
}

Declare the function that is going to perform the ajax call:

function ajaxSubmit(val) {
    // Check if 'val' is not undefined
    if (val) {
       $.ajax({
          type:"POST",
          url:"z.php",
          cache:false,
          data: { val: val },
          success:function(data) {
             window.location.href="show.php";
          },
          error:function() {
             // error handling here...
          }
       });
    }
}

Add an event listener on the desired elements:

$(document).on('click', '.button-class', function() {
   // Call nano passing the clicked button as parameter
   // this --> the javascript object that triggered the click event
   // $(this) --> the jQuery object of 'this' 
   nano($(this));
});

IMPORTANT:

Remove onClick attributes from all your buttons! (Don't use it, instead use the on() function to add event listeners)