0

I am creating a Wordpress plugin and using it to learn jQuery and AJAX. I have read many posts here on WPD and SE and on other sites but cannot get to grips with what I need to do (I am a real novice at this).

I currently have this as my JS

 jQuery(".my_button").click(function(){
        var sn = jQuery(this).val();
        alert(sn);
        jQuery.get(ajaxurl,{'action': 'getname'},
            function (msg) { jQuery(".result_area").html(msg);});

    });

This works fine and it alerts with the value from the button click, it then calls the PHP fuction fine and displays the result correctly in the div.

What I need to do is send the value of the variable sn to the php function and use that result in a custom database query. I think that I need to add something to this line of code jQuery.get(ajaxurl,{'action': 'getname'},

But after a couple of days trying various different bits of code I cannot get the variable to appear in the PHP function.

Should I use $atts in the PHP function to retrieve this or do it in some other way.

1

You can pass the var the same way the action is passed- add a comma and add it on:

jQuery.get( ajaxurl,{ 'action': 'getname', 'my_var': sn },

Then in your ajax php function, $_GET['my_var'] will contain that value.

  • That works perfectly, thank you for adding to my knowledge. I hope that this helps someone else. – Colin Dec 30 '18 at 8:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.