I send a store request to my laravel application through AJAX. The controller function works properly, but either I cannot get a success message in my ajax function, or the function on success is not working.
Ajax code:
$.ajax({
type: "POST",
url: 'http://127.0.0.1:8000/dreams',
data: {
description: description,
offset_top: offset_top,
offset_left : offset_left
},
success: function(msg){
console.log("done");
}
});
Controller's store function:
public function store(Request $request)
{
echo $request;
if (Auth::check()) {
$user = Auth::user();
$dream = new Dream($request->all());
if ($dream) {
$user->dreams()->save($dream);
$response = array(
'dream' => $dream,
'status' => 'success',
'msg' => 'Setting created successfully',
);
return \Response::json($response);
}
return \Response::json(['msg' => 'No model']);
} else {
return \Response::json('msg' => 'no auth');
}
}
Try to pass data in ajax using this way.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: 'http://127.0.0.1:8000/dreams',
data: {
description: description,
offset_top: offset_top,
offset_left: offset_left
},
success: function(msg) {
console.log("done");
}
});
Try below code for store method:
public function store(Request $request)
{
if (Auth::check()) {
$user = Auth::user();
$dream = new Dream($request->all());
if ($dream) {
$user->dreams()->save($dream);
$response = array(
'dream' => $dream,
'status' => 'success',
'msg' => 'Setting created successfully',
);
return \Response::json($response);
}
return \Response::json(['msg' => 'No model']);
} else {
return \Response::json(['msg' => 'no auth']);
}
}
Related
I'm trying to make another ajax call when one is executed successfully to pass the post variable to another controller action. However, it is returning null when I check the console log message. I'm not sure why.
Here is my code:
jQuery:
$('#modify-store-name').on('change', function() {
$.ajax({
type: "POST",
url: "/user/get-one-store",
dataType: "json",
data: {
store_name: $(this).val()
}
}).done(function (msg) {
$.each(msg, function (i) {
$('#modify-store-label').attr('style', '');
$('#modify-store-desc').attr('style', '');
$('#modify-store-category-label').attr('style', '');
$('#modify-store-category').attr('style', '');
$('.upload-btn-wrapper').attr('style', '');
$('#modify-store-desc').val(msg[i].store_description);
$('#modify-store-category').html($("<option />").val(msg[i].store_category).text(msg[i].store_category));
$('#msubmit').attr('disabled', false);
});
$.ajax({
type: "POST",
url: "/user/modify-store",
dataType: "json",
data: {
store_name2: $('#modify-store-name').val() // why is this sending a null value
}
}).done(function(msg) {
console.log(msg);
}).fail(function(msg) {
console.log(msg);
});
}).fail(function (msg) {
$("#msg").html(msg.failure);
});
});
and my php code:
public function getonestoreAction()
{
$layout = $this->layout();
$layout->setTerminal(true);
$view_model = new ViewModel();
$view_model->setTerminal(true);
try {
$store_name = $this->params()->fromPost('store_name');
echo json_encode($this->getUserService()->getAStore($store_name));
} catch (\Exception $e) {
echo json_encode(array('failure' => $e->getMessage()));
}
return $view_model;
}
public function modifystoreAction()
{
$layout = $this->layout();
$layout->setTerminal(true);
$view_model = new ViewModel();
$view_model->setTerminal(true);
if ($this->getRequest()->isPost()) {
try {
$store_name = $this->params()->fromPost('store-name2');
echo json_encode($store_name); // returning null
$mstore_name = $this->params()->fromPost('modify-store-name');
$mstore_description = $this->params()->fromPost('modify-store-description');
$mstore_category = $this->params()->fromPost('modify-store-category');
$mstore_image = $this->params()->fromFiles('modify-store-image');
if (count($mstore_image) > 0) {
if ($this->getUserService()->modifyStore($store_name, array('store_name' => $mstore_name, 'store_description' => $mstore_description, 'store_category' => $mstore_category, 'store_image' => $mstore_image, 'tmp_name' => $mstore_image['tmp_name']))) {
echo json_encode(array('success' => 'Store was modified successfully.'));
}
}
} catch (\Exception $e) {
echo json_encode(array('failure' => $e->getMessage()));
}
}
return $view_model;
}
I read that you can make two ajax calls like this but I'm not sure why one is not passing the store name via post.
Any help would be appreciated
Thanks!
testAjax function inside PostsController class:
public function testAjax(Request $request)
{
$name = $request->input('name');
$validator = Validator::make($request->all(), ['name' => 'required']);
if ($validator->fails()){
$errors = $validator->errors();
echo $errors;
}
else{
echo "welcome ". $name;
}
}
inside web.php file:
Route::get('/home' , function(){
return view('ajaxForm');
});
Route::post('/verifydata', 'PostsController#testAjax');
ajaxForm.blade.php:
<script src="{{ asset('public/js/jquery.js') }}"></script>
<input type="hidden" id="token" value="{{ csrf_token() }}">
Name<input type="text" name="name" id="name">
<input type="button" id="submit" class="btn btn-info" value="Submit" />
<script>
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#name").val();
var token = $("#token").val();
/**Ajax code**/
$.ajax({
type: "post",
url:"{{URL::to('/verifydata')}}",
data:{name:name, _token: token},
success:function(data){
//console.log(data);
$('#success_message').fadeIn().html(data);
}
});
/**Ajax code ends**/
});
});
</script>
So when click on submit button by entering some data then the output message(echo "welcome ". $name;) is printing. But when I click on submit button with empty text box then it does not print the error message from the controller and it throws a 422 (Unprocessable Entity) error in console. Why my approach is wrong here and how can I print the error message then. Please help. Thank you in advance.
Your approach is actually not wrong, it's just, you need to catch the error response on your ajax request. Whereas, when Laravel validation fails, it throws an Error 422 (Unprocessable Entity) with corresponding error messages.
/**Ajax code**/
$.ajax({
type: "post",
url: "{{ url('/verifydata') }}",
data: {name: name, _token: token},
dataType: 'json', // let's set the expected response format
success: function(data){
//console.log(data);
$('#success_message').fadeIn().html(data.message);
},
error: function (err) {
if (err.status == 422) { // when status code is 422, it's a validation issue
console.log(err.responseJSON);
$('#success_message').fadeIn().html(err.responseJSON.message);
// you can loop through the errors object and show it to the user
console.warn(err.responseJSON.errors);
// display errors on each form field
$.each(err.responseJSON.errors, function (i, error) {
var el = $(document).find('[name="'+i+'"]');
el.after($('<span style="color: red;">'+error[0]+'</span>'));
});
}
}
});
/**Ajax code ends**/
On your controller
public function testAjax(Request $request)
{
// this will automatically return a 422 error response when request is invalid
$this->validate($request, ['name' => 'required']);
// below is executed when request is valid
$name = $request->name;
return response()->json([
'message' => "Welcome $name"
]);
}
Here's a better approach to validation:
In your controller:
public function testAjax(Request $request)
{
$this->validate($request, [ 'name' => 'required' ]);
return response("welcome ". $request->input('name'));
}
The framework then will create a validator for you and validate the request. It will throw a ValidationException if it fails validation.
Assuming you have not overriden how the validation exception is rendered here's the default code the built-in exception handler will run
protected function convertValidationExceptionToResponse(ValidationException $e, $request)
{
if ($e->response) {
return $e->response;
}
$errors = $e->validator->errors()->getMessages();
if ($request->expectsJson()) {
return response()->json($errors, 422);
}
return redirect()->back()->withInput($request->input())->withErrors($errors);
}
Again this is handled for you by the framework.
On the client side you should be able to do:
<script>
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#name").val();
var token = $("#token").val();
/**Ajax code**/
$.ajax({
type: "post",
url:"{{URL::to('/verifydata')}}",
data:{name:name, _token: token},
success:function(data){
//console.log(data);
$('#success_message').fadeIn().html(data);
},
error: function (xhr) {
if (xhr.status == 422) {
var errors = JSON.parse(xhr.responseText);
if (errors.name) {
alert('Name is required'); // and so on
}
}
}
});
/**Ajax code ends**/
});
});
</script>
best way for handle in php controller :
$validator = \Validator::make($request->all(), [
'footballername' => 'required',
'club' => 'required',
'country' => 'required',
]);
if ($validator->fails())
{
return response()->json(['errors'=>$validator->errors()->all()]);
}
return response()->json(['success'=>'Record is successfully added']);
The code for form validation in Vannilla Javascript
const form_data = new FormData(document.querySelector('#form_data'));
fetch("{{route('url')}}", {
'method': 'post',
body: form_data,
}).then(async response => {
if (response.ok) {
window.location.reload();
}
const errors = await response.json();
var html = '<ul>';
for (let [key, error] of Object.entries(errors)) {
for (e in error) {
html += `<li>${error[e]}</li>`;
}
}
html += '</ul>';
//append html to some div
throw new Error("error");
})
.catch((error) => {
console.log(error)
});
Controller
use Illuminate\Support\Facades\Validator;//Use at top of the page
$rules = [
'file' => 'image|mimes:jpeg,png,jpg|max:1024',
'field1' => 'required',
'field2' => 'required'
];
$validator = Validator::make($request->post(), $rules);
if ($validator->fails()) {
return response()->json($validator->errors(), 400);
}
session()->flash('flash', ['status' => 'status', 'message' => 'message']);
Jquery Code:
let first_name= $('.first_name').val();
let last_name= $('.last_name').val();
let email= $('.email').val();
let subject= $('.subject').val();
let message= $('.message').val();
$('.show-message').empty();
console.log('clicked');
$.ajax({
type : 'POST',
url : '{{route("contact-submit")}}',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {
first_name,
last_name,
email,
subject,
message,
},
success: function(data) {
console.log('data',data);
$('.show-message').html('Form Submitted');
},
error : function(data,data2,data3)
{
let response=data.responseJSON;
let all_errors=response.errors;
console.log('all_errors',all_errors);
$.each(all_errors,function(key,value){
$('.show-message').append(`<p>${value}</p>`);
});
}
});
Controller Code:
$validator=Validator::make($request->all(),[
'first_name'=>'required',
'last_name'=>'required',
'email'=>'required|email',
'subject'=>'required',
'message'=>'required',
]);
if($validator->fails())
{
return response()->json([
'success'=>false,
'errors'=>($validator->getMessageBag()->toArray()),
],400);
}
return response()->json([
'success'=>true,
],200);
See More Details at: https://impulsivecode.com/validate-input-data-using-ajax-in-laravel/
I can not solve this problem
$ _SESSION ['usernam'] is wrong on purpose to go to the else
Middleware.php
<?php
$auth = function ($response, $request, $next) {
if (isset($_SESSION['usernam']) and is_array($_SESSION['username'])) {
$response = $next($response, $request);
//$response = $response->withStatus(401)->write('403.phtml');
} else {
$response = $response->withStatus(401)->withHeader('Location', '403.phtml');
}
return $response;
};
Error:
Details
Type: Error
Message: Call to undefined method Slim\Http\Request::withStatus()
File: C:\Users\Geovane\Documents\Dropbox\www\tennis\src\middleware.php
Line: 9
Trace
routes.php
$app->map(['GET', 'POST'], '/login', function ($request, $response, $args) {
//var_dump($_SERVER); exit;
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$data = json_decode(filter_input(INPUT_POST, 'data'));
} else {
$data = 'data';
}
$table = $this->db->table('_users');
$login = $table->where([
'username' => $data->username,
'password' => $data->password
])->get();
if($login->count()){
$_SESSION['username'] = (array)$login->first();
return json_encode('ok');
} else {
return false;
}
});
app.js
$(function() {
$('#log-in').click(function(){
var data = {'username': $('#username').val(), 'password': $('#password').val()};
data = JSON.stringify(data);
$.ajax({
type : 'POST',
url : 'login',
dataType : 'json',
data : {data:data},
success: function(data){
if (data == 'ok'){
window.location.replace("athletes");
} else {
new PNotify({
title: 'Ooops!',
text: 'Username ou Password incorretos.',
type: 'danger',
styling: 'bootstrap3'
});
};
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
new PNotify({
title: 'Oh No!',
text: 'Erro! Por favor, contate o administrador.',
type: 'warning',
styling: 'bootstrap3'
});
}
});
});
});
The order of the parameters is wrong, its request response next.
Change
function ($response, $request, $next) {
to this:
function ($request, $response, $next) {
I am using an AJAX call to insert some data into MYSQL
JS code:
$("input.addtruck").click(function (event) {
event.preventDefault();
var user_id = $("input#user_id").val();
var numar = $("input#numar").val();
var serie = $("input#serie").val();
var marca = $("select#marca").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "aplicatie/add_truck",
dataType: 'json',
data: {user_id: user_id, numar: numar, serie: serie, marca: marca},
});
success: function (res) {
if (res)
{
jQuery("div#truck_form").hide();
jQuery("div#success").show();
} else {
jQuery("div#error").show();
}
}
});
Method used from controller:
function add_truck() {
$data = array(
'user_id' => $this->input->post('user_id'),
'marca' => $this->input->post('marca'),
'serie' => $this->input->post('serie'),
'numar' => $this->input->post('numar')
);
//Transfering data to Model
$this->trucks_model->insert_truck($data);
$data['confirmare'] = 'Data Inserted Successfully';
}
And method from models file
function insert_truck($data){
$this->db->insert('trucks', $data);
}
Basicly i need to hide the #truck_form and show #success if the data was inserted, or show #error .
You need to check data is inserted or not in database using affected_rows in model
Model
function insert_truck($data){
$this->db->insert('trucks', $data);
$afftectedRows=$this->db->affected_rows();
if($afftectedRows>0)
{
return TRUE;
}
else{
return FALSE;
}
}
YOu need to echo your result in Controller
Controller
function add_truck() {
$data = array(
'user_id' => $this->input->post('user_id'),
'marca' => $this->input->post('marca'),
'serie' => $this->input->post('serie'),
'numar' => $this->input->post('numar')
);
//Transfering data to Model
$res=$this->trucks_model->insert_truck($data);
if($res){
$data['msg'] = 'true';
}else{
$data['msg'] = 'false';
}
echo json_encode($data);
}
Ajax
success: function (res) {
if (res.msg=='true')
{
jQuery("div#truck_form").hide();
jQuery("div#success").show();
} else {
jQuery("div#error").show();
}
}
You can create an array of response like this. As you ajax dataType is json so you will send response in json.
function add_truck() {
$response = array();
$data = array(
'user_id' => $this->input->post('user_id'),
'marca' => $this->input->post('marca'),
'serie' => $this->input->post('serie'),
'numar' => $this->input->post('numar')
);
//Transfering data to Model
$check_insert = $this->trucks_model->insert_truck($data);
if(check_insert){
$response['status'] = 'true';
$response['msg'] = 'Data Inserted Successfully';
}else{
$response['status'] = 'false';
$response['msg'] = 'Problem in data insertion';
}
echo json_encode($response);
die;
}
and then in ajax :
success: function (res) {
if (res.status == 'true')
{
jQuery("div#truck_form").hide();
jQuery("div#success").show();
} else {
jQuery("div#error").show();
}
}
error: function (result) {
console.log('Problem with ajax call insert');
}
And method from models file
Just to ensure row inserted return insert_id
function insert_truck($data){
$this->db->insert('trucks', $data);
$insert_id = $this->db->insert_id();
return $insert_id;
}
In AJAX
<script type="text/javascript">
$("#addtruck").click(function (event) { // change
event.preventDefault();
var user_id = $("#user_id").val(); // remove input(input#user_id)
var numar = $("#numar").val();
var serie = $("#serie").val();
var marca = $("#marca").val();
$.ajax(
{
type: "post",
dataType: 'json',
url: "<?php echo base_url(); ?>aplicatie/add_truck",
data: {user_id: user_id, numar: numar, serie: serie, marca: marca},
}
);
success: function (res) {
if (res == TRUE)
{
jQuery("truck_form").hide(); // remove div on here
jQuery("success").show(); // remove div on here
} else {
jQuery("error").show(); // remove div on here
}
}
});
</script>
In HTML
Button should be
<input type="button" id="addtruck" value="Add New Truck">
and form action="" should be removed
In Controller
function add_truck() {
$data = array(
'user_id' => $this->input->post('user_id'),
'marca' => $this->input->post('marca'),
'serie' => $this->input->post('serie'),
'numar' => $this->input->post('numar')
);
# passing to model
$res = $this->trucks_model->insert_truck($data);
# Check return value on $res
if($res == TRUE)
{
$data['msg'] = 'true';
}
else
{
$data['msg'] = 'false';
}
echo json_encode($data);
}
In Model
function insert_truck($data){
$this->db->insert('trucks', $data);
$row_affect = $this->db->affected_rows();
if($row_affect > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
You can add error after success to know ajax called successfully or not.
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "aplicatie/add_truck",
dataType: 'json',
data: {user_id: user_id, numar: numar, serie: serie, marca: marca},
success: function (res) {
if (res)
{
jQuery("div#truck_form").hide();
jQuery("div#success").show();
} else {
jQuery("div#error").show();
}
},
error: function (xhr,err) {
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
Just remove event.preventDefault() from the code and use success like below
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "aplicatie/add_truck",
dataType: 'json',
data: {user_id: user_id, numar: numar, serie: serie, marca: marca},
success : functionName
});
function functionName(){
//your code for success
}
I am working with Laravel 4 and I want to perform validation with Ajax. I have 2 main problems:
1. The URL at Ajax is static, which means that if I have my app online I should put the URL for online and locally doesn't works
2. my route is insur_docs/{id} how should be URL for this?
jQuery('form#insur_docs_update').submit(function()
{
jQuery.ajax({
url: "http://localhost:8080/insur_docs/{id}", //my url I don't know how to put it
type: "post",
data: jQuery('form#insur_docs_update').serialize(),
datatype: "json",
beforeSend: function()
{
jQuery('#ajax-loading').show();
jQuery(".glyphicon-warning-sign").hide();
}
})
.done(function(data)
{
$('#validation-div').empty()
if (data.validation_failed === 1)
{
var arr = data.errors;
jQuery.each(arr, function(index, value)
{
if (value.length !== 0)
{
$("#validation-div").addClass('alert alert-danger');
document.getElementById("validation-div").innerHTML += '<span class="glyphicon glyphicon-warning-sign"></span>' + value + '<br/>';
}
});
jQuery('#ajax-loading').hide();
}
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
return false;
});
routes.php
Route::get('insur_docs/{id}', 'Insur_DocController#edit');
controller
public function update($id) {
Input::flash();
$data = [
"errors" => null
];
$rules = array(
"ownership_cert" => "required",
"authoriz" => "required",
"drive_permis" => "required",
"sgs" => "required",
"tpl" => "required",
"kasko" => "required",
"inter_permis" => "required",
);
$validation = Validator::make(Input::all(), $rules);
if ($validation->passes()) {
$car_id = DB::select('select car_id from insur_docs where id = ?', array($id));
$data = InsurDoc::find($id);
$data->ownership_cert = Input::get('ownership_cert');
$data->authoriz = Input::get('authoriz');
$data->drive_permis = Input::get('drive_permis');
$data->sgs = Input::get('sgs');
$data->tpl = Input::get('tpl');
$data->kasko = Input::get('kasko');
$data->inter_permis = Input::get('inter_permis');
$data->save();
return Redirect::to('car/' . $car_id[0]->car_id);
} else {
if (Request::ajax()) {
$response_values = array(
'validation_failed' => 1,
'errors' => $validation->errors()->toArray()
);
return Response::json($response_values);
}
}
}
Use laravel's url generator helper to create your form's action:
<form action="{{ URL::action('Insur_DocController#edit', $id) }}" method="post">
You can access it in your javascript:
jQuery('form#insur_docs_update').submit(function()
{
var url = $(this).attr("action");
jQuery.ajax({
url: url,
type: "post",
data: jQuery('form#insur_docs_update').serialize(),
datatype: "json",
beforeSend: function()
{
jQuery('#ajax-loading').show();
jQuery(".glyphicon-warning-sign").hide();
}
});
}
EDIT
You're second problem is that you're redirecting in response to the ajax call, and that does not redirect the page. You'll need to return the url and do the redirect in javascript like this.
Controller:
return Response::json(["redirect_to" => 'car/' . $car_id[0]->car_id]);
JS (just the relevant part):
.done(function(data)
{
$('#validation-div').empty()
if (data.validation_failed === 1)
{
// your code
} else {
window.location = data.redirect_to;
}
})
var myUrlExtension = "whatever.php"
and inside the ajax
url: "http://localhost:8080/insur_docs/" + myUrlExtension