Welcome Guest, Not a member yet? Register   Sign In
Cannot get AJAX to work for Post/Create
#1

This is my controller;

PHP Code:
    public function task_create(){
        
$rules = [
            
"description" => "required",
        ];
            
        if (!
$this->validate($rules)) {
            
//$errors = $validation->getErrors();
            
$response = [
                
'success' => false,
                
'msg' => "There are some validation errors",
            ];
            return 
$this->response->setJSON($response);
        } else {
            
$task = new TaskEntity();
            
$data = [
                
"user_id"       =>  $this->current_user->id,
                
"description"   => $this->request->getVar("description"),
            ];
            
            if (
$task->insert($data)) {
                
$response = [
                    
'success' => true,
                    
'msg' => "Task created",
                ];
            } else {
                
$response = [
                    
'success' => false,
                    
'msg' => "Failed to create task",
                ];
            }
            return 
$this->response->setJSON($response);    
        }
    } 

and this is task_create.js

Code:
$(function() {
        // Ajax form submission
        $('#form-task-create').on('submit', function(e) {
            //alert("Hello! I am an alert box!!");
            e.preventDefault();
            //OR can use var formData = new FormData(this);
            var formData = $(this).serialize();
            var tokenHash=jQuery("input[name=csrf_token_secret]").val();
            
            //We can add more values to form data
            //formData.append("key", "value");
            
            $.ajax({
                url:  '/admin/tasks/create',
                type: 'post',
                cache: false,
                data: formData,
                processData: false,
                contentType: false,
                dataType: 'json',
                beforeSend: function (xhr)  {      
                    xhr.setRequestHeader('X-CSRF-Token' , tokenHash);      
                },
                success: function(data) {
                    console.log(data);
                    $("#resultDiv").html(data);
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log(formData);
                    console.log(errorThrown+'---'+textStatus+'---'+jqXHR);
                    alert('Error at add data');
                }
            });
        });
    });

And this is a part of my view

Code:
<form class="form-horizontal" action="<?= route_to('admin/tasks/create'); ?>" method="post" id="form-task-create">
                        
                        <input type="hidden" name="<?= csrf_token() ?>" value="<?= csrf_hash() ?>" />
                          
                        <!-- category_name / text input -->
                        <div class="form-group" action="/tasks/create" >
                            <label for="name">
                                Task Description
                            </label>
                            <?php
                            $description = array(
                                'name'        => 'description',
                                'id'          => 'description',
                                'style'       => '',
                                'class'       => 'form-control col-md-6',
                                'placeholder' => ''
                            );
                            echo form_input($description);
                            ?>
                        </div>
                        
                        </br>
                        
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <button type="submit" class="btn btn-primary">Submit</button>
                            </div>
                        </div>
                    
                        <div id="resultDiv">
                            
                        </div>
                    </form>

Whenever i run it, I get always get a validation error. This is the console log;

{success: false, msg: 'There are some validation errors'}
msg: "There are some validation errors"
success: false
[[Prototype]]: Object

The above appears whether I leave the input box blank or with a string. Any pointers appreciated.
Reply


Messages In This Thread
Cannot get AJAX to work for Post/Create - by spreaderman - 06-04-2022, 05:53 AM



Theme © iAndrew 2016 - Forum software by © MyBB