Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass variable from ajax to php

i have 1 php file name index.php. in that 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 can see that ajax already post 'action=value' but in php, $_POST['action'] is empty. anyone can help me, what's wrong with my code? thank you

like image 960
Yessie Setiawan Avatar asked Mar 19 '13 09:03

Yessie Setiawan


2 Answers

set this as json object:

data: {action: elem}

and don't mix jquery with pure js.

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

and as friend above say. There can be situation where js is trying to get value property before whole page is loaded. You should do everything in document ready block.

You can also do:

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

You will be sure then that you have the newest data on the form!

like image 22
imclickingmaniac Avatar answered Sep 27 '22 19:09

imclickingmaniac


Try using data like this

data: {action: elem},

For Example

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

printr whole $_REQUEST and check if your are getting action

like image 99
Subodh Ghulaxe Avatar answered Sep 27 '22 20:09

Subodh Ghulaxe