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

If you're debugging that, I would strip it down and simplify further, you probably don't need the form action on the form-class either if you're firing it off from ajax.

Also your ajax could be greatly simplified, also there's alpinejs Smile
Practical guide to IgnitedCMS - Book coming soon, www.ignitedcms.com
Reply
#12

(06-06-2022, 04:09 AM)ignitedcms Wrote: If you're debugging that, I would strip it down and simplify further, you probably don't need the form action on the form-class either if you're firing it off from ajax.

Also your ajax could be greatly simplified, also there's alpinejs Smile

thanks, will have a look at alpinjs but would like to try to solve this bug first. Seems the ajax I have is a bare minimum. The ajax request does make it to the controller and to the specific method. It just fails a simple validation rule. On the other hand, I can see the data been summitted via the network tab in chrome and I assume that is correct. Strange thing is that I cannot access the date with getVar or getPost. The method recognizes that the request is a POST, too.
Reply
#13

Try sending primitive data a=b with CSRF protection disabled (without passing tokens in the request body).
Reply
#14

Use the Developer Tools in your Web Browser F-12 key.

This may also help.

Makitweb - How to Send AJAX request with CSRF token in CodeIgniter 4
What did you Try? What did you Get? What did you Expect?

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

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

Thanks and am often using the developer tools to console out debugging info.  I have now turned of csfr per below.  The controller and method sit under Admin.  I have removed the references to csfr and confirm it is working.

PHP Code:
public $globals = [
'before' => [
// 'honeypot',
'csrf' => ['except' => 
[
'Api/*''Admin/*'],
],
],
'after'  => [
 
'toolbar',
 
// 'honeypot',
 
],
]; 

When I submit now, I get [] in the console for " console.log(data);" and under the network tab I get;

headers ok 200
request url; https://development.example.com/admin/tasks/create
payload;  [object Object]
preview: []

So I guess I am not sending the form data, right?

This is again my js;

Code:
  $(function() {
        $('#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);
            //var tokenHash=jQuery("input[name=csrf_token_mamamia]").val();
           
            //We can add more values to form data
            //formData.append("key", "value");
            baseurl = 'https://development.example.com'
           
            $.ajax({
                url:  'https://development.example.com/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');
                }
            });
        });
    });
Reply
#16

Just saw this on StackOverflow.

How to send FormData objects with Ajax-requests in jQuery
What did you Try? What did you Get? What did you Expect?

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

(This post was last modified: 06-11-2022, 08:51 PM by spreaderman.)

Really cannot figure this out but getting somewhat closer.  I have rewritten a lot of my code.  This is where I am at. 

This my controller:

Code:
public function task_create(){
    $validation = \Config\Services::validation();
$rules = [
"description" => "required",
];
    $this->validate($rules);
    if ($validation->run()==FALSE) {
    $errors = $validation->getErrors();
    log_message('error', implode($errors));
    $response = [
    'success' => 0,
    'msg' => $errors,
];
echo json_encode($response);
} else {
    $task = new TaskEntity();
        $data = [
            "user_id"      =>  $this->current_user->id,
"description"  => $this->request->getPost("description"),
];
log_message('error', 'id is'.$user_id);
log_message('error', 'description is'.$description);
if ($task->fill($data)) {
$response = [
'success' => 1,
'msg' => "Task created",
];
} else {
$response = [
'success' => 0,
'msg' => "Failed to create task",
];
}
echo json_encode($response);
}
}

This is my javascript;

Code:
$(function() {
        $('#form-task-create').on('submit', function(e) {
            e.preventDefault();
            var form = this;
            $.ajax({
                url:  'https://development.example.com/admin/tasks/create',
                type: $(form).attr('method'),
                data: new FormData(form),
                processData: false,
                contentType: false,
                dataType: 'json',
                beforeSend: function (xhr)  {     
                    //xhr.setRequestHeader('X-CSRF-Token' , tokenHash); 
                    $(form).find('span.error-text').text('');
                },
                success: function(data) {
                        if (data.success == 1){
                            $(form)[0].reset();
                            alert(data.msg);
                        }else{
                            $.each(data.msg, function(prefix, val){
                                $(form).find('span'+prefix+'_error').text(val);
                            });
                        }
                },
            });
        });
    });

When I submit the form without the description, I should see an error in the <span> area.  I do not.  I do see this in the network tab of chrome

Code:
{success: 0, msg: {description: "The description field is required."}}
msg: {description: "The description field is required."}
description: "The description field is required."
success: 0

Above is as expected.

When I submit the form with a description, for example "homework", I get an alert say, "development.example.com says: Task Created.  Unfortunately, it is not.  Under payload in the network tab, I can see; form data, description, homework and status 200 and then after I close the alter, I can see the response as  {"success":1,"msg":"Task created"}.  In my ci log files, I cannot see that the method is catching the vars as the log file say;  ERROR - 2022-06-10 04:47:06 --> id is
ERROR - 2022-06-10 04:47:06 --> description is
I watch expecting the vars to be written into the log.
Reply
#18

I got this working. Thank you all for your help and suggestions.

The controller;

PHP Code:
    public function task_create(){
        
$validation = \Config\Services::validation();
        
$rules = [
            
"description" => "required",
        ];
        
$this->validate($rules);
        if (
$validation->run()==FALSE) {
            
$errors $validation->getErrors();
            
//log_message('error', implode($errors));
            
$response = [
                
'success' => 0,
                
'msg' => $errors,
            ];
            echo 
json_encode($response);
        } else {
            
$task = new TaskModel();
            
$description $this->request->getVar('description');
            
$user_id $this->current_user->id;
            
$data = [
                
"user_id"       => $this->current_user->id,
                
"description"   => $description,
            ];
            
//log_message('error', 'id is'.$user_id);
            //log_message('error', 'description is'.$description);
            
if ($task->insert($data)) {
                
$response = [
                    
'success' => 1,
                    
'msg' => "Task created",
                ];
            } else {
                
$response = [
                    
'success' => 0,
                    
'msg' => "Failed to create task",
                ];
            }
            echo 
json_encode($response);    
        }
    } 

The javascript for task_create.js. In the headers I do <script> let ajaxUrl = "'.base_url().'";</script>

PHP Code:
$(function() {
        $(
'#form-task-create').on('submit', function(e) {
            
e.preventDefault();
            var 
form this;
            
//console.log(form);
            
$.ajax({
                
url:  ajaxUrl+'/admin/tasks/create',
                
type: $(form).attr('method'),
                
data: new FormData(form),
                
processDatafalse,
                
contentTypefalse,
                
dataType'json',
                
                
beforeSend: function (xhr)  {       
                    
//xhr.setRequestHeader('X-CSRF-Token' , tokenHash);   
                    
$(form).find('span.error-text').text('');
                },
                
                
success: function(data) {
                    if (
data.success == 1){
                        $(
'#task_index').DataTable().ajax.reload();
                        $(
form)[0].reset();
                        
alert(data.msg);
                        
// sort table to place most recent one on top
                        
var table = $('#task_index').DataTable();
                        
table.order( [ 3'desc' ] ).draw();
                        
//table.rows().eq( 0 ).addClass( 'newlyadded' );
                    
}else{
                        $.
each(data.msg, function(prefixval){
                            
console.log(val);
                            $(
"#error-text").append(val);
                            
//$(form).find('span '+prefix+'_error').text(val);
                        
});
                    }
                    
                },
            });
        });
    }); 

And the view.

Code:
<!-- right side -->
                <div class="col-md-3">
                    <div>
                        <h3>Add a New Task Here</h3>
                        
                    </div>
              
        
                    <form class="form-horizontal" action="<?= route_to('admin/tasks/create'); ?>" method="post" id="form-task-create">
                        
                        <!-- category_name / text input $descriptiont -->
                        <div class="form-group" >
                            <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);
                            ?>
                            <span id='error-text' class="text-danger error-text description_error" >here:</span>
                        </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>
                    
                </div>

If any questions, pleased to help.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB