I am trying to submit a form using ajax in Laravel 5.5
The problem is the page is refreshing and not submitting data in the database. I need to store data in the database without refreshing the page.
Here is my code:
Controller
public function new_timing_table(Request $request)
{
if (Request::ajax()) {
$timing_tables = new Timing_Table;
$timing_tables->timing_tables_name = $request->timing_tables_name;
$timing_tables->save();
$msg = "yes";
} else {
$msg = "yes";
}
return ['msg'=> $msg];
}
View
<form id="timeForm" class="form-horizontal form-material" >
<div class="form-group">
{{ csrf_field() }}
<div class="col-md-12 m-b-20">
<label> Table Name</label>
<input type="text" id="timing_tables_name" class="form-control"
name="timing_tables_name" />
</div>
<div class="modal-footer">
<input type="button" value="Replace Message" id='btnSelector'>
</div>
</div>
</form>
Ajax script
const xCsrfToken = "{{ csrf_token() }}";
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': xCsrfToken
}
});
jQuery(document).ready(function() {
jQuery('#btnSelector').click(function(e) {
event.preventDefault();
getMessage();
});
});
var getMessage = function() {
var timing_tables_name = $("input[name=timing_tables_name]").val();
$.ajax({
type: 'post',
url: '/new_timing_table',
dataType: 'json', //Make sure your returning data type dffine as json
data: timing_tables_name,
//data:'_token = <php echo csrf_token() ?>',
success: function(data) {
console.log(data); //Please share cosnole data
if (data.msg) //Check the data.msg isset?
{
$("#msg").html(data.msg);
}
}
});
}
Router
Route::post('/new_timing_table','Timing_TableControoler#new_timing_table');
You got a typo or a mistake in your script.
jQuery('#btnSelector').click(function(e){
// An error here - it should be e.preventDefault();
event.preventDefault();
getMessage();
});
My code is working now after adding beforeSend: function (request) in Ajax script
var getMessage = function(){
var timing_tables_name = $("#timing_tables_name").val();
console.log(timing_tables_name);
$.ajax({
type:'GET',
url:'/new_timing_table', //Make sure your URL is correct
dataType: 'json', //Make sure your returning data type dffine as json
data:
{
timing_tables_name
},
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-
token']").attr('content'));
},
success:function(data){
console.log(data); //Please share cosnole data
if(data.msg) //Check the data.msg isset?
{
$("#msg").html(data.msg); //replace html by data.msg
}
}
});
}
and editing the controller to be simple as this one
public function new_timing_table(Request $request){
$timing_tables = new Timing_Table;
$timing_tables->timing_tables_name = $request->timing_tables_name;
$timing_tables->save();
$msg = "This is a simple message.";
return ['msg'=> $msg];
}
Thank you all for your help
Related
I have a form on my front-end and when the submit button is clicked I want to send the details to my get-emp.php file without page reload.
The code looks like this:
index.html
<form class="form-emp-details hide" action="">
<div class="form-group">
<label for="">First name:</label>
<input type="text" class="form-control input-emp-firstname" name="input_emp_firstname">
</div>
<div class="form-group">
<label for="">Last name:</label>
<input type="text" class="form-control input-emp-lastname" name="input_emp_lastname">
</div>
<div class="form-group">
<label></label>
<button type="submit" class="btn btn-default btn-submit-1" name="submit_emp_details">Save</button>
</div>
</form>
custom.js
$(".form-emp-details").("submit", function(e) {
var input_first_name = $(".input-emp-firstname").val();
$.ajax({
type: "POST",
url: "get-emp.php",
data: {
input_emp_firstname:input_first_name,
},
success: function(data) {
console.log(data)
},
error: function(xhr,status,error) {
console.log(error);
}
});
});
get-emp.php
if(isset($_POST['submit_emp_details'])) {
$firstname = $_POST['input_emp_firstname'];
echo $firstname;
}
I want to display the submitted form data on get-emp.php file but it seems that I am not able to detect the submitted button and echo the form data on.
My goal is to capture all form data with a single request variable or identifier $_POST['submit_emp_details']
Any help is greatly appreciated. Thanks
$("#MyformId").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(),
success: function(data)
{
// success..
}
});
});
You passing the POST data of firstname and lastname by:
input_emp_firstname
input_emp_lastname
so, you need to change the $_POST['submit_emp_details'] to $_POST['input_emp_firstname'] on file get-emp.php to
<?php
if(isset($_POST['input_emp_firstname'])) {
$firstname = $_POST['input_emp_firstname'];
echo $firstname;
}
Edit 2:
$.ajax({
type: "POST",
url: "get-emp.php",
cache: false,
data: {
submit_emp_details: {
input_emp_firstname:input_first_name,
input_emp_lastname:input_last_name
}
},
success: function(data) {
console.log(data)
},
error: function(xhr,status,error) {
console.log(error);
}
});
I have a datatable where I have the detail column with an edit button. When the user clicks on the edit am passing the id as a parameter. I am fetching all the values for that id and displaying in the form. Now when I edit the values and submit the form using PUT method it is getting inserted in the table, the values are passing as a parameter and it shows the empty form. How to solve this issue.
HTML:
<form class="container" id="myform" name="myform" novalidate>
<div class="form-group row">
<label for="position" class="col-sm-2 col-form-label fw-6">Position</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="position" name="position" placeholder="Position" required>
</div>
</div>
<div class="form-group row">
<label for="location" class="col-sm-2 col-form-label fw-6">Location</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="location" name="location" placeholder="Location" required>
</div>
</div>
<div class="form-group row">
<div class="col-sm-10">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</form>
PUT Method Script:
<script type='text/javascript'>
$(document).ready(function(){
$("#myform").submit(function(e) {
var parms = {
position : $("#position").val(),
location : $("#location").val()
};
var par_val;
var param_id = new window.URLSearchParams(window.location.search);
par_val = param_id.get('id');
console.log(par_val);
var par_url = par_val;
$.ajax({
url: "http://localhost:3000/joblists/"+par_val,
method: 'PUT',
async: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(parms),
success: function(data){
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
});
});
</script>
GET method script:
<script type="text/javascript">
$(document).ready(function(){
var id_val;
var params = new window.URLSearchParams(window.location.search);
id_val = params.get('id');
console.log(id_val);
var url1=id_val;
$.ajax({
url: "http://localhost:3000/joblists/"+id_val,
type: "GET",
dataType: "json",
success: function (data) {
// alert(JSON.stringify(data));
console.log(typeof(data));
$("#position").val(data.position);
$("#location").val(data.location);
},
error: function(data) {
console.log(data);
}
});
});
</script>
After submitting the form the page should remain the same with edit form values. only the edited values should be inserted. How to achieve this.
$('#myform').on('submit', function (e) {
e.preventDefault();
..........
I have checked your code in my editor. There are some changes which i made in ajax request, and it now works for me. here is the code. Try it
<script type='text/javascript'>
$(document).ready(function(){
$("#myform").submit(function(e) {
e.preventDefault();
var parms = {
position : $("#position").val(),
location : $("#location").val()
};
var par_val;
var param_id = new window.URLSearchParams(window.location.search);
par_val = param_id.get('id');
console.log(par_val);
var par_url = par_val;
$.ajax({
url: "http://localhost:3000/joblists/"+id_val,
method: 'POST', //or you can use GET
dataType : "json", //REMOVED CONTENT TYPE AND ASYNC
data: {send_obj:JSON.stringify(parms)}, //ADDED OBJECT FOR DATA
success: function(data){
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
});
});
</script>
Adding prevent default in form submit handle is enough. You're handling the post request by ajax call.
e.preventDefault();
There are 2 changes in your code.
This code will prevent your page from reloading and also you are not sending the data in proper format.
$("#myform").submit(function(e) {
e.preventDefault(); // 1. Dont reload the page
var parms = {
position : $("#position").val(),
location : $("#location").val()
};
var par_val;
var param_id = new window.URLSearchParams(window.location.search);
par_val = param_id.get('id');
console.log(par_val);
var par_url = par_val;
$.ajax({
url: "http://localhost:3000/joblists/"+par_val,
method: 'PUT',
async: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
data: parms, // 2. Just send the parms object bcoz you already defined the dataType as json so it will automatically convert it into string.
success: function(data){
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
})
});
I have a big problem with Ajax-request via Laravel. I can't understand why it is not Ajax. All resources here.
It is my Ajax-request.
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var nickname = "<?php echo $name_user; ?>";
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.subscribe').click(function() {
jQuery.ajax({
type: 'post',
url: "{{ route('postSubscribe', '<?php echo $name_user; ?>') }}", //Путь к обработчик
data: {'user_name': nickname},
response: 'text',
success: function(data) {
console.log(data['result']);
},
error: alert('Error');
})
})
</script>
It is my web-routes.
Route::group(['middleware' => 'auth'], function() {
Route::get('/', 'AccountController#redirectToAccountPage');
Route::get('/account', 'AccountController#showAccount')->name('account');
Route::get('/account/settings', 'AccountController#showSettings')->name('settings');
Route::post('/account/settings', 'AccountController#sendSetting');
Route::get('/account/subscribe', 'AccountController#showSubscriberForm')->name('subscriber');
Route::post('/account/subscribe', 'AccountController#findUser')->name('postFindUser');
Route::get('/account/load_image', 'AccountController#showLoadImage')->name('load_image');
Route::post('/account/load_image', 'Photos\LoadPhotoController#loadPhoto');
Route::post('/account/logout', 'AccountController#logout')->name('logout');
Route::post('/user/{user_name}/', 'AccountController#subscribe')->name('postSubscribe');
Route::get('/admin', 'AccountController#showAdminPanel');
});
It's my main request.
public function subscribe(Request $request, $name_user) {
if($request->ajax()) {
$query = 'SELECT id FROM subscriptions WHERE id_subscriber = ? AND id_subscribtion = ?';
$queryFindAnother = 'SELECT id From new_users WHERE nickname = ?';
$idAnotherUser = DB::select($queryFindAnother, [$name_user]);
if(!DB::select($query, [Auth::user()->id, $idAnotherUser[0]->id])) {
$query = 'INSERT INTO subscriptions (id_subscriber, id_subscribtion) VALUES (?, ?)';
dd('Я здесь');
//id_subscriber - тот, кто подписался.
//id_subscribtion - на кого подписан.
DB::insert($query, [Auth::user()->id, $idAnotherUser[0]->id]);
return response()->json([
'result' => '1', //всё прошло успешно, я подписан
]);
}
return back();
}
dd("It's not ajax");
return back();
}
As a result I got the message "It's not Ajax". Help me please!
I think the problem is in your form
Please update your form
<form>
{!! csrf_field() !!}
<button class="subscribe" name="user" type="button">Подписаться.</button>
</form>
Here, you don't need any action or method also does not need any form
because you passing the form data as ajax
and add the type of your button as button, by default its a submit type, so its submitting the form as normally.
Make sure you have imported the Request Facade on top
I can't get the ajax response when submitting a modal dialog form. It works perfectly when the form is not modal.
The form:
<div id="form2" style="display: none">
<form id="objectInsert" action="element/create" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="name">Name</label>
<input class="form-control" type="text" name="name" id="name"/>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" name="description"></textarea>
</div>
</form>
Here i get the ajax success part in the console!
$("#objectInsert").submit(function(e) {
e.preventDefault();
resetErrors();
var form = this;
var url = $(this).attr('action');
var data = new FormData($(this)[0]);
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
cahe:false,
processData: false,
contentType: false,
success: function(resp) {
console.log(resp);//Working
},
error: function() {
console.log('there was a problem checking the fields');
}
});
});
Here i get the ajax error part in the console! can someone tell me where i'm doing wrong?
$("#add_element").click(function(){
$("#form2").dialog({
modal:true,
width:400,
buttons:{
Send:function(e){
e.preventDefault();
var form = $("#objectInsert");
var url = form.attr('action');
var data = new FormData(form[0]);
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
cahe:false,
processData: false,
contentType: false,
success: function(resp) {
console.log(resp);//not working
},
error: function(xhr, status, error) {
console.log('there was a problem checking the fields');
console.log(xhr);
console.log(error);
}
});
return false;
},
Cancel:function(){
$(this).dialog("close");
}
}
});
});
The controller
public function create() {
try{
$this->form = new Form();
$this->form->post('name');
$this->form->val('isEmpty', 'name');
$this->form->post('description');
$this->form->val('isEmpty', 'description');
$this->form->fetch();
$this->form->submit();
$data = $this->form->get_postData();
$this->model->insert($data);
echo json_encode('success');
} catch (Exception $ex) {
$errors = $this->form->get_error();
$_SESSION["errors"] = $errors;
//This is for ajax requests:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])
== 'xmlhttprequest') {
echo json_encode($_SESSION['errors']);
exit;
}
foreach ($_SESSION["errors"] as $errors){
echo $errors;
echo '<br/>';
}exit;
}
}
see this code you have not closed the function block
success: function(resp) {
console.log(resp);//not working
},//This is not closed for success function
error: function() {
console.log('there was a problem checking the fields');
}
I am trying to create a live search using jquery, ajax and laravel. I also use pjax on the same page, this might be an issue?. Quite simply it should query the database and filter through results as they type.
When using Ajax type:POST I am getting 500 errors in my console. I get zero errors using GET but instead of returning in #foreach it will a full page view (this might be because of pjax).
Where am I going wrong?
Route:
Route::post('retailers/{search}', array(
'as' => 'search-retailers', 'uses' => 'RetailersController#search'));
Controller:
public function search($keyword) {
if(isset($keyword)) {
$data = array('store_listings' => RetailersListings::search($keyword));
return $data;
} else {
return "no results";
}
}
Model:
public static function search($keyword)
{
$finder = DB::table('retailers_listings')
->Where('city', 'LIKE', "%{$keyword}%")
->orWhere('country', 'LIKE', "{$keyword}")
->orderBy('country', 'asc')
->get();
return $finder;
}
View (store.blade.php):
<div id="flash"></div> //loading
<div id="live"> // hide content
<div id="searchword"><span class="searchword"></span></div> //search word
<table class="table">
<tbody>
#foreach($store_listings as $store)
<tr>
<td></td> //echo out all fields eg: {{ $store->name }}
</tr>
#endforeach
</tbody>
</table>
</div>
Form:
<form method="get" action="">
<input type="text" class="search-retailers" id="search" name="search">
</form>
Ajax and JS:
$(function() {
$("#search").keyup(function() {
var keyword = $("#search").val();
var dataString = 'keyword='+ keyword;
if(keyword=='') {
} else {
$.ajax({
type: "GET",
url: "{{ URL::route('search-retailers') }}",
data: dataString,
cache: false,
beforeSend: function(html)
{
document.getElementById("live").innerHTML = '';
$("#flash").show();
$("#keyword").show();
$(".keyword").html(keyword);
$("#flash").html('Loading Results');
},
success: function(html)
{
$("#live").show();
$("#live").append(html);
$("#flash").hide();
}
});
} return false;
});
});
Additional, Here is my controller for pjax, It is important to note I am using the view store.blade.php foreach in for the search and for this store listing.
public function stores($city)
{
$this->layout->header = $city;
$content = View::make('retailers.stores', with(new RetailersService())->RetailersData())
->with('header', $this->layout->header)
->with('store_listings', RetailersListings::stores($city));
if (Request::header('X-PJAX')) {
return $content;
} else {
$this->layout->content = $content;
}
}
Your route is Route::post('retailers/{search}', [...]) and there you go. You pass data to your ajax-call. In GET you get something like url?key=value but using POST the data are added to the request body not to the url.
Knowing this your route is no longer valid since it only looks up for retailers/{search} and not for retailers only (which is the url POST is using).
Well maybe it could help somebody.
As a first problem you are defining the route as POST and then in the ajax request the type GET so it would not work
Also when making POST request Laravel has the csrf check so in order to work, provide it. The js function will be like
$(function() {
$("#search").keyup(function() {
var keyword = $("#search").val();
if(keyword=='') {
} else {
$.ajax({
type: "post",
url: "{{ URL::route('search-retailers') }}",
data: {
'keyword': keywork,
'_token': '{{ csrf_token() }}';
},
dataType: 'html',
cache: false,
beforeSend: function(html)
{
document.getElementById("live").innerHTML = '';
$("#flash").show();
$("#keyword").show();
$(".keyword").html(keyword);
$("#flash").html('Loading Results');
},
success: function(html)
{
$("#live").show();
$("#live").append(html);
$("#flash").hide();
}
});
} return false;
});
});
And you can test your PHP search method doing separate tests for it.