Ajax retrieving errors not working Laravel - php

I'm trying to retrieve errors when a user fills a form submitted using ajax. I'm following this tutorial. I'm not getting the result expected despite the logic I think should be right.
Here is my blade view code :
#extends('layouts.layout')
#section('title','Soumettre thématique')
#section('content')
<body>
<div class="container_fluid">
<div class="row">
<div class="alert alert-danger print-error-msg" style="display: none;">
#if($errors->any())
<ol style="color: red">
#foreach($errors->all() as $error)
<li>
{{$error}}
</li>
#endforeach
</ol>
#endif
</div>
</div>
</div>
<form method="POST" action=" {{route('themes.store')}} ">
#csrf
<!-- Intitulé du thème -->
<input type="text" name="intitule" id="intitule" placeholder="Intitulé du thème" required><br>
<!-- Catégorie -->
<select name="categorie" required>
<option value="">-- Catégorie --</option>
<option value="web">Développement web</option>
<option value="appMobile">Programmation application mobile</option>
<option value="secure">Sécurisation</option>
<option value="other">Autre</option>
</select> <br>
<!-- Filière désirée -->
<input type="checkbox" name="filiere[]" id="GL" value="GL" required>
<label for="GL">Génie Logiciel</label><br>
<input type="checkbox" name="filiere[]" id="SI" value="SI" required>
<label for="SI">Sécurité Informatique</label><br>
<input type="checkbox" name="filiere[]" id="IM" value="IM" required>
<label for="IM">Internet et Multimédia</label><br>
<input type="checkbox" name="filiere[]" id="SIRI" value="SIRI" required>
<label for="SIRI">Systèmes d'Information et Réseaux Informatiques</label><br>
<!-- Descriptif -->
<textarea name="description" id="description" placeholder="Description de la thématique" required>{{old('description')}} </textarea><br>
<input type="submit" name="submit" id="submit" value="Ajouter">
<span id="error-message" class="text-danger"></span>
<span id="success-message" class="text-success"></span>
</form>
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<script type="text/javascript">
$(function (){
var itsChecked = null;
$('input[type=checkbox]').on('click', function(){
if($('input[type=checkbox]:checked').length > 0){ //S'il y a au moins 1 ([...].length > 0) ckecked
// alert('At least one is checked');
$('#GL').removeAttr("required");
$('#SI').removeAttr("required");
$('#IM').removeAttr("required");
$('#SIRI').removeAttr("required");
}
else if(!$('input[type=checkbox]:checked').length > 0){ //S'il n'y a aucun checked (!(at least 1)>0)
// alert('None is checked');
$('#GL').attr('required','');
$('#SI').attr('required','');
$('#IM').attr('required','');
$('#SIRI').attr('required','');
}
});
$('#submit').on('click',function(e){
e.preventDefault();
var _token = $("input[name='_token']").val();
var intitule = $("input[name='intitule']").val();
var categorie = $("select[name='categorie']").val();
var filiereChecked = [];
$.each($("input[type='checkbox']:checked"), function(){
filiereChecked.push($(this).val());
});
var filiere = filiereChecked.join(", ");
var filiere = filiere.toString();
$.ajax({
url: "{{route('themes.store')}}",
type: 'POST',
data: {
_token:_token,
intitule:intitule,
categorie:categorie,
filiere:filiere
},
success: function(data){
if($.isEmptyObject(data.error)){
alert(data.success);
}
else{
// console.log(data.error);
printErrorMsg(data.error);
}
}
});
});
function printErrorMsg (msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display','block');
$.each( msg, function( key, value ) {
$(".print-error-msg").find("ul").append('<li>'+value+'</li>');
});
}
});
</script>
</body>
#endsection
The controller store function :
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validator = Validator::make($request->all(),[
'intitule' => 'unique:themes,intitule'
]);
$theme = new Theme;
$theme->intitule = $request->input('intitule');
$theme->description = $request->input('description');
$theme->categorie = $request->input('categorie');
$request->merge([
'filiere' => implode(',', (array) $request->get('filiere'))
]);
$theme->filiereDesiree = $request->input('filiere');
$theme->save();
if ($validator->passes()) {
return response()->json(['success'=>'Added new records.']);
}
return response()->json(['error'=>$validator->errors()->all()]);
}
The problem is I'm not getting a message at all, either success or error may it be. I don't know where I'm doing wrong there.
P.S:
I've already used Ajax to submit this form. I did it using XMLHttpRequest object. The problem was I do not know how to use the 422 status to return errors using this XHR object. I've looked for it but found nothing really helpful.. So I changed this method to use here the ajax() jquery function which seems to be more used. Still not getting the messages.. It's the first time I try to manage the validation errors using Ajax. Your help would be very welcome

You can use this on your controller.
return response()->json(array('errors'=>$validator->getMessageBag()->toArray(),));
and in javascript try to use this one
success: function(data){
if(data.error){
printErrorMsg(data.error);
}
else{
alert(data.success);
}
}
ajax code
$.ajax({
url: "{{route('themes.store')}}",
type: 'POST',
data: {
_token:_token,
intitule:intitule,
categorie:categorie,
filiere:filiere
},
success: function(data){
if(data.error){
printErrorMsg(data.error);
}
else{
alert(data.success);
}
}
});
Controller
public function store(Request $request)
{
$validator = \Validator::make($request->all(),[
'intitule' => 'unique:themes,intitule'
]);
if ($validator->fails()) {
return response()->json(array('error'=>$validator->getMessageBag()->toArray(),));
}
$theme = new Theme;
$theme->intitule = $request->input('intitule');
$theme->description = $request->input('description');
$theme->categorie = $request->input('categorie');
$request->merge([
'filiere' => implode(',', (array) $request->get('filiere'))
]);
$theme->filiereDesiree = $request->input('filiere');
$theme->save();
return response()->json(array('success'=>'Added new records.',));
}

Oops this is my fault... I've just figured why it was not working. I've placed this in my blade view
#if($errors->any())
<ol style="color: red">
#foreach($errors->all() as $error)
<li>
{{$error}}
</li>
#endforeach
</ol>
#endif
instead of the <ul> </ul> tags that the javascript code is looking for to output the errors. Thank you all

You can use Laravel Request for your validation.
php artisan make:request ThemeCreateRequest
Controller
use App\Http\Request\ThemeCreateRequest
public function store(ThemeCreateRequest $request)
{
$theme = new Theme;
$theme->intitule = $request->input('intitule');
$theme->description = $request->input('description');
$theme->categorie = $request->input('categorie');
$request->merge([
'filiere' => implode(',', (array) $request->get('filiere'))
]);
$theme->filiereDesiree = $request->input('filiere');
$theme->save();
if ($validator->passes()) {
return response()->json(['success'=>'Added new records.']);
}
return response()->json(['error'=>$validator->errors()->all()]);
}
App\Http\Request\ThemeCreateRequest.php
public function authorize()
{
return true;
}
public function rules()
{
return [
'intitule' => 'required|unique',
];
}

Related

how to send data from Blade view to controller in laravel to preform a post request

