Welcome Guest, Not a member yet? Register   Sign In
Updating my news post (with jquery/Ajax)
#1

[eluser]DynamiteN[/eluser]
I've been trying to get this to work, searched here and google with no luck
so i thought i gave it a shot telling my problems to you guys

anyways, i have a model, controller, and a view all setup
When i try to update this news post without all the ajax and stuff it works just fine
but if i try to use the ajax it wont work
i watched this tutorials earlier
http://www.weblee.co.uk/2009/06/07/simpl...er-part-1/
but i dont really know much about coding jquery and such
and in those tutorial he never shows how to do when working with a db
anyway
here is my controller:
Code:
function EditNewsPost() {
/*See details of a news post
Okey so THIS is the page/function i go to,so i see all the current data of the news post
and i show them in input fields
*/
    //if post is not submitted
    if($this->input->post('submit') == FALSE) {
            
    $nid = $this->uri->segment(4);
    $get = $this->admin_news_model->GetOneNews($nid);
    foreach($get as $news){
    $data['newspost'] = $news;
    }
    $data['page_title'] = 'View News Details';
    $this->load->view('admin/edit_news', $data);
    }else{
    $this->UpdateNews();
    }
}

    
function UpdateNews() {
/*
This is the function i am sent to after clicking submit
*/
if($this->input->post('submit') == TRUE){
$nid = $this->uri->segment(4);
$this->form_validation->set_rules('newstitle', 'News Title', 'required|trim');
$this->form_validation->set_rules('newsauthor', 'News Author', 'required|trim');
$this->form_validation->set_rules('newscontent', 'News Content', 'required|trim');
$this->form_validation->set_rules('news_date', 'News Date', 'required');

$newstitle = $this->input->post('newstitle');
$newsauthor =  $this->input->post('newsauthor');
$newscontent = $this->input->post('newscontent');
$news_date =  $this->input->post('news_date');
            
$data = array(
    'title'   => $newstitle,
    'content' => $newscontent,
    'author' => $newsauthor,
    'news_date' => $news_date
            );
            
    if($this->form_validation->run() == FALSE) {
    echo validation_errors();
    }else{
    $this->admin_news_model->UpdateNews($data, $nid);
    }

}else{
//if the submit is false
  $this->editnewspost();

}
            
}
And here is the view:
Code:
<?php $this->load->view('admin/header'); ?>


<div id="edit_news">
<div id="busy" style="display:none">Processing Form <img src="&lt;?php base_url(); ?&gt;/img/js/ajax-loader.gif" /></div>
<br/>
<div id="errors">&lt;?php echo validation_errors(); ?&gt;</div>

&lt;?php $form = array('id' => 'news_form');?&gt;

&lt;?php echo form_open("admin/admin_news/updatenews/$newspost->id", $form); ?&gt;

<p>Title: &lt;?php echo form_input('newstitle', $newspost->title); ?&gt;</p>

<p>Author: &lt;?php echo form_input('newsauthor', $newspost->author); ?&gt;</p><br/>

<p>Content: </p>&lt;?php echo form_textarea('newscontent', $newspost->content); ?&gt;<br/>
<br/>
<p>News Date: &lt;?php echo form_input('news_date', $newspost->news_date); ?&gt;</p><br/>

<br/>
&lt;?php echo form_submit('submit', 'Edit Post');?&gt;
&lt;?php echo form_close(); ?&gt;
</div>

&lt;?php $this->load->view('admin/footer'); ?&gt;

ALL this code actually works Smile
but if i where to add this code:
Code:
// Functon to Show out Busy Div
function showBusy(){
    $('#busy').show('slow');
}

// function to process form response
function processForm(html){

        $('#errors').hide('slow');
        
        window.setTimeout( function(){
            
            $('#busy').hide('slow');
            
        
            if(parseFloat(html)){
                 $('#news_form').after('Thank you for submitting');
                 $('#news_form').hide('slow');
             }else{
                 $('#errors').html(html).show('slow');
             }
            
         }, 3000);
    
}


$(document).ready(function() {

    // $.AJAX Example Request
    $('#news_form').submit(function(eve){
        eve.preventDefault();
        
        $.ajax({
            url: "/admin/admin_news/editnewspost/",
            type: "POST",
            dataType: "html",
            data: $('#news_form').serialize(),
            beforeSend: function(){
                showBusy();
            },
    
              success: function(html) {
                processForm(html);
             }
        });
        

    });

});

It wont work, and i dont know how to do this
i've been trying to go forward from that tutorial but i just cant get it to work
Plz, any help is highly appreciated

P.S im sure all my code could use some cleaning up Smile
#2

[eluser]pickupman[/eluser]
Watch your capitalization to match uri and your method names, as your code is never calling the controller, because you have camel case in one code and lowercase in the other.
Code:
&lt;?php echo form_open("admin/admin_news/UpdateNews/$newspost->id", $form); ?&gt;


