Pass AJAX variable to PHP functions Wordpress plugin

admin2025-06-05  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.

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.

Share Improve this question asked Dec 29, 2018 at 15:28 ColinColin 1356 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1749058997a316004.html

最新回复(0)