0

I'm having trouble getting ajax to work with jquery and codeigniter. I've followed multiple tutorials but nothing seems to work. I'm trying to implement an upvote button that sends post data using ajax to be inserted into a db. Any help is much appreciated.

The code from my view:

<pre>
<?php foreach($query->result() as $row): ?>
<div>
<form action="" method="post">
<input type="hidden" name="story_id" value=<?php echo $row->id; ?>>
<input type="submit" name="story_id" class="button" id="submit_btn" value=<?php echo      $row->id;?>>
</form>
</div>
<?php endforeach; ?>
</pre>

The jquery script I'm using:

<pre>
<script type="text/javascript">
$(document).ready(function(){
$(".button").click(function(){
    var form_data = {
        story_id: $(this).val()
    };
    $.ajax({
        url: "<?php echo base_url('cyoa/upvote'); ?>",
        type: 'POST',
        data: form_data,
        success: function() 
            {
            $("#upvote").hide();
            }
    });
    return false;
});
});

</script>
</pre>
2
  • The first problem I see (well, I see a few) is that you're outputting forms in a loop, so which one do you want to use? Commented Oct 5, 2012 at 17:25
  • I'm trying to enable an upvote button per post. Will I have to have a new script for each upvote? Commented Oct 5, 2012 at 17:34

4 Answers 4

1

Best way is to serialize your form data and send that to the server:

<script type="text/javascript">
$(document).ready(function(){
  $(".button").click(function(){
    var form_data = $("#myform").serialize();
    $.ajax({
        url: "<?php echo base_url('cyoa/upvote'); ?>",
        type: 'POST',
        data: form_data,
        success: function() 
            {
            $("#upvote").hide();
            }
    });
    return false;
  });
});

</script>

To access the form, give it a id:

<form id="myform" action="" method="post">
Sign up to request clarification or add additional context in comments.

6 Comments

I tried this and it's still not working. I have no idea what's wrong.
upvote is a method of the cyoa controller: public function upvote() { $this->load->model('Voting_model'); $message = $this->Voting_model->upvote(); $this->load->view('ajax_upvote'); }
add a var_dump($_POST) in your controller method, to see what is posted.
I tried var_dump but can't seem to get it to produce an output. I apologize for being such a noob.
the var_dump is producing the following: array(1) { ["story_id"]=> string(4) "5678" }
|
0

I strongly suggest to look at this plugin (and use it) :

JQuery Form Plugin

Comments

0

You can use form serialization to pass on data to php as below

First Give ID "storyform" to your form tag

$.ajax({
        url: "<?php echo base_url('cyoa/upvote'); ?>",
        type: 'POST',
        data: $("#storyform").serialize(),
        success: function() 
            {
            $("#upvote").hide();
            }
    });

Comments

0

try using json objects,

view....

<pre>
<?php foreach($query->result() as $row): ?>
<div>
<form action=" controller_name/upvote" method="post">
<input type="hidden" name="story_id" id = "story_id" value=<?php echo $row->id; ?>>
<input type="submit" name="story_id" class="button" id="submit_btn" value=<?php     echo      $row->id;?>>
</form>
</div>
<?php endforeach; ?>
 </pre>

Then your controller,

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Controller_name extends CI_Controller {

function __construct()
{
    parent::__construct();

    //loading libraries
    $this->load->helper(array('form','url'));

    $this->load->library('form_validation');


}
//##############################################################################
    function upvote(){


    //setting validation rules
    $this->form_validation->set_rules('story_id', 'story Id', 'required|xss_clean');


    if ($this->form_validation->run() == true){

        //if validations ok, send the  data to  database
        $this->load->model('your_model');

        $params = ($this->input->post('story_id');

        $query = 'INSERT INTO table_name (story_id) VALUES(?)';
        $result = $this->your_model_name->method_name($query,$params);

        echo '{"validation_result": "passed"}';

    }
    else{
        $output = '{"story_id":"'.form_error('story_id').'"}';

        echo $output;
        }

}
}
?>

Then Your java script file

$(document).ready(function(){
$('#submit_btn').live('click',function(){

    var form_data = {
                    $story_id: $('#story_id').val()
                };

                $.ajax({
                    type: "POST",
                    url: baseurl+"controller_name/upvote",
                    dataType: "json",
                    data : form_data,
                    success: 
                        function(data){

                            if(data.validation_result == "passed"){

                                $("#upvote").hide();


                            }
                            else{
                                //form_validation errors
                                }
                        }
                    });

        return false;   
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.