Rajan
Rajan

Reputation: 2425

Send POST Data using AJAX JQuery

I want to send the selected item from Bootstrap dropdown in POST to my controller, but somehow it is not being sent.

In my dropdown I fetch records from the database in <li></li> tag, like this:

 <li class="dropdown">

      <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Your Sites <span class="caret"></span></a>
      <ul class="dropdown-menu">
        <li ><a href="#"><?php

    foreach($sites as $site)
    {

    echo "<li class='specialLink' id='$site->site_key'>".$site->site_key."</li>";
    }?></a></li>

      </ul>
    </li>     

This is my script to send POST data:

<script type="text/javascript">

$( ".specialLink" ).click(function() {
    var value = this.id; //get value for throw to controller
    alert(value);  

    $("#specialLink").submit(function(){
        $.ajax({
            type: "POST", //send with post
            url: "<?php echo site_url('customer/dashboard') ?>",  
            data: "value=" + value,
        });
    });
});

</script>

But I don't send anything in POST data at my controller, nor do I get any error message in the console.

Upvotes: 0

Views: 1351

Answers (2)

Hamid hp
Hamid hp

Reputation: 9

you can use this code instead to send your data to php file:

 <a href="#" onclick="postExample(); return false;">Your Link here</a>

     function postExample() {
     $.post('url', {"postfield1":"val1"}, function(resp) {
         //Do something with the AJAX response
     });
 }

or

 <a href="#" onclick="$.post('url', {"postfield1":"val1"},; return false;">Your Link here</a>

Upvotes: 0

Sohan Jain
Sohan Jain

Reputation: 2377

I think you're not using submit correctly. The submit function binds an event handler to the submit javascript event. Read more at https://api.jquery.com/submit/.

You just want to do the ajax request when $(.specialLink) is clicked, so try:

 $( ".specialLink" ).click(function() {
    var value = this.id; //get value for throw to controller
    $.ajax({
      type: "POST", //send with post
      url: "<?php echo site_url('customer/dashboard') ?>",  
      data: "value=" + value, 
    });
});

Upvotes: 1

Related Questions