0

I wrote a plugin in wordpress. It has some .js files and .php files and I receive data from db by calling ajax method in jquery. when I use wp_enqueue_script and add them to the wordpress, it works fine. but my question is how to use wp_ajax method instead raw ajax call. here is my code:

in my.js file:

$(document).ready(function(){
$('#submit').on('click', function(){
    var name = $('input[name=name]').val();
    var price = $('input[name=price]').val();
    var goods = $('input[name=goods]').val();
    var date = $('input[name=delivery]').val();
    if( name.length > 1 && price.length >1 && goods.length > 1 && date.length >1){
        var obj = {
            name: name,
            price: price,
            goods: goods,
            date: date
        };
        var btn=$(this).button('loading');
        $.ajax({
            url: "service.php",
            method: "POST",
            data: obj,
            dataType:'json',
            success: function(e){
               $('#alt-div').html('<div id="alert" class="alert alert-info alert-dismissable"><a  href="#" class="close" data-dismiss="alert" aria-label="close">×</a>'+e.Comment+'</div>');
            },
            error: function(){
                alert('error');
            }
        })
    }
});
});

in service.php file:

 $name = $_POST['name'];
 $goods = $_POST['goods'];
 $date = $_POST['date'];
 $price = $_POST['price'];
 $tmp = explode('/', $date);
 $jy = $tmp[0];
 $jm = $tmp[1];
 $jd = $tmp[2];

 $query = "INSERT INTO products (name, goods, price, date) VALUES ('$name', 
 '$goods', '$price', '$time')";
 results = mysql_query($query);
 $inserted_id= mysql_insert_id();
 if ($results > 0)
   echo   json_encode ([
    'status'=>1,
    'Comment'=>"ok"]);
Steven Lury
  • 47
  • 2
  • 9
  • check this https://stackoverflow.com/questions/43557755/how-to-call-ajax-in-wordpress – Vel Aug 12 '17 at 05:17

1 Answers1

0

First its not a correct method to send ajax request on php files. Doing in this way, many important functions are not executed and it can lead to a code prone to sql injections and other threats.

Correct way to sending ajax in wordpress is on wp-admin/admin-ajax.php

just point your ajax call to admin_url("admin-ajax.php?action=my_action");

$.ajax({
        url: '<?php echo admin_url("admin-ajax.php?action=my_action"); ?>',
        method: "POST",
        data: obj,
        dataType:'json',
        success: function(e){
           $('#alt-div').html('<div id="alert" class="alert alert-info alert-dismissable"><a  href="#" class="close" data-dismiss="alert" aria-label="close">×</a>'+e.Comment+'</div>');
        },
        error: function(){
            alert('error');
        }
    })

Remember to check your action parameter in ajax call. It will be identification to function you want to execute for this ajax call. Now you can put below lines anywhere in your plugin or template functions.php.

add_action("wp_ajax_my_action", "my_action_function");
add_action("wp_ajax_nopriv_my_action", "my_action_function");

function my_action_function (){
    //your code
}

Now whenever your ajax call is executed. it will go to wp-admin/admin-ajax.php and this function will be executed. Here you can process your post request.

You can refer to this article for more help. https://www.smashingmagazine.com/2011/10/how-to-use-ajax-in-wordpress/

hanish singla
  • 782
  • 8
  • 21
  • all scripts file are in my js folder. So their type are `.js`. how to include `php` tag inside them – Steven Lury Aug 12 '17 at 05:38
  • Generally `ajax_url` is available already. you can try to `console.log(ajax_url)` or `alert(ajax_url)` to check. . if its not available then you can try `wp_localize_script` ... https://gist.github.com/nickpelton/11146942 – hanish singla Aug 12 '17 at 06:11
  • I can't understand what you mean. how to send ajax_url to `my.js`. when I wrote `console.log(ajax_url)` nothing has been shown – Steven Lury Aug 12 '17 at 06:53
  • I meant `ajax_url` is already in JavaScript. you can use just like `$.ajax({ url: ajax_url, method: "POST", data: obj, dataType:'json', success: function(e){ } })` – hanish singla Aug 12 '17 at 07:06
  • I wrote like this in `my.js`: url: ajaxurl+'?action=fn_pg_show', and then in main plugin file add function `fn_pg_show`. is it ok? – Steven Lury Aug 12 '17 at 07:21
  • yes. . but you need to add action as well. . add_action("wp_ajax_fn_pg_show", "fn_pg_show"); add_action("wp_ajax_nopriv_fn_pg_show", "fn_pg_show"); – hanish singla Aug 12 '17 at 07:48
  • I did it but any response. – Steven Lury Aug 12 '17 at 08:50
  • you can try to set `obj.action = "fn_pg_show";` then. . or may be update your new code in your question. . also try to check if your function and action is being executed. put a `die('here');` there and see if control reaches there. may be you have put your function and action in some file, which does not get loaded. – hanish singla Aug 12 '17 at 09:40