$(document).ready(function() {

    // $.AJAX Example Request
    $('#news_form').submit(function(eve){
        
        
        $.ajax({
            url: "&lt;?php echo site_url('/admin/admin_news/EditNewsPost');?&gt;",
            type: "POST",
            dataType: "html",
            data: $('#news_form').serialize(),
            beforeSend: function(){
                showBusy();
            },
    
              success: function(html) {
                processForm(html);
             }
        });
        eve.preventDefault();
        

    });

});
Wrap your ajax urls using site_url() function to make sure you don't have a wrong relative link. And move the preventDefault as the very last event handler of the submit function.
#3

[eluser]cahva[/eluser]
As always, use Firebug (or some other devtool similar if you dont use Firefox) to debug ajax calls. That way you can see what happens in the background and see if the form is even submitted.
#4

[eluser]DynamiteN[/eluser]
[quote author="cahva" date="1271022618"]As always, use Firebug (or some other devtool similar if you dont use Firefox) to debug ajax calls. That way you can see what happens in the background and see if the form is even submitted.[/quote]

i do use firebug in FF
but i am new to it and i couldnt really see where the error was ...
#5

[eluser]pickupman[/eluser]
In firebug, enable the console tab, and reload the page. Whenever a ajax call is made you will see the url shown in the console window. If the ajax call is not found, the link will be red. If the call is found, the link will be black. You can click on the plus to expand the detail for the ajax call. There is a response tab that shows the output back from the server, and a parameters tab that shows the variables sent in the call. Worth its weight in gold.
#6

[eluser]DynamiteN[/eluser]
[quote author="pickupman" date="1271022365"]Watch your capitalization to match uri and your method names, as your code is never calling the controller, because you have camel case in one code and lowercase in the other.
Code:
&lt;?php echo form_open("admin/admin_news/UpdateNews/$newspost->id", $form); ?&gt;


$(document).ready(function() {

    // $.AJAX Example Request
    $('#news_form').submit(function(eve){
        
        
        $.ajax({
            url: "&lt;?php echo site_url('/admin/admin_news/EditNewsPost');?&gt;",
            type: "POST",
            dataType: "html",
            data: $('#news_form').serialize(),
            beforeSend: function(){
                showBusy();
            },
    
              success: function(html) {
                processForm(html);
             }
        });
        eve.preventDefault();
        

    });

});
Wrap your ajax urls using site_url() function to make sure you don't have a wrong relative link. And move the preventDefault as the very last event handler of the submit function.[/quote]

if i use the php in a .js file
Code:
url: "&lt;?php echo site_url('/admin/admin_news/EditNewsPost');?&gt;",
i get this with firebbug 400 bad request

and if i onyl is this
Code:
url: "/admin/admin_news/EditNewsPost/",
the whole page get messed up and i dont see any errors in firebug .... only on page

A PHP Error was encountered

Severity: Notice

Message: Undefined variable: newspost

Filename: admin/edit_news.php

Line Number: 13

all though i dont know why as it should have those variables set allready for this page ... im lost .. :/
#7

[eluser]DynamiteN[/eluser]
it seems to get all those post values correct but nothing else no warnings in red links or like that :/
#8

[eluser]pickupman[/eluser]
It looks like your model is not returning a result for GetOneNews(), and so $data['newspost'] is false. I don't know that your model is returning whether is a result object, result array, array, or a string. But check what you are looping through with:
Code:
foreach($get as $news){}

If you are only wanting one record from the DB, return that from your model since you model is GetOneNews().
Code:
/** Model
* @param int $id of news item to retrieve
* @return object result object
*/
function GetOneNews($id){

  $query = $this->db->get_where('news',array('news_id'=>$id)); //get news item with news_id of $id
  if($query->num_rows() > 0)
  {
    return $query->row(0);
  }
return FALSE;
}

//In Controller
$news = $this->admin_news_model->GetOneNews($nid);
if($news){
  $data['newspost'] = $news;
}else{
   //Do nothing with no news id found
}

PS I've found a little easier to not put my jQuery code in a .js file, as you can't use php tags in them. You can rename the file extension to .php and still use as javascript document. You might have to tell your editor the php file is a js to correct the syntax highlighting.
#9

[eluser]DynamiteN[/eluser]
Okey, so now i have edited a little in my files and dont really know what to do next
instead of having the java in a seperat file called .js
i now moved it to the view file (edit_news.php) this is the file where i submit the data
this is the php and java code in view file:
Code:
&lt;?php $this->load->view('admin/header'); ?&gt;


