Linz Darlington
Linz Darlington

Reputation: 671

Passing a variable into a JavaScript Function

I have written a Javascript Function

jQuery(document).ready( function newbie($) {

    //var email = 'emailaddress'
    var data = {
        action: 'test_response',
        post_var: email
    };
    // the_ajax_script.ajaxurl is a variable that will contain the url to the ajax processing file
    $.post(the_ajax_script.ajaxurl, data, function(response) {
        alert(response);
    });
    return false;
});

Which I will call using

newbie();

But I want to pass in a variable (the email address) when I call the function but I am not sure how to do this. That $ sign seems to get in my way! Any thoughts much appreciated.

Upvotes: 0

Views: 56

Answers (3)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

jQuery(document).ready(function(){
   var email = 'emailaddress';
   newbie(email);
});


function newbie(email) {
    var data = {
        action: 'test_response',
        post_var: email
    };
    // the_ajax_script.ajaxurl is a variable that will contain the url to the ajax processing file
    $.post(the_ajax_script.ajaxurl, data, function(response) {
        alert(response);
    });
    return false;
}

OR

 jQuery(document).ready(function(){
        var newbie = function(email) {
           var data = {
               action: 'test_response',
               post_var: email
           };
           // the_ajax_script.ajaxurl is a variable that will contain the url to the ajax processing file
           $.post(the_ajax_script.ajaxurl, data, function(response) {
               alert(response);
           });
           return false;
      }

     var email = 'emailaddress';
     newbie(email);
  });

Upvotes: 1

user2624242
user2624242

Reputation: 358

jQuery(document).ready( function newbie($, email) {

//var email = 'emailaddress'
var data = {
    action: 'test_response',
    post_var: email
};
// the_ajax_script.ajaxurl is a variable that will contain the url to the ajax processing file
$.post(the_ajax_script.ajaxurl, data, function(response) {
    alert(response);
});
return false;

});

you simply call the function by passing the values

Upvotes: 0

Shadowfool
Shadowfool

Reputation: 1036

Functions in javascript take 'arguments'. You can pass in as many arguments you want and define their name space in the function declaration. ie

function foo(bar,baz,etc){
   console.log(bar,baz,etc);
}
foo(1,2,3)
 //logs out 1 2 3

Sometimes you don't always know what's going to be passed in or how many arguments there are going to be, in this case inside of the function declaration we can use the 'arguments' object to pick out certain arguments passed into the function.

function foo(){
   console.log(arguments);
}
foo(1,2,3)
 //logs out an array object that looks like this [1,2,3]

Upvotes: 0

Related Questions