Kay
Kay

Reputation: 87

how to trigger jQuery $.post

I want to send data to a php file when I click a link

<a href="test.html" onclick ="post()">click me</a>

I have in an external JS file

function post(){
   $.post("myPhp.php", { name: "John" });
}

but when I check my PHP file, nothing gets posted.

$_POST['name'] is undefined.

What am I doing wrong? Thanks for your help.

Upvotes: 0

Views: 2120

Answers (5)

rajesh kakawat
rajesh kakawat

Reputation: 10896

try something like this,Reason your code was not working because before your ajax request is submited ,your page get redirected

   <a href="test.html" onclick ="return post()">click me</a>

JAVASCRIPT CODE

function post(){
   $.post("myPhp.php", { name: "John" });
   return false;
}

EDITED CODE

To redirect page use async

    function post(){
       $.ajax({url:"myPhp.php", 
              data: {name: "John"},
              type:'post',
              async: false,
              success: function(data){
                return true;    
              },
         });
    }

Upvotes: 3

Manwal
Manwal

Reputation: 23816

I think its redirected to the corresponding page before your ajax is completed.So try to stop that redirection with following code like:

<a href="javscript:void(0)" onclick ="post()">click me</a>

function post(){
   $.post("myPhp.php", { name: "John" },function(){
    window.location.href('test.html');
    });
}

Upvotes: 1

Satheesh
Satheesh

Reputation: 417

I was in the same problem you had. If you are using jquery.redirect.min.js as your jquery plugin, You can use as below. It gives you POST method.

   $().redirect("myPhp.php", { name: "John" });

Works fine for me.

Upvotes: 0

N20084753
N20084753

Reputation: 2170

Think the error is with the name ... it should be some string.

var name = 'name';

or 

data: {'name' : 'john'}

Hope this helps. Also try adding callbacks to check if your post data is sent successfully.

Upvotes: 0

Ankush Jain
Ankush Jain

Reputation: 1527

try the follwing

function post(){
   $.ajax({url:"myPhp.php", 
          data: {name: "John"},
          type:'post',
          success: funcation(data){},
          });
}

or find a quick overview of $.post here and then use it properly http://api.jquery.com/jQuery.post/

Upvotes: -1

Related Questions