简体   繁体   中英

How to send data with AJAX and PHP

I'm trying to implement a commenting box with AJAX and PHP (CodeIgniter framework). Here is the code.

The view (HTML code):

<form id="form" method="post">
    <div class="input-group" id="input-group"><!-- input group starts-->
        <textarea class="form-control" id="Comment" name="Comment"  placeholder="Comment on Scenery..." maxlength="300" cols="70" rows="3" required></textarea>
        <input type="hidden" id="uploader_id" value="<?php echo $uploader_id ?>"/>
        <input type="hidden" id ="scenery_id" value="<?php echo $scenery_id ?>"/>
        <button type="submit" id="submit"class="btn btn-info regibutton" >Post</button>
    </div>
</form>

<hr/>

<div class="comment-block">
<?php
if ($comment==NULL){
    //if no scenery comment echo disclaimer
    echo " <ul style = ' margin-left: 0px;padding-left: 0px;'> <li style = 'list-style: none; background-color: #fff; padding : 5px 5px 5px 10px; margin: 5px 5px 5px 5px'>";
    echo " No scenery Comments";    
    echo "</li>
        </ul>"; 
} else {
    foreach ($comment as $row){
        // if the comments are availabe echo them
        echo " <ul style = ' margin-left: 0px;padding-left: 0px;'> <li style = 'list-style: none; background-color: #fff; padding : 10px 5px 5px 10px; margin: 5px 5px 5px 5px'>";
        echo $row->Comment;
        echo "<br/>";
        echo "<p style='font-size: 11px; color:#333; padding-top: 5px;'>".date(" D d M Y - H:i:s ",strtotime($row->Date_posted))."By - ". $row->Username. " </p>";
        echo $row->Date_added;
        echo "</li>
            </ul>";
    }
}
?>
</div>

The AJAX code:

<script>
$(document).ready(function(){
    $('#submit').click(function(e){
        // remove the error class
        $('.input-group').removeClass('has-error');
        //remove the previous  
        $('.help-block').remove(); 
        var Comment = $('#Comment').val();
        var scenery_id = $('#scenery_id').val();
        var uploader_id = $('#uploader_id').val();
        var datastring = 'Comment'+Comment+'&scenery_id'+scenery_id+'&uploader_id'+uploader_id;

        $.ajax({
            type:'POST',
            url: "<?php echo base_url('display_scenery/add_comment')?>",
            data: datastring,
            datatype: 'json',
            cache: 'false',
            encode: true
        });
        .done(function(data) {
            // log data to the console so we can see
            console.log(data);
            // here we will handle errors and validation messages
            if(!data.success){
                $('#data.errors.input-group'){
                    $('#iput-group').addClass('has-error');
                    $('#iput-group').append('<div class= "help">' + data.errors.Comment+'</div>');
                } else {
                    $('#form').append('<div class="alert">'+ data.message+'</div>');
                } 
            )};
            .fail(function(data) {
                // show any errors
                // best to remove for production
                console.log(data);
            });
        }*/
        // prevent default action
        e.preventDefault();
    });
});
</script>

The back end code in CodeIgniter:

public function add_comment(){
    if(!$this->session->userdata('logged_in')) {
        $data['error'] = 'Signup needed to comment on a scenery';
    } else {
        $this->load->library('form_validation'); 
        $session_data = $this->session->userdata('logged_in');
        $User_id= $session_data['User_id'];
        $scenery_id = $_POST['Scenery_id'];
        $Comment=$_POST['Comment'];
        $this->form_validation->set_rules('Comment', 'Comment', 'trim|required');
        if($this->form_validation->run() == FALSE) {
            $data['error'] = validation_errors();
        } else {
            //loads the model image_display then redirects to scenery page
            $this-> image_display->add_comment( $scenery_id,$User, $Comment); 
            $data['Comment']=$this-> image_display->get_comments($scenery_id);
            $data['success'] = TRUE;
        }
    }
    echo json_encode($data);
}

I want a system where the user can comment and the comments can be displayed. I'm trying to locate why the code is not working,kindly assist, I'm relatively new to AJAX.

try this :

<script>
$(document).ready(function(){
    $('#submit').click(function(e){
        // remove the error class
         $('.input-group').removeClass('has-error');
         //remove the previous  
    $('.help-block').remove(); 
        var datastring = $("#form").serialize();

        $.ajax({
            type:'POST',
            url: "<?php echo base_url('display_scenery/add_comment')?>",
            data: datastring,
            datatype: 'json',
            cache: 'false',
            encode: true
        });
        .done(function(data)
        {
              // log data to the console so we can see
            console.log(data);
            // here we will handle errors and validation messages
        if(!data.success){

            $('#data.errors.input-group'){
                $('#iput-group').addClass('has-error');
                $('#iput-group').append('<div class= "help">' + data.errors.Comment+'</div>');
            }
            else
            {
                $('#form').append('<div class="alert">'+ data.message+'</div>');
            } 
            )};
        .fail(function(data) {

        // show any errors
        // best to remove for production
        console.log(data);
    });

        }*/
            // prevent default action
    e.preventDefault();
    });

});


</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM