开发者

My Ajax/jquery code not working with codeigniter

开发者 https://www.devze.com 2022-12-17 11:30 出处:网络
The following codes works without jquery. I insert data but it does not update with ajax. I have to refresh to show the update.

The following codes works without jquery.

I insert data but it does not update with ajax. I have to refresh to show the update.

Could anyone have a look at it and point out what I am doing wrong please?

Thanks in advance.

Jquery is this one.

$(document).ready(function(){
//global vars
var inputUser = $("#nick");
var inputMessage = $("#message");
var loading = $("#loading");
var messageList = $(".content > ul");

//functions
function updateShoutbox(){
    //just for the fade effect
    messageList.hide();
    loading.fadeIn();
    //send the post to shoutbox.php
    $.ajax({
        type: "POST", 
        url: "index.php/admin/messages/getShoutBox", 
        // data: "action=update",
        complete: function(data){
            loading.fadeOut();
            messageList.html(data.responseText);
            messageList.fadeIn(2000);
        }
    });
}
//check if all fields are filled
function checkForm(){
    if(inputUser.attr("value") && inputMessage.attr("value"))
        return true;
    else
        return false;
}

//Load for the first time the shoutbox data
updateShoutbox();

//on submit event
$("#form").submit(function(){
    if(checkForm()){
        var nick = inputUser.attr("value");
        var message = inputMessage.attr("value");
        //we deactivate submit button while sending
        $("#send").attr({ disabled:true, value:"Sending..." });
        $("#send").blur();
        //send the post to shoutbox.php
        $.ajax({
            type: "POST", 
            url: "index.php/admin/messages/insertShoutBox", 
            data: $('#form').serialize(),
            complete: function(data){
                messageList.html(data.responseText);
                updateShoutbox();
                //reactivate the send button
                $("#send").attr({ disabled:false, value:"Shout it!" });
            }
         });
    }
    else alert("Please fill all fields!");
    //we prevent the refresh of the page after submitting the form
    return false;
});
});

I have the following controller. controllers/admin/messages.php

function getShoutBox(){
  $data['title'] = "getshoutbox";
    $data['main'] = 'admin_home';
      $data['messages']=$this->MMessages->getMessages();
    $this->load->vars($data);
    $this->load->view('dashboard'); 

}

function insertShoutBox(){
    $data['title'] = "insertshoutbox";
    $data['main'] = 'admin_home';
    $this->MMessages->updateMessage();
    $data['messages']=$this->MMessages->getMessages();
    $this->load->vars($data);
    $this->load->view('dashboard'); 

}

View is this one.

<form method="post" id="form" action="index.php/admin/messages/insertShoutBox" >
        <label>User</label>
        <input class="text user" name="user" id="nick" type="text" MAXLENGTH="25" />
        <label>Message</label>
        <input class="text" id="message" name="message" type="text" MAXLENGTH="255" />
        <input id="send" type="submit" value="Shout it!" />

    </form>
    <div id="container">
        <ul class="menu">
            <li>Shoutbox</li>
        </ul>
        <span class="clear"></span>
        <div class="content">
            <h1>Latest Messages</h1>
            <div id="开发者_高级运维loading"><img src="images/general/loading.gif" alt="Loading..." /></div>

            <?php
            foreach ($messages as $key => $list){

            print_r ($list);
            }
            ?>

        </div>
    </div>


A few things look suspicious to me.

Are you sure this URL is correct?

url: "index.php/admin/messages/getShoutBox",

Also, this line looks a bit suspect:

if(inputUser.attr("value") && inputMessage.attr("value"))  

Have you check what happens if if both values are zero? (You could use the .val() function instead of .attr("value") as well)

Even if it does work, a simple return instead your if/else would have sufficed:

return (inputUser.attr("value") && inputMessage.attr("value"));


You have to use the following code:

$this->load->view('dashboard', '', TRUE);

This will return data rather than trying to directly output it to your browser.


I had a very similar, if not identical issue in my own site. I was trying to pull the contents of a div out of pages (views) generated by codeigniter, but the AJAX was just failing and firebug wasn't really giving me any clues beyond the fact that there was nothing returned, not even a 404 error.

iainco's answer saved me, but to make it work you have to set the data returned by codeigniter to a variable and echo it manually.

Here's the basics to get ajax working across both frameworks.

jQuery:

//setting up a global variable to make the code easier to recycle
AX = {
toLoad:'',
contentWrapper:'#content',
contentDiv:'#ajax-target'
};

//this is called on a click event I added to a DOM element that contains a link
function ajaxInit(){
    AX.toLoad = $(this).find('a').attr('href') + ' ' + AX.contentDiv;
    $(AX.contentWrapper).load(AX.toLoad,"");
}

and then the relevant codeigniter controller or view, assuming that $content contains the name of the view you're trying to load:

<div id='content'>
<div id='ajax-target'>
<?php
    //setting the third variable to true tells ci to return a data string that can be read using AJAX methods
    $content_var = $this->load->view("$content",'',TRUE);
    echo $content;
?>
</div>
</div>

NOTE: I had this working on a site without the extra ci step, but I'm now convinced this was due to some kind of (beneficial) bug because I couldn't reproduce it in my next project.

0

精彩评论

暂无评论...
验证码 换一张
取 消