<div id="edit_news">
<div id="busy" style="display:none">Processing Form <img src="&lt;?php base_url(); ?&gt;/img/js/ajax-loader.gif" /></div>
<br/>
<div id="errors">&lt;?php echo validation_errors(); ?&gt;</div>

&lt;?php $form = array(
            'id' => 'news_form',
        );
    ?&gt;
&lt;?php echo form_open("admin/admin_news/UpdateNews/$newspost->id", $form); ?&gt;

[removed]

// Functon to Show out Busy Div
function showBusy(){
    $('#busy').show('slow');
}

// function to process form response
function processForm(html){

        $('#errors').hide('slow');
        
        window.setTimeout( function(){
            
            $('#busy').hide('slow');
            
            {}
            if(parseFloat(html)){
                 $('#news_form').after('Thank you for submitting');
                 $('#news_form').hide('slow');
             }else{
                 $('#errors').html(html).show('slow');
             }
            
         }, 3000);
    
}
$(document).ready(function(){
                
    // $.AJAX Example Request
    $('#news_form').submit(function(eve){
        eve.preventDefault();
        
        $.ajax({
            url: "/admin/admin_news/UpdateNews/",
            type: "POST",
            dataType: "html",
            data: $('#news_form').serialize(),
            beforeSend: function(){
                showBusy();
            },
    
              success: function(html) {
                processForm(html);
             }
        });
        

    });
});
            
  // Load jQuery
google.load("jquery", "1.4.2");
[removed]

<p>Title: &lt;?php echo form_input('newstitle', $newspost->title); ?&gt;</p>

<p>Author: &lt;?php echo form_input('newsauthor', $newspost->author); ?&gt;</p><br/>

<p>Content: </p>&lt;?php echo form_textarea('newscontent', $newspost->content); ?&gt;<br/>
<br/>
<p>News Date: &lt;?php echo form_input('news_date', $newspost->news_date); ?&gt;</p><br/>

<br/>
&lt;?php echo form_submit('submit', 'Edit Post');?&gt;
&lt;?php echo form_close(); ?&gt;
</div>

&lt;?php $this->load->view('admin/footer'); ?&gt;
When this linesad this:
Code:
url: "/admin/admin_news/UpdateNews/",
the whole page got fucked after submitting
now it is like this:
Code:
url: "/admin/admin_news/UpdateNews/",
And then it wont get fucked up on page

this is the controller right now:
Code:
function EditNewsPost() {
//See details of a news post
    
            //if post is not submitted
            if($this->input->post('submit') == FALSE) {
            
            $nid = $this->uri->segment(4);
                $get = $this->admin_news_model->GetOneNews($nid);
                if($get){
                $data['newspost'] = $get;
                }else{ /*Do nothing*/ }
            $data['page_title'] = 'View News Details';
            $this->load->view('admin/edit_news', $data);
            }else{
                $this->UpdateNews();
            }    
}

function UpdateNews() {
if(IS_AJAX) {
    if($this->input->post('submit') == TRUE){
    $nid = $this->uri->segment(4);
    $this->form_validation->set_rules('newstitle', 'News Title', 'required|trim');
    $this->form_validation->set_rules('newsauthor', 'News Author', 'required|trim');
    $this->form_validation->set_rules('newscontent', 'News Content', 'required|trim');
    $this->form_validation->set_rules('news_date', 'News Date', 'required');
    
    $newstitle = $this->input->post('newstitle');
    $newsauthor =  $this->input->post('newsauthor');
    $newscontent = $this->input->post('newscontent');
    $news_date =  $this->input->post('news_date');
                
    $data = array(
    'title'    => $newstitle,
    'content' => $newscontent,
    'author' => $newsauthor,
    'news_date' => $news_date
     );
                
        if($this->form_validation->run() == FALSE) {
            echo validation_errors();
            }else{
            $this->admin_news_model->UpdateNews($data, $nid);
            }
            }else{
            echo "News not updated";
            }
}else{
echo "No Direct Access";
}
}




now when i press submit that function (busy) that shows a rotating icon shows up as it's suppose to adn then i wait for the news updated line but i get the "news not updated"
and i dont know why, not getting any errors either in firebug

EDIT1:
P.S IF i submit everything without the java/ajax code it gets updated :/
#10

[eluser]cahva[/eluser]
So you have this:
Code:
if($this->input->post('submit') == TRUE){
And its saying that $_POST['submit'] is not TRUE. Try to change that to
Code:
if($this->input->post('submit')){
CI's input lib will return false if its not set so you dont have to use == TRUE(which itself is faulty as submits value is "Edit Post").

And even better, dont use post('submit') to check if the form is submitted. Some browsers(for example older IE) dont send the input value if you have not pressed the button, but pressed enter on some of the fields which also sends the form.

And check from the firebug that it indeed have sent the right information in POST.




Theme © iAndrew 2016 - Forum software by © MyBB