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
#2

I cannot seem to find the form data being submitted. It hits the right controller and method though.

I should be able to access the form data like this right?

$this->request->getVar("description");

or even getPost, right?

Above is all null or blank.

The method does see the ajax as a post when I do this;

PHP Code:
        
if ($this->request->getMethod() == "post") {
            return 
$this->response->setJSON(json_encode('hello'));


Any pointers appreciated.
Reply
#3

Check the browser console to see if data is being sent.
Reply
#4

Your ajax url is wrong try this one.

Code:
url: "<?= base_url('admin/tasks/create');?>",
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#5

(This post was last modified: 06-05-2022, 12:20 AM by iRedds.)

(06-04-2022, 11:59 PM)InsiteFX Wrote: Your ajax url is wrong try this one.

Code:
url: "<?= base_url('admin/tasks/create');?>",

url correct.

'/admin/tasks/create' is a relative path and will use the domain of the loaded page.

for page https://domain/some/page, '/admin/tasks/create' -> https://domain/admin/tasks/create
Reply
#6

(This post was last modified: 06-05-2022, 02:50 AM by spreaderman.)

(06-05-2022, 12:18 AM)iRedds Wrote:
(06-04-2022, 11:59 PM)InsiteFX Wrote: Your ajax url is wrong try this one.

Code:
url: "<?= base_url('admin/tasks/create');?>",

url correct.

'/admin/tasks/create' is a relative path and will use the domain of the loaded page.

for page https://domain/some/page, '/admin/tasks/create'  -> https://domain/admin/tasks/create

Thanks. Even if I put in the full path, like "https://www.example.com/admin/tasks/create" I get the same thing.

If i log console.log(data); I see this;

{success: false, msg: 'There are some validation errors'}

But it give that back regardless of whether I pass validation or not I think.

(06-05-2022, 02:49 AM)spreaderman Wrote:
(06-05-2022, 12:18 AM)iRedds Wrote:
(06-04-2022, 11:59 PM)InsiteFX Wrote: Your ajax url is wrong try this one.

Code:
url: "<?= base_url('admin/tasks/create');?>",

url correct.

'/admin/tasks/create' is a relative path and will use the domain of the loaded page.

for page https://domain/some/page, '/admin/tasks/create'  -> https://domain/admin/tasks/create

Thanks.  Even if I put in the full path, like "https://www.example.com/admin/tasks/create" I get the same thing.

If i log console.log(data); I see this;

{success: false, msg: 'There are some validation errors'}

But it give that back regardless of whether I pass validation or not I think.

And I cannot seem to catch the form data.
Reply
#7

Speaking of the browser console, I meant the network section.
There you can see each request made by the browser (request and response headers, sent data and response body)

If the data is a send, then $_POST or request->getPost() must contain the data.
Perhaps some filter replaces the request class.
Reply
#8

(06-05-2022, 03:05 AM)iRedds Wrote: Speaking of the browser console, I meant the network section.
There you can see each request made by the browser (request and response headers, sent data and response body)

If the data is a send, then $_POST or request->getPost() must contain the data.
Perhaps some filter replaces the request class.

I checked the NETWORK tab and under PAYLOAD it shows;

csrf_token_mamamia=[token-snip]&description=canada

under headers, I see;

Request Method: POST
Status Code: 200 OK

under response I see;

{"success":false,"msg":"There are some validation errors"}
Reply
#9

(06-05-2022, 12:18 AM)iRedds Wrote:
(06-04-2022, 11:59 PM)InsiteFX Wrote: Your ajax url is wrong try this one.

Code:
url: "<?= base_url('admin/tasks/create');?>",

url correct.

'/admin/tasks/create' is a relative path and will use the domain of the loaded page.

for page https://domain/some/page, '/admin/tasks/create'  -> https://domain/admin/tasks/create

Thanks, I always used the base_url and never had a problem with ajax. but this is good to know.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#10

(This post was last modified: 06-06-2022, 03:07 AM by spreaderman.)

BTW, is this what it is supposed to look like in the NETWORK tab of chrome?  Is it sending correctly?

csrf_token_mamamia=[token-snip]&description=canada
Reply




Theme © iAndrew 2016 - Forum software by © MyBB