ajax error in wordpress plugin

I’m writing a plugin for wordpress. The plugin has a widget which contains a button and textbox.
the button has onclick event.
when that event occurs i need to post the textbox data to php file using ajax
the ajax code doesn’t return an error, but php doesn’t get the data.

here’s my JS file

Read More
 function F()
    {
        var x=document.getElementById('last').value;


        jQuery.ajax({
            type: "POST",
            url: 'http://localhost/wordpress/wp-content/plugins/Hovo/Scripts/vote.php',         
            data: x,
            success: function() {
                alert('Sends successfully');
            },
            error: function(jqXHR, textStatus, errorThrown) {
            alert(errorThrown);
            }
        });
    }

here’s my php file

<?php
    if(isset($_POST["anun"]))
    {
        echo $_POST['anun'];
    }
    else
    {
        echo "error";
    }
?>

please help to fix this problem

Related posts

Leave a Reply

1 comment

  1. In your PHP $_POST is expecting a key / value pair and you are sending only a value in your ajax. Where ‘anun‘ would be the key and whatever is stored in x is the value.

    Since you are not sending the key ‘anun‘ to $_POST it cannot return the value stored in x because your if condition fails.

    You should be able to correct this by changing your ajax call slightly:

    function F() {
    
        var x = document.getElementById('last').value;
    
        jQuery.ajax({
            type: "POST",
            url: 'http://localhost/wordpress/wp-content/plugins/Hovo/Scripts/vote.php',         
            data: { anun: x },
            success: function() {
                alert('Sends successfully');
            },
            error: function(jqXHR, textStatus, errorThrown) {
            alert(errorThrown);
            }
        });
    }
    

    To be sure you are getting the correct value of x, try using console.log(x); just before your ajax call and check the browser console to see what it returns.

    If it does not return the correct value or simply returns nothing, try changing:

    var x = document.getElementById('last').value;
    

    To simply:

    x = jQuery('#last').val();