I am trying to favorite and unfavorite posts and insert it in favorites table if clicked and if clicked again it deletes it from favorites table i put my routes in web.php file
the functions in the controller which should be called in the route are not called i insert there dd() method to test it so i am guessing the problem is in the form action and not sending the data
<body>
...
#foreach ($posts as $post)
<div class="column">
#if ($post->showstar == true)
<form action="/favorites/delete" method="post">
<span class="foo fa fa-star checked"></span>
</form>
#endif
<h2>{{$post->title}}</h2>
<img src={{$post->url}} >
</div>
#endforeach
</body>
<script>
$(document).ready(function () {
$("form").on("click", ".foo", function () {
if ($(this).hasClass("checked")) {
$(this).removeClass("checked");
} else {
$(this).addClass("checked");
}
});
});
</script>
Controller:
class FavoritesController extends Controller
{
public function index()
{
return view('Favorites', ['favs' => Favorite::where('user_id', '1')->get()]);
}
public function view(Request $request)
{
dd("hello");
$fav = new Favorite();
$fav->user_id = $request->get('userid');
$fav->post_id = $request->get('postid');
$fav->save();
}
public function delete(Request $request)
{
dd("bye");
$fav = new Favorite();
$dfav = $fav->where('id', $request->id);
$dfav->delete();
return view('favorites');
}
public function fetch(Request $request)
{
$fav = new Favorite();
$favs = $fav->where('user_id', $request->user_id);
return view('favorites', compact('favs'));
}
}
Routes:
Route::post('/favorites', 'FavoritesController#view');
Route::post('/favorites/delete', 'FavoritesController#delete');
Route::post('/favorites/fetch', 'FavoritesController#fetch');
You could always try the plain and simple html form submit.
<form action="/favorites/delete" method="post">
#csrf
<input type="hidden" name="id" value="{{ $post->id }}">
<button>
<span class="foo fa fa-star checked"></span>
</button>
</form>
This way you can send the hidden input, post id in your case, to the controller and it will delete it.
You need a similar function ajax, to send data to a controller:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url:'youUrl',
data:{'youData':"YourValueData"},
type:'post',
success: function (response) {
alert(response);
},
error: function(x,xs,xt){
alert(x);
}
});

Laravel + Vue unable to save data to my database

I'm trying to save data from my vue component to database but it will just say 500 (internal server error ) on my dev tools.
I tried one by one deleting my code to see where it fails everything will work fine until the I added the save(); function to my database
Vue Component
<template>
<form #submit.prevent="submit">
<div class="form-group">
<input type="text" class="form-control" name="name" id="name" v-model="fields.name" />
<div v-if="errors && errors.name" class="text-danger">{{ errors.name[0] }}</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="post" id="post" v-model="fields.post" />
<div v-if="errors && errors.post" class="text-danger">{{ errors.post[0] }}</div>
</div>
<button type="submit" class="btn btn-primary">Send message</button>
<div v-if="success" class="alert alert-success mt-3">
Message sent!
</div>
</form>
Vue COmponent Script
<script>
export default {
data() {
return {
fields: {},
errors: {},
success: false,
loaded: true,
}
},
methods: {
submit() {
if (this.loaded) {
this.loaded = false;
this.success = false;
this.errors = {};
axios.post('/adminquickannc', this.fields).then(response => {
this.fields = {}; //Clear input fields.
this.loaded = true;
this.success = true;
}).catch(error => {
this.loaded = true;
if (error.response.status === 422) {
this.errors = error.response.data.errors || {};
}
});
}
},
},
}
</script>
Controller // My controller code to save it on the database
use App\Post;
use Illuminate\Http\Request;
public function store(Request $request)
{
// Validation
$this->validate($request, [
'name' => 'required',
'post' => 'required|max:500|min:10'
]);
// Variables we needed
$name = $request->input('name');
$post = $request->input('post');
// Saving the post to database
$post = new Post();
$post->name = $name;
$post->post = $post;
$post->save();
}
I expect this code to save data to my database, is this way of saving it safe? and can you guys give me tools where errors like this can be more specific so i can understand where it fails Thank you in advance guys!

Codeigniter form validation return false on ajax request

