Laravel AJAX put method 405 error - php

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 !");
}

Related

Ajax live edit is not wotking and got an 500 (Internal Server 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

return a view or redirect after ajax request

how i cant redirect o return a view after a ajax request.
i try validate the request and after (if the request are ok) return a view, but this dont work, i try redirect to the new route but dont work too.
this is my controller:
public function searchActivity(Request $request){
$validator = Validator::make($request->all(), [
'search' => 'required',
'date' => 'required_with:search|required|date|date_format:d-m-y|after:yesterday'
]);
if ($validator->fails()){
return response()->json([
'sucess' => false,
'errors' => $validator->errors()->toArray(),
'data' => $request->all()
]);
}else{
$queries = DB::table('activities')->where('name', $request->search)->orWhere('City', $request->search)->paginate(1);
return redirect()->route('ActivitiesResults', ['results' => $queries]);
}
JS code:
function selectDate(){
$(document).ready(function () {
$( "#datepicker" ).datepicker({ dateFormat: 'dd-mm-yy' });
});
}
function searchActivity(event) {
event.preventDefault();
console.log(event);
$.ajax({
type: 'POST',
url: searchRoute,
data: {
search: $('.search').val(),
date: $('#datepicker').val(),
_token: $('#token').val()
},
dataType : "json",
success: function (data) {
if (data.success){
console.log(data)
}else{
console.log(data.errors);
}
}
})
}
thanks for the help!
you need to change your php code
if ($validator->fails()){
return response()->json([
'sucess' => false,
'errors' => $validator->errors()->toArray(),
'data' => $request->all()
]);
}else{
return response()->json([
'sucess' => true,
'what_you_want' => ''
]); }
change your ajax code like this
success: function (data) {
if (data.success){
//console.log(data)
window.location.replace("http://stackoverflow.com");
}else{
console.log(data.errors);
window.location.replace("http://google.com");
}
}
use header("url) or window.location.href="url" in you success funciton.

i want to register user in laravel 5.2 by ajax, but the image file always turn null, why?

my ajax code is:
$('form.employeeForm').on('submit',function(){
$("span").hide();
$(".danger").removeClass("danger");
var that=$(this),
url=that.attr('action'),
method=that.attr('method'),
data={};
that.find('[name]').each(function(index,value){
var that=$(this),
name=that.attr('name'),
value=that.val();
data[name]=value;
});
console.log(data);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': data['_token']
}
});
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: data,
beforeSend: function () {
$('#addEmployee').val('Recording data..........');
},
complete: function () {
$('#addEmployee').val('Save Record');
},
success: function (data) {
console.log(data);
},
error: function(data){
var errors= data.responseJSON;
//var error=errors.name[0];
$.each(errors.errors, function(key, value) {
console.log(key,value);
//$('input','textarea').removeClass('error');
var dtextarea=$('textarea[name="'+key+'"]').closest('textarea[name="'+key+'"]');
dtextarea.next('.text-danger').remove();
dtextarea.addClass('danger').after("<span class='text-danger'>"+value+"<br></span>");
var dinput=$('input[name="'+key+'"]').closest('input[name="'+key+'"]');
dinput.next('.text-danger').remove();
dinput.addClass('danger').after("<span class='text-danger'>"+value+"<br></span>");
//$('input[name="'+key+'"]').addClass('danger').closest('input[name="'+key+'"]').after("<span class='text-danger'>"+value+"</span>");
});
}
});
return false;
});
Controller Code is:
public function eregister(Request $request){
if ($request->ajax()) {
$rules = [
'full_name' => 'required',
'image' => 'required',
'eid' => 'required',
'username' => 'required',
'address' => 'required',
'join_date' => 'required',
'n_id_no' => 'required',
'position' => 'required',
'blood' => 'required',
'birth_date' => 'required',
// 'role' => 'required',
'phone_no' => 'required',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed',
'password_confirmation' => 'required|min:6',
];
$validation = Validator::make($request->all(), $rules);
$errors=$validation->errors();
//print_r($errors->image);
if ($validation->fails()) {
return response()->json([
'status' => 'false',
'errors' =>$validation->errors()], 400);
//return response()->json($validation->errors());
} else {
$uploadDirectory = 'uploads/';
$file = $request->file('image');
$filename = $request->input('username') . "." . $file- >getClientOriginalName();
$saveData = new User();
if ($file->move($uploadDirectory, $filename)) {
$saveData->image = $filename;
$saveData->position = $request->input('position');
$saveData->full_name = $request->input('full_name');
$saveData->eid = $request->input('eid');
$saveData->phone_no = $request->input('phone_no');
$saveData->username = $request->input('username');
$saveData->address = $request->input('address');
$saveData->join_date = $request->input('join_date');
$saveData->n_id_no = $request->input('n_id_no');
$saveData->email = $request->input('email');
$saveData->blood = $request->input('blood');
$saveData->birth_date = $request->input('birth_date');
$saveData->status =1;
$saveData->password = Hash::make($request->input('password'));
if($saveData->save()){
return response()->json([
'status' => 'true',
'errors' =>null], 200);
}
}
}
} else {
return view('auth.register');
}
}
The problem is it always fires the error block of ajax though the form validation succeeded. I have debug the response of ajax for a validate form it returns 500 on network tab and the reason is the $file variable got null though i select an image file.

Can't insert data into database using ajax

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

Display Zend Form Validation error in Ajax

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.

Categories