Pass variable from ajax to php

I have 1 php index.php file name. in this file I want to pass one variable from ajax to php.

var elem = document.getElementById("mydiv").value;
(function($)
{
    $(document).ready(function()
    {   
        $.ajax(
        {   
            type:"POST",
            url: window.location.href,
            data: 'action='+elem,
            beforeSend: function() {
                $('#cctv').hide();
            },
            complete: function() {
                $('#cctv').show();
            },
            success: function() {
                $('#cctv').show();
            }
        });
        var $container = $("body");
        $container.load('findAllPath.php',{'function': 'findAllPath'});
        var refreshId = setInterval(function()
        {
            $container.load('findAllPath.php',{'function': 'findAllPath'});
        }, 10000);
    });
})(jQuery); 

and my php

if (isset ($_POST['action']))
{   
    echo $_POST['action'];
}

in firebug, I see that ajax already sent 'action = value', but in php, $ _POST ['action'] is empty. can anyone help me what is wrong with my code? thank

+5
source share
4 answers

Try using data like this

data: {action: elem},

Example

$.ajax({
   type: "POST",
   url: "some.php",
   data: { name: "John", action: "save" }
   }).done(function( msg ) {
  alert( "Data Saved: " + msg );
});

printr all $ _REQUEST and check for action

+4
source

set this as a json object:

data: {action: elem}

and don't mix jquery with pure js.

var elem = $('#myDiv').val();

, . , js . .

:

data: {
action: $('#myDiv').val()
}

, !

+1

Look at it and find what you missed.

    $.ajax({
        type: "POST",
        url: "some.php",
        data: { action: elem}
        beforeSend: function() {
            $('#cctv').hide();
        },
        complete: function() {
            $('#cctv').show();
        },
        success: function() {
            $('#cctv').show();
        }
    });
    var $container = $("body");
    $container.load('findAllPath.php',{'function': 'findAllPath'});
    var refreshId = setInterval(function()
    {
        $container.load('findAllPath.php',{'function': 'findAllPath'});
    }, 10000);
});
+1
source
if (!empty($_POST['action']))
{   
echo $_POST['action'];
}

Try this code ...

0
source

All Articles