Before I start, sorry for my English. i am developing a website using CI on Backend. And i want to make a registration system without refreshing the page. If i try with post form submit i got no error and everything went good. but when I try using with ajax request, I can't use form validation because form validation return false and validation_errors is empty. if I disable form validation, ajax request works well. here is my controller and ajax request. Please help me.
User.php (My Controller)
public function register(){
$this->load->library('form_validation');
$this->form_validation->set_rules('email_kyt', 'Email', 'is_unique[users.email]');
$this->form_validation->set_rules('username_kyt', 'Kullanici', 'is_unique[users.username]');
if($this->form_validation->run() == FALSE) {
$data = json_encode(array('status'=> false,'info'=>validation_errors()));
}else {
if($this -> input -> is_ajax_request()){
$userData = array(
'email' => strip_tags($this->input->get('email_kyt')),
//bla bla,
);
if ($this->User_model->form_insert($userData) == true) { //this method works perfectly.
$data = json_encode(array('status' => true,'info' => 'Successfully Registered'));
} else {
$data = json_encode(array('status' => false,'info'=>'The Error Occurred During Registration'));
}
}else{
$data = json_encode(array('status'=> false,'info'=>'This is not Ajax request'));
}
}
echo $data;
}
}
And here is my ajax request in js
$(document).ready(function(){
$('#btn_register').on('click',function (e) {
$('form[name=register-form]').unbind("submit");
$('form[name=register-form]').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'get',
url: url + 'User/register', //url is correct i tested without form validation
data: $('#register-form').serialize(),
dataType: "json",
success: function (data) {
if (data.status == true) {
alert(data.info);
window.location.reload();
json= [];
} else if (data.status == false) {
$('#span_validate').html(data.info);
json= [];
}
}
});
});
});
});
edit: and here is my form:
<!-- Register Form -->
<?php echo form_open(base_url('index.php/User/register'),array('id' => 'register-form','name' => 'register-form')); ?>
<?php echo form_hidden($this->security->get_csrf_token_name(), $this->security->get_csrf_hash()); ?>
<div class="md-form">
<input type="text" id="name_kyt" name="name_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="name_kyt" >Name</label>
</div>
<div class="md-form">
<input type="text" id="surname_kyt" name="surname_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="surname_kyt" >Surname</label>
</div>
<div class="md-form">
<input type="text" id="username_kyt" name="username_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="username_kyt" > Username </label>
</div>
<div class="md-form">
<input type="email" id="email_kyt" name="email_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="email_kyt" >Email</label>
</div>
<div class="md-form">
<input type="password" id="password_kyt" name="password_kyt" class="form-control" data-toggle="popover" data-trigger="focus" data-content="...">
<label for="password_kyt" >Password</label>
</div>
<div class="md-form">
<input type="password" id="password_confirm" name="password_onay" class="form-control">
<label for="password_confirm" >Password Confirm</label>
</div>
<div class="form-group text-center">
<div class="row">
<div class="col-sm-10 col-sm-offset-3 mr-auto ml-auto">
<input type="submit" name="btn_register" id="btn_register" tabindex="4" class="btn btn-register mr-auto ml-auto" value="Register">
<p><span id="span_validate" class="label label-default mr-auto ml-auto"></span></p>
</div>
</div>
</div>
<!-- End of Register Form -->
<?php echo form_close(); ?>
Please refer below example to validate a form in CodeIgniter using ajax call.
1. ajax code.
$(document).ready(function(){
$('#btn_register').on('click',function (e) {
$('form[name=register-form]').unbind("submit");
$('form[name=register-form]').submit(function (e) {
e.preventDefault();
var formData = $("#register-form").serialize();
$.ajax({
type: 'get',
url: url + 'User/register',
data: formData,
success: function (data) {
if (data.status == true) {
alert(data.info);
window.location.reload();
json= [];
} else if (data.status == false) {
$('#span_validate').html(data.info);
json= [];
}
}
});
});
});
});
2. Controller code :
Load form_validation library and form helper
$this->load->library('form_validation');
$this->load->helper('form');
Now write your controller as ...
public function register(){
$this->load->library('form_validation');
$this->load->helper('form');
$this->form_validation->set_rules('email_kyt', 'Email', 'is_unique[users.email]');
$this->form_validation->set_rules('username_kyt', 'Kullanici', 'is_unique[users.username]');
if($this->form_validation->run() == FALSE) {
echo $data = json_encode(array('status'=> false,'info'=>validation_errors())); die;
}else {
if($this -> input -> is_ajax_request()){
$userData = array(
'email' => strip_tags($this->input->get('email_kyt')),
//bla bla,
);
if ($this->User_model->form_insert($userData) == true) { //this method works perfectly.
echo $data = json_encode(array('status' => true,'info' => 'Successfully Registered')); die;
} else {
echo $data = json_encode(array('status' => false,'info'=>'The Error Occurred During Registration')); die;
}
}else{
echo $data = json_encode(array('status'=> false,'info'=>'This is not Ajax request')); die;
}
}
}
}
I have solved this problem. Form validation only works with post method. If you use get method it won't work.

Update DB::table from passed object of array in laravel

In laravel, I'm trying to update several tables and rows. i have items that are to be received and checked by 2 different users.
in my show.blade.php, i have this verify button and submit button depending on the user.
#if (($current_user_id != $saved_receiver_id) && ($saved_receiver_id != $not_yet_received))
<div class="row padder m-b">
<div class="col-md-12">
<label for="received_by" class="pull-left" >Received by:</label> <span class="fa"></span>
<input type="hidden" name="receiver_id" value="{{ $saved_receiver_id }}" >{{ $receiver_username }}</input>
</div>
</div>
<div class="row padder m-b">
<div class="col-md-12">
<label for="received_date" class="pull-left" >Received date:</label> <span class="fa"></span>
<input type="hidden" name="received_date" value="{{ $received_date }}" >{{ $received_date }}</input>
</div>
</div>
<input type="hidden" name="purchase_orders_id" value="{{ $purchase_order_number }}">
<input type="hidden" name="checker_id" value="{{ $current_user_id }}">
<div class="row padder m-b">
<div class="col-md-12">
<label for="final_checker_remarks" class="pull-left" >Final Remarks</label>
<textarea class="form-control col-md-12" name="final_checker_remarks" value="{{ $final_checker_remarks }}" id="final_checker_remarks">{{ $final_checker_remarks }}</textarea>
</div>
</div>
<br />
<div class="row">
<div class="col-md-12">
<button type="button" class="pull-right btn btn-success btn-sm submit-btn" id="update-form-submit" data-action="verified">Verified</button>
</div>
</div>
#else
<div class="pull-right">
<div class="btn-group">
<button type="button" class="btn btn-info btn-sm submit-btn" id="update-form-submit" data-action="submit">Submit List</button>
</a>
</div>
#endif
now in my ReceivesController.php, i have this postUpdate function,
public function postUpdate(Request $request)
{
if (! $request->ajax()) {
abort(404);
}
$items = json_decode($request->items);
$action = json_decode($request->action);
if(!count($items) && !count($items->purchase_item_id)){
return false;
}
$cnt = count($items->purchase_item_id);
// Receiver Submit function
if ($action == "submit") {
// Saves the received id of the one who received to purchase order table
DB::table('purchase_orders')
->where('id', $items->purchase_orders_id)
->update([
'receiver_id' => $items->receiver_id,
]);
// Saves the quantity received and receiver remarks to purchase items table
for($i=0; $i<$cnt; $i++){
DB::table('purchase_items')
->where('id', $items->purchase_item_id[$i])
->update([
'quantity_received' => $items->quantity_received[$i],
'receiver_remarks' => $items->receiver_remarks[$i],
]);
}
// Items Received Success Message
$message = 'Items Received';
}
// QA or Checker Finalize function
else {
// Saves the checker id, and final checker remarks of the one who made the QA to purchase order table
DB::table('purchase_orders')
->where('id', $items->purchase_orders_id)
->update([
'checker_id' => $items->checker_id,
'final_checker_remarks' => $items->final_checker_remarks,
]);
// Saves the quality received and checker remarks to purchase items table
for($i=0; $i<$cnt; $i++){
$quality_received = $items->quality_received;
if(is_array($items->quality_received)){
$quality_received = $items->quality_received[$i];
}
$checker_remarks = $items->checker_remarks;
if(is_array($items->checker_remarks)){
$checker_remarks = $items->checker_remarks[$i];
}
$quantity_received = $items->quantity_received;
if(is_array($items->quantity_received)){
$quantity_received = $items->quantity_received[$i];
}
$receiver_remarks = $items->receiver_remarks;
if(is_array($items->receiver_remarks)){
$receiver_remarks = $items->receiver_remarks[$i];
}
DB::table('purchase_items')
->where('id', $items->purchase_item_id[$i])
->update([
'quality_received' => $quality_received,
'checker_remarks' => $checker_remarks,
'quantity_received' => $quantity_received,
'receiver_remarks' => $receiver_remarks,
]);
// Increments or Adds the quantity received to items table
DB::table('items')
->where('purchase_items.id', $items->purchase_item_id[$i])
->join('purchase_items', 'items.id', '=', 'purchase_items.item_id')
->increment('items.measurement', $items->quantity_received[$i]);
}
/ / Items Finalized Success Message
$message = 'Items Verified';
}
// Returns Success Message
return response()->json([
'success' => true,
'message' => $message
]);
}
Now my problem is only the first letter of the word that is typed in the input area are being saved, and in others they are not saved, however, in other, it can be saved. I know its weird, but i cant find which part of my codes is doing such result, what is it that i need to do for me to update my tables correctly? Thanks in advance for the help.
Update: Here is my receive-form-function.js
/* ========================================================================
* Initialize Pages
* ======================================================================== */
$(initialPages);
/* ========================================================================
* Major function
* ======================================================================== */
/* ==== function to init this page === */
function initialPages($) {
// if($('#receives-list-table').length){
// DataTables("#receives-list-table", "receives");
// }
if($('#receiveItems-list-table').length){
$("#receiveItems-list-table").DataTable({
responsive: true,
ordering: false,
});
}
$('#update-form-submit').on('click', function(){
var action = $(this).data('action');
updateReceiveItem(action);
});
clearInputs();
}
/* === dataTables === */
function DataTables(selector, controller) {
$(selector).DataTable({
responsive: true,
processing: true,
serverSide: true,
ajax: url+'/'+controller+'/paginate'
});
}
function updateReceiveItem(action){
loadingModal('show','Updating ....');
ajaxCsrfToken();
var data = $('#receiveItems_id').serializeArray();
data = JSON.stringify(data);
// data = JSON.parse(data);
data = JSON.stringify($('#receiveItems_id').serializeObject());
// data = $('#receiveItems_id').serializeObject();
$.ajax({
url: url+'/receives/update',
type: 'post',
data: {'items':data, 'action': action},
dataType: 'json',
complete: function() {
loadingModal('close');
},
error: function(result) {
},
success: function(result) {
successAlert('#receiveItems-result', result.message);
// if (result.success) {
// $('input, select, textarea').attr('disabled', true);
// } else {
// alert(result.message);
// }
}
});
console.log(data);
return false;
}
/**
* Use to format serialize data and convert to json data
*
* Usage: JSON.stringify($('form').serializeObject())
*/
$.fn.serializeObject = function() {
var o = Object.create(null),
elementMapper = function(element) {
element.name = $.camelCase(element.name);
return element;
},
appendToResult = function(i, element) {
var node = o[element.name];
if ('undefined' != typeof node && node !== null) {
o[element.name] = node.push ? node.push(element.value) : [node, element.value];
} else {
o[element.name] = element.value;
}
};
$.each($.map(this.serializeArray(), elementMapper), appendToResult);
console.log(o);
return o;
};
my $.fn.serializeObject = function() above seems to have the bug, i tried using another $.fn.serializeObject = function(), and it gave me the json object that i want. here is the $.fn.serializeObject = function() that i am using now.
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};

PHP Laravel 4.2 ajax post return null or empty

I try to post data to laravel controller using ajax, but still get response null. My achievement is to post form data and return error message or success message.
I'm newbie in ajax and laravel framework please help me to solve the problem.
Here is the meta tag header:
<meta name="_token" content="{{ csrf_token() }}">
Here is the html form :
{{ Form::open(['id'=>'testimonial_form','url'=>URL::action("processing-give-testimonial"),'method'=>'POST']) }}
{{ Form::hidden('_method', 'PUT') }}
<div class="row marginbot-20">
<div class="col-md-6 xs-marginbot-20">
{{ Form::text('name',null, ['class'=>'form-control input-lg','placeholder'=>'Enter Name','id'=>'name']) }}
</div>
<div class="col-md-6">
{{ Form::email('email',null, ['class'=>'form-control input-lg','id'=>'email','placeholder'=>'Enter email','id'=>'email']) }}
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<select name="subject" id="subject" class="form-control" require="required">
<option value="ask">Ask Question / Information</option>
<option value="testimonial">Give Feedback / Testimonial</option>
</select>
</div>
<div class="form-group">
{{ Form::textarea('message',null,['id'=>'message','class'=>'form-control','rows'=>'4','cols'=>'25','placeholder'=>'message','id'=>'message']) }}
</div>
<!-- {{ Form::submit('Send Message',['id'=>'btnContactUs','class'=>'btn btn-skin btn-lg btn-block']) }} -->
{{ Form::button('Submit', ['class'=>'btn btn-skin btn-lg btn-block','id'=>'click']) }}
</div>
</div>
{{ Form::close() }}
Here is the ajax code :
$(function() {
$.ajaxSetup({
headers: {
'X-XSRF-Token': $('meta[name="_token"]').attr('content')
}
});
});
$(document).ready(function() {
$('#click').click(function() {
var formData = {
name : $('#name').val(),
email : $('#email').val(),
subject : $('#subject').val(),
message : $('#message').val(),
};
$.ajax({
type : "POST",
url : "{{ URL::action('processing-give-testimonial') }}",
data : formData,
beforeSend: function () {
alert('sure?');
},
success: function(data) {
console.log(data);
},
error: function() {
console.log('error');
}
});
});
});
Here is the controller :
public function create()
{
$inputs = array(
'name' =>Input::get('name'),
'email' =>Input::get('email'),
'subject' =>Input::get('subject'),
'message' =>Input::get('message')
);
//return "we reached here";
return Response::json("success");
/*if(Request::ajax()) {
return Response::json('success', 200);
} else {
return Response::json('failed', 400);
}*/
/* if(Request::ajax()) {
$data = Input::get('email');
//print_r($data);die;
if ($data != '') return Response::json('success',200);
else return Response::json('failed',400);
}*/
/*
$input = Input::get('name');
//$input = Input::get('_token');
if ($input == '') {
return Response::json('failed',400);
}
else {
return Response::json('success',200);
}*/
//if(!empty($input)) return Response::json(['data'=>'success']);
//else return Response::json('data',$input);
}
Here is the my route :
Route::post('give-testimonial',['uses'=>'TestimonialController#store','as'=>'processing-give-testimonial']);
Here is the filter.php :
Route::filter('csrf', function() {
$token = Request::ajax() ? Request::header('X-XSRF-Token') : Input::get('_token');
if (Session::token() != $token) {
throw new Illuminate\Session\TokenMismatchException;
} });
I'm guessing your routing is wrong. Try changing this route:
Route::post('give-testimonial',['uses'=>'TestimonialController#store','as'=>'processing-give-testimonial']);
to this:
Route::post('give-testimonial',['uses'=>'TestimonialController#create','as'=>'processing-give-testimonial']);

Categories