I
I
Ivan Damaskin2016-02-13 15:40:10
CodeIgniter
Ivan Damaskin, 2016-02-13 15:40:10

How in codeigniter, when submitting a form, first load the avatar file and then pass its data to the model?

Hello to all php monsters
I must say right away that the experience is not great. For this, I turn to experienced developers.
I'm writing my little project on codeigniter. I downloaded
the ion auth library for the authorization system.
I want to add an avatar when registering. In general, I did everything, added a field in the view, through the Ajax post request that sends all the form data.
The trouble is that the post request refers to the same page in the controller. Those. I'm on
/auth/create_user
Accordingly, the request leads there

$.ajaxFileUpload({
                    url 			:'/auth/create_user/',
                    secureuri		:false,
                    fileElementId	:'avatar',
                    dataType		: 'json',
                    data			: {
                        'first_name'			: $('#first_name').val(),
                        'last_name'				: $('#last_name').val(),
                        'email'				    : $('#email').val(),
                        'password'				: $('#password').val(),
                        'password_confirm'		: $('#password_confirm').val()
                    },
                    success	: function (data, status)
                    {
                        if(data.status != 'error')
                        {
                            $('#files').html('<p>Reloading files...</p>');
                            refresh_files();
                            $('#title').val('');
                        }
                        alert(data.msg);
                    }
                });

In this create_user controller, I process the data and send it to the model for writing to the database. But when I submit the form, there is no file upload data yet, and therefore a NULL value is sent from here and an error:
A Database Error Occurred

Error Number: 1048

Column 'avatar' cannot be null

INSERT INTO `users` (`username`, `password`, `email`, `group_id`, `ip_address`, `avatar`, `created_on`, `last_login`, `active`) VALUES ('ivan damaskin123', '694249d6babe4d1fee2b914e27cfd0c1452cc91f', '[email protected]', '2', '127.0.0.1', NULL, 1455366325, 1455366325, 1)

Filename: X:\home\bl.ls\www\system\database\DB_driver.php

Line Number: 331

Although a record is created in the database and even the path to the file is written, i.e. everything works, but the database initially receives NULL for the avatar cell when checking, but then the file is loaded and the data is all written as it should, but the error remains -(
I hope I'm not too confused and someone can figure it out.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Damaskin, 2016-02-14
@Joannes

Все очень просто оказалось на самом деле.
Сначала выполняем загрузку картинки, затем условие, если загружена то передаем данные в модель где у нас идет запись этих данных в бд причем туда же передаем и название файла которое у нас успешно уже загрузилось, если не загрузили то присваиваем переменно, которая должна была содержать url картинки, любое значение, например default.jpg и теперь у нас не передается null а по любому какое то значение будет одно из двух -) Кароче вывод такой, прежде чем писать код надо в голове или на бумаге по шагам все выстроить по шагам -)

T
ThunderCat, 2016-02-13
@ThunderCat

Well, I didn’t work with CI, but as far as I remember, this is MVC, go to the controller, look where the file path parameter is received, change it to some forced value, like "_", then it loads the file and writes there what you need. Or we correct the type of the field in the database - remove notNull.
This is easy way, how correctly based on the CI paradigm - this is a question for experts, and so - the skeleton will work)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question