Welcome Guest, Not a member yet? Register   Sign In
CI, jQuery, and a Database
#1

[eluser]phusiondesign[/eluser]
I need some help understanding how to relate Code Igniter to jQuery and how to interact the two. I am using jQuery w/ the form plugin.

If someone could point me to a tutorial which shows how to have a input field which is submitted using json and jquery and then is inserted into a database and then then a success message is shown on the page.

I know this probably easy, but I am having a hard time figuring it out... even with the examples at jquey.com. Thanks.

I think this is because I am passing the values incorrectly around within in CI.
#2

[eluser]Jay Turley[/eluser]
I don't have a pointer to a tutorial, but here is how I did it:

1. Make the form-database work without jquery in the mix at all.

2. Include jquery on the form page, then use jquery to replace the form submit with an ajax call.
a. I typically set the form action to ''
b. I typically use serialize() to get the form elements ready for sending (use serializetoarray() for JSON notation)
c. I typically call the ajax pointing it to an ajax-only controller which will return a JSON view.

This is called progressive enhancement, and should be used in most cases when adding Ajax to a web application. Make it work first, then layer the ajax on top.
#3

[eluser]phusiondesign[/eluser]
Thanks for the help... Here is what I have so far and hope that someone can help me to get it working. It gets to the point where it alerts me before it does the ajaxSubmit.

Model:

Code:
<?php

class ratings_model extends Model {
    
    function get_ratings_avg($entry) {
        $this->db->select_avg('rating','average');
        $this->db->where('entry_id',$entry);
        $rating = $this->db->get('ratings');
        
        return $rating->row('average');            
    }
    
    function get_ratings_count($entry) {
        $this->db->where('entry_id', $entry);
        $rating = $this->db->get('ratings');
        
        return $rating->num_rows();
  }
    

}
?>

Controller:

Code:
<?php
class Ratings extends Controller {

    function Ratings() {
        parent::Controller();

        $this->load->helper('url');
        $this->load->helper('form');
        
        $this->load->scaffolding('ratings');
        
        $this->load->model('ratings_model');    
    }

    function index() {
        $data['title'] = "Ratings - Home";
        $data['heading'] = "Test Rating";
        $data['query'] = $this->db->get('ratings');
        
        $this->load->view('ratings_view', $data);
    }
        
    function add() {
        $data = json_decode($_POST);
        
        $this->db->insert('ratings', $data);
        
        $output = '{ "success": "yes" }';
        echo $output;
    }
}

?>

View:

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;
&lt;meta http-equiv='expires' content='-1' /&gt;
&lt;meta http-equiv='pragma' content='no-cache' /&gt;
&lt;title&gt;&lt;?=$title?&gt;&lt;/title&gt;

&lt;link rel="stylesheet" href="/public/css/member.css" type="text/css" media="screen" /&gt;








&lt;link rel="stylesheet" href="/public/css/jquery.rating.css" type="text/css" media="screen" /&gt;

&lt;/head&gt;

&lt;body&gt;

<h1>&lt;?=$heading?&gt;</h1>


$(function(){
    $('#form1 :radio.star').rating();
});


$(function(){
    $('.auto-submit-star').rating({
        callback: function(value, link){
            // 'this' is the hidden form element holding the current value
            // 'value' is the value selected
            // 'element' points to the link element that received the click.
            alert("Selected Value: " + value);
            $('#form1').ajaxSubmit({
                type: "POST",
                url: "http://www.mydomain.com/index.php/ratings/add",
                dataType: "json",
                data: "entry_id=1&rating=2",
                success: alertMe
            });
            return false;
        }
    });
});

function alertMe() {
    alert("Success! Woot!");
}


&lt;form id="form1"&gt;
  <div class="Clear">
    &lt;input class="auto-submit-star {split:2}" type="radio" name="rating" value="0.5"/&gt;
    &lt;input class="auto-submit-star {split:2}" type="radio" name="rating" value="1.0"/&gt;
    &lt;input class="auto-submit-star {split:2}" type="radio" name="rating" value="1.5"/&gt;
    &lt;input class="auto-submit-star {split:2}" type="radio" name="rating" value="2.0"/&gt;
    &lt;input class="auto-submit-star {split:2}" type="radio" name="rating" value="2.5"/&gt;
    &lt;input class="auto-submit-star {split:2}" type="radio" name="rating" value="3.0"/&gt;
    &lt;input class="auto-submit-star {split:2}" type="radio" name="rating" value="3.5" checked="checked"/&gt;
    &lt;input class="auto-submit-star {split:2}" type="radio" name="rating" value="4.0"/&gt;
    &lt;input class="auto-submit-star {split:2}" type="radio" name="rating" value="4.5"/&gt;
    &lt;input class="auto-submit-star {split:2}" type="radio" name="rating" value="5.0"/&gt;
  </div>
&lt;/form&gt;

<div style="clear: both;">
  <p>&lt;? echo 'Average: '.$this->ratings_model->get_ratings_avg(1) ?&gt;</p>
  <p>&lt;? echo 'Ratings: '.$this->ratings_model->get_ratings_count(1) ?&gt;</p>
</div>

&lt;/body&gt;
&lt;/html&gt;

I am probably making some obvious mistake... thanks in advance.
#4

[eluser]Jay Turley[/eluser]
[quote author="phusiondesign" date="1206429175"]
Code:
$(function(){
    $('.auto-submit-star').rating({
        callback: function(value, link){
            // 'this' is the hidden form element holding the current value
            // 'value' is the value selected
            // 'element' points to the link element that received the click.
            alert("Selected Value: " + value);
            $('#form1').ajaxSubmit({
                type: "POST",
                url: "http://www.mydomain.com/index.php/ratings/add",
                dataType: "json",
                data: "entry_id=1&rating=2",
                success: alertMe
            });
            return false;
        }
    });
});

I am probably making some obvious mistake... thanks in advance.[/quote]

Okay, maybe I am missing something, but it doesn't look to me like you are using the Form Plugin for jquery.

Instead, your syntax above looks exactly like the typical form for a plain jQuery Ajax submission. Try changing this line:
Code:
$('#form1').ajaxSubmit({
to this:
Code:
$.ajax({
I do not guarantee anything, and I am not in a position to test right now, but that very well could be the problem.
#5

[eluser]phusiondesign[/eluser]
I tried that earlier and again just now and it didn't give me any luck either time. From what I can tell it is either not posting the data correctly to the controller or my controller is not handling the information correctly. Still need some help. Thanks!
#6

[eluser]phusiondesign[/eluser]
I have changed my ajax call to a script data type and the controller to handle it accordingly, and everything is working.... but I did not utilize json and would really like to understand how and why it wasn't working.

Thanks everyone for the help.

Controller:

Code:
function add() {
        //$data = json_decode($_POST);
                
        $data = array(
            'entry_id' => $_POST['entry_id'],
            'rating' => $_POST['rating']
        );
        
        $this->db->insert('ratings', $data);
        
        $output = '{ "success": "yes" }';
        echo $output;
    }

Ajax Call:

Code:
$(function(){
    $('.auto-submit-star').rating({
        callback: function(value, link){
            // 'this' is the hidden form element holding the current value
            // 'value' is the value selected
            // 'element' points to the link element that received the click.
            alert("Selected Value: " + value);
            $.ajax({
                type: "POST",
                url: "http://www.mydomain.com/ratings/add",
                dataType: "script",
                data: "entry_id=1&rating;=" + value,
                success: alertMe
            });
            return false;
        }
    });
});
#7

[eluser]Merolen[/eluser]
Hi, I've actually been working with jQuery and JSON today. Think I'm starting to understand it all. For some reason it didn't work, but after a while (the next day) it suddenly worked. Maybe I did something to it or maybe there is some kind of strange caching I don't know of.

In the success: are you doing:
Code:
success: function(data){
    alert(data.success);
}
when you set the dataType: 'json'?

Also defining
Code:
error: function (data, status, e){ alert('error: ' + e); }
might be a good idea for debugging

You have tried everything? removeing the "" inside the json-string? Or changing the ' ' to " "
Code:
// This one works for me
echo "{id: 'the-string'}";

These are my initial experience with jQuery and json, hope it helps




Theme © iAndrew 2016 - Forum software by © MyBB