I am new to jquery and ajax and now I have a hard time finding a fix to this problem of mine when inserting data into database using ajax and codeigniter.
All errors are okay but when there's no error on the form, I get a database error and all the inputs become NULL.
Controller
public function add () {
$this->load->model('user_model');
$data => array (
'first_name' => $this->input->post['first_name'],
'last_name' => $this->input->post['last_name'],
'active' => $this->input->post['active'],
'date_registered' => date('Y/m/d h:i:sa')
);
// assume validation rules are already set.
if ($this->form_validation->run() == FALSE) {
$result['message'] = validation_errors();
} else {
$result['data'] = $this->user_model->save($data);
}
}
Ajax 1:
$(document).ready(function() {
$('#create-user').click( function(e) {
var is_valid = false;
var form_id = '#'+ $(this).parents('form').attr('id');
// Validate required fields are not blank
// do a js validation?
// Apply action
if(is_valid) {
var add_result = do_submit(form_id);
} else {
$('#error-msg').html(result.message); // if form is not valid
}
});
});
Ajax 2:
function do_submit(form_id) {
var url = $(form_id).attr("action");
var ajax_result = false;
var formData = {};
// Submit form using ajax
ajax_result = $.ajax({
type: "POST",
url: url,
data: $(form_id).serialize(),
dataType: 'json',
success: function(result) {
// return result;
// do something
console.log(result);
if (result.data) {
make_alert();
}
},
error: function(textStatus) {
/* Note: decide how all errors should be shown. */
swal({
title: "Error!",
text: "Oops, something went wrong. Check fields and try again.",
type: "error"
});
}
});
return ajax_result;
} // End do_submit()
I think you have a syntax error here
$this->load->model('user_model');
'data' => array (
'first_name' => $this->input->post['first_name'],
'last_name' => $this->input->post['last_name'],
'active' => $this->input->post['active'],
'date_registered' => date('Y/m/d h:i:sa')
);
Should probably be
$this->load->model('user_model');
$data => array (
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'active' => $this->input->post('active'),
'date_registered' => date('Y/m/d h:i:sa')
);
Your parameter array seems to be a key, but of what variable? So you need to have $data instead of 'data'.
To get post data in codeigniter we use
$this->input->post('field_name');
SO you need to change all post['field_name'] to post('field_name')
Your final code would be
$this->load->model('user_model');
$data => array (
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'active' => $this->input->post('active'),
'date_registered' => date('Y/m/d h:i:sa')
);
Read https://www.codeigniter.com/user_guide/libraries/input.html
Related
I am submitting a form and AJAX is displaying errors as it should but when everything goes right, it means that when form values are saving in database correctly AJAX is not triggering the success function.
Here's the Laravel product verification code:
public function productVerify(Request $request)
{
$val = $request->validate
(
[
'name' => 'required',
's_description' => 'required',
'l_description' => 'required',
'image_src' => 'required|mimes:jpg,png,jpeg',
'category' => 'required',
'quantity' => 'required|integer|not_in:0|regex:^[1-9][0-9]+^',
'price' => 'required|integer|not_in:0|regex:^[1-9][0-9]+^',
],
[
'required' => 'The :attribute field is required',
'mimes' => 'Image should be a JPG, JPEG, or PNG',
'integer' => 'The :attribute field should be an integer.',
's_descripton.required' => 'The short description is required',
'l_descripton.required' => 'The long description is required',
'image_src.required' => 'The image file is required.'
]
);
if (!$val)
{
return response()->json(['errors']);
}
else
{
return response()->json(['success' => 'Product Added Successfully']);
}
}
Here's the AJAX code:
$(document).ready(function()
{
$("#addForm").submit(function(event)
{
// Store all data from form as object;
var formData = new FormData(this);
$.ajaxSetup({
headers:
{
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
// AJAX implementation error:function() return errors without page reload.
$.ajax(
{
url: '/save_product',
type: "POST",
processData:false,
contentType:false,
cache:false,
dataType: 'json',
data:formData,
success: function(xhr)
{
responseSu = xhr.responseJSON.success;
alert(responseSu);
},
error:function(xhr, status, error)
{
// Errors from the XML Http Request JSON Response
responseER = xhr.responseJSON.errors;
// console.log(responseER);
$("#error").html(" ");
// For Each loop for printing errors from the response
$.each(responseER, function (key, item)
{
console.log(item);
$("#error").append("<li class='text-danger'>"+item+"</li>")
// Hide Errors after 15 seconds with a fadeout animation
$("#error").show().delay(15000).fadeOut();
});
}
});
// Stop form from submitting normally
event.preventDefault();
});
});
After the form is submitted successfully and data is inserted into database it gives the error:
i'm trying to modify a product but when i click the button a got that 500 (Internal Server Error)
this is ajax method
$(document).ready(function(){
fetch_customer_data();
$(document).on('click', '#btnModify', function(){
var name = $('#Name2').text();
var title = $('#Title2').text();
var mainPrice = $('#MainPrice2').text();
var discount = $('#DiscountPrice2').text();
var StockQ = $('#StockQuantity2').text();
var Desc = $('#Discription2').text();
var Features = $('#Features2').text();
var id = $("#id2").text();
if(name != ' ')
{
$.ajax({
url:"/Product/Update",
method:"POST",
data:{name:name, title:title , name:name , mainPrice:mainPrice , discount:discount ,StockQ:StockQ , Desc:Desc , Features:Features, id:id, _token:_token},
success:function(data)
{
fetch_customer_data();
}
});
}
else
{
alert('Something went wrong');
}
});
and this is the edit function
public function edit(Request $request)
{
if($request->ajax())
{
$data = array([
'Name' => $request->name,
'Title' => $request->title,
'MainPrice' => $request->mainPrice,
'DiscountPrice' => $request->discount,
'StockQuantity' => $request->StockQ,
'Discription' => $request->Desc,
'Features' => $request->Features
]
);
DB::table('products')
->where('id', $request->id)
->update($data);
echo '<div class="alert alert-success">Data Updated</div>';
}
}
Route :
Route::post('/Product/Update', [ProductsController::class, 'edit']);
Try this:
$data = array(
'Name' => $request->name,
'Title' => $request->title,
'MainPrice' => $request->mainPrice,
'DiscountPrice' => $request->discount,
'StockQuantity' => $request->StockQ,
'Discription' => $request->Desc,
'Features' => $request->Features
)
because you are using multi dimensional array instead of 2d array
maybe this will helpful
I'm trying to send data through AJAX put method. I don't know what I'm doing wrong.
All code posible code
link
My route file
Route::resource('restaurant', 'RestaurantController');
RestaurantController
public function update(Request $request, $id)
{
$rules = array (
'address_id' => 'required|alpha',
'name' => 'required|alpha',
'description' => 'required',
'phone' => 'required',
'email' => 'required|email',
'homemade' => 'required'
);
$validator = Validator::make ( Input::all (), $rules );
if ($validator->fails ())
return Response::json ( array (
'errors' => $validator->getMessageBag ()->toArray ()
) );
else {
$items = Restaurant::find ($id);
$items->address_id = ($request->address_id);
$items->name = ($request->name);
$items->description = ($request->description);
$items->phone = ($request->phone);
$items->email = ($request->email);
$items->homemade = ($request->homemade);
$items->save ();
return response ()->json ( $items );
}
}
ajax request
$('.modal-footer').on('click', '.edit', function() {
$.ajax({
type: 'PUT',
url: '/restaurant',
data: {
'_token': $('input[name=_token]').val(),
'id': $("#fid").val(),
'address_id': $('#address_id').val(),
'name': $('#name').val(),
'description': $('#description').val(),
'phone': $('#phone').val(),
'email': $('#email').val(),
'homemade': $('#homemade').val(),
'lat': $('#lat').val(),
'lng': $('#lng').val(),
'bank_name': $('#bank_name').val(),
'bank_code': $('#bank_code').val(),
'paypal_email': $('#paypal_email').val(),
'paypal_merchantname': $('#paypal_merchantname').val(),
'zipcode': $('#zipcode').val(),
'easypeisa': $('#easypeisa').val(),
'cod': $('#cod').val()
},
success: function(data) {
if (data.errors){
$('#myModal').modal('show');
if(data.errors.address_id) {
$('.address_id_error').removeClass('hidden');
$('.address_id_error').text("address_id name can't be empty !");
}
if(data.errors.name) {
$('.name_error').removeClass('hidden');
$('.name_error').text("name can't be empty !");
}
if(data.errors.description) {
$('.description_error').removeClass('hidden');
$('.description_error').text("description must be a valid one !");
}
Im a beginner in Laravel. I have two login authentication types; using facebook API and using your own email.
Everytime I upload an image when im logging in with my own email, I got this error
{"error":{"type":"Symfony\Component\Debug\Exception\FatalErrorException","message":"Call to a member function create() on a non-object","file":"C:\base_app_folder\app\controllers\OnboardingController.php","line":133}}
But it's success uploading image when im logging in with Facebook API
Here's my Controller :
if (Input::hasFile('profile_pic')) {
$images = ImageUpload::handle(Input::file('profile_pic'));
$mainImage = $images[0];
$time = time();
$mainImageObj = $this->images->create($this->userId, array(
'entity_id' => $this->currentUser->Entity_Id,
'image_url' => $mainImage['image_url'],
'width' => $mainImage['width'],
'height' => $mainImage['height'],
'created_fb' => $time,
'is_original' => $mainImage['is_original'],
'original_id' => null
));
$this->userDetails->update($this->userId, array(
'Profile_Pic_Url' => $mainImageObj->image_url
));
array_shift($images);
Log::info('images = '.print_r($images, true));
$retImage = "";
foreach ($images as $image) {
$this->images->create($this->userId, array(
'entity_id' => $this->currentUser->Entity_Id,
'image_url' => $image['image_url'],
'width' => $image['width'],
'height' => $image['height'],
'created_fb' => $time,
'is_original' => $image['is_original'],
'original_id' => $mainImageObj->image_id
));
if ($image['width'] == 250) {
$retImage = $image['image_url'];
}
}
return Response::json(array(
'success' => true,
'message' => 'Upload succeeded!',
'image_thumbnail_url' => $retImage,
'image_url' => $mainImage['image_url']
));
} else {
App::abort(404);
}
}
Here's my View :
<form action="{{{ route('postEditProfile', array('profile_id' => Session::get('user_id'))) }}}" class="dropzone" id="profile-pic-upload">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</form>
And here's the javascirpt:
<script type="text/javascript">
$(window).bind("load", function() {
var pic_height = $('.profile_pic').height();
var pic_width = $('.profile_pic').width();
var height_factor = pic_height/240;
var pic_width = pic_width/height_factor;
$('.profile_pic').css('height','240px');
$('.profile_pic').css('width',pic_width+"px");
});
$(document).ready(function () {
$(function () {
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
});
var routes = {
postEditProfile: "{{{ route('postOnboardingPhotos') }}}"
};
var onboarding = new Onboarding(routes);
});
</script>
Anyone knows how to solve it ? I've searching for the error message but it seems no one ever found this error message.
Did you forget to inject a dependency and assign $this->images to that dependency? Looks like you have an images repository and you forgot to take care of this.
There is a Zend Registration Form. Having as input username, email, password and confirm password. Validator for email is following:
$this->add(array(
'name' => 'email_reg',
'required' => true,
'filters' => array(
array(
'name' => 'StripTags',
),
array(
'name' => 'StringTrim',
),
),
'validators' => array(
array(
'name' => 'EmailAddress',
'options' => array(
'domain' => true,
'messages' => array(
\Zend\Validator\EmailAddress::INVALID_FORMAT => 'Email address format is invalid'
),
),
),
array(
'name' => 'Db\NoRecordExists',
'options' => array(
'table' => 'user',
'field' => 'email',
'adapter' => $sm->get ( 'Zend\Db\Adapter\Adapter' ),
'messages' => array(
NoRecordExists::ERROR_RECORD_FOUND => 'E-mail address already exists'
),
),
),
),
));
There are 4 validators: Required Type, e-amil format and if there is someone with following e-mail in database.
Error messages will be:
- E-mail is required
- Email address format is invalid
- E-mail address already exists
Problem Trying to catch error messages and output using ajax. In RegisterController having following function:
public function ajaxAction()
{
if (!$this->request->isPost()) {
return $this->redirect()->toRoute(NULL,
array( 'controller' => 'index'
)
);
}
$form = $this->getServiceLocator()->get('RegisterForm');
$form->setInputFilter(new RegisterFilter($this->getServiceLocator()));
$post = $this->request->getPost();
$form->setData($post);
$response = $this->getResponse();
$hello = 1;
if (!$form->isValid()){
// email is invalid; print the reasons
$json= $form->getMessages();
$response->setContent(\Zend\Json\Json::encode($json));
}
return $response;
}
And jQuery file:
$( document ).ready(function() {
var urlform = "register/ajax";
$("#btnRegister").click( function() {
$("#Register").submit( function() {
return false;
});
$.ajax({
url: urlform,
type: 'POST',
dataType: 'json',
async: true,
data: $(".form-signin").serialize(),
success: function (data) {
$("#rCheck").text(data);
console.log(data);
},
error: function (data) {
$("#rCheck").text(data);
console.log(data);
}
});
});
});
In Console i got something like this https://imagizer.imageshack.us/v2/558x205q90/661/uC09Da.png and in div with id #rCheck getting [Object][Object].
From the image you provided the error messages are correctly returned. The error is that you are trying to write directly an Object into your div.
You should have seached how to read an object with JavaScript. Try with this code :
success: function (data) {
data.forEach(function(datum) {
Object.keys(datum).forEach(function (key) {
$('<p>'+obj[key]+'</p>').appendTo('#rCheck');
});
});
console.log(data);
},
Or you may also do that within your ajaxAction :
$messages = array();
$errors = $form->getMessages();
foreach($errors as $key=>$row)
{
if (!empty($row) && $key != 'submit') {
foreach($row as $keyer => $rower)
{
$messages[$key][] = $rower;
}
}
}
if (!empty($messages)){
$response->setContent(\Zend\Json\Json::encode($messages));
}
return $response;
Here's is a good post on how to use Zend\Form with Ajax validation.