hello i am using modal form and if login successful , the successful message is shown in alertity message box. Why my message is not shown? If i am successful login stay on same page and show alertity message in message box & if failed then show failed message and show modal again? code is working and redirect on same page after login and failed in login.
Controller:
public function submitUser(Request $req)
{
$req->validate([
'email' => 'required|email',
'password' => 'required',
]);
$email_address=$req->input('email');
$password=$req->input('password');
$query_select=DB::table('table_users')->where('email','=',$email_address)->where('password','=',$password)->first();
if($query_select)
{
if($email_address==$query_select->email && $password ==$query_select->password)
{
$remember=$req->input('remember');
$req->session()->put('name',$query_select->name);
$req->session()->put('user_id',$query_select->id);
$req->session()->put('user_email',$query_select->email);
if(!empty($remember))
{
setcookie ("email",$query_select->email,time()+ (10 * 365 * 24 * 60 * 60));
setcookie ("password",$query_select->password,time()+ (10 * 365 * 24 * 60 * 60));
return redirect()->back()->with('status_of_login','You log in successful');
}
else
{
if(isset($_COOKIE["email"]))
{
setcookie ("email","");
}
if(isset($_COOKIE["password"]))
{
setcookie ("password","");
}
return redirect()->back()->with('status_of_login','You log in successful');
}
}
else
{
// $req->session()->flash('error','You have entered wrong credentials');
return redirect()->back()->with('status_of_login_wrong','Your credentials are wrong');
}
}
else
{
return redirect()->back()->with('status_of_login_wrong','Your credentials are wrong');
}
}
html:
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Login safely</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="card">
<center>
<div class="social-media">
<i class="fa fa-facebook-f fa_fb_new"></i>
<i class="fa fa-google fa_go_new"></i>
</div>
</center>
<form class="ps-product__review" action="{{ route('submit_user')}}" method="post" enctype="multipart/form-data">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="form-group">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" id="" placeholder="Enter Email" name="email" value="<?php if(isset($_COOKIE["email"])) { echo $_COOKIE["email"]; } ?>" required>
<span class="text-danger">{{ $errors->first('email') }}</span>
</div>
<div class="form-group">
<label for="inputPassword">Password</label>
<input type="password" class="form-control" id="" placeholder="Enter Password" name="password" value="<?php if(isset($_COOKIE["password"])) { echo $_COOKIE["password"]; } ?>" required>
<span class="text-danger">{{ $errors->first('password') }}</span>
</div>
<div class="form-group">
<label class="form-check-label"><input type="checkbox" name="remember" <?php if(isset($_COOKIE["email"])) { ?> checked <?php } ?>> Remember me</label>
</div>
<button type="submit" class="ps-btn-login">Log In</button>
Sign Up
</form>
</div>
</div>
</div>
</div>
</div>
in footer:
<script type="text/javascript" src="{{ asset('js/alertify.min.js')}}"></script>
<script type="text/javascript">
#if(session('status_of_login'))
alertify.set('notifier','position', 'top-center');
alertify.success("{{session('status_of_login')}}");
#endif
</script>
change your footer code like
<script type="text/javascript" src="{{ asset('js/alertify.min.js')}}"></script>
#if(session('status_of_login'))
<script type="text/javascript">
$(function(){
alertify.set('notifier','position', 'top-center');
alertify.success("{{session('status_of_login')}}");
alertify.error("{{session('status_of_login_wrong')}}");
})
</script>
#endif
here it check have any session is there or not once it got session then it trigger onload function of jQuery
Related
I'm using laravel and trying to save data using post through ajax but data is not saved in database. I'm getting following error: jquery.min.js:2 POST http://localhost:8000/admin/products/attributes/add 500 (Internal Server Error). My code is as follows:
view:
<script>
$("#add_attributes_info").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: '/admin/products/attributes/add',
data: $('#frmattributes').serialize(),
success: function(msg) {
console.log('success'+msg);
}
});
});
</script>
<form action="#" id="frmattributes" method="POST">
<h3 class="tile-title">Add Attributes To Product</h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="values">Select an value <span class="m-l-5 text-danger"> *</span></label>
<select id="attribute_values" name="value" class="form-control custom-select mt-15">
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="quantity">Quantity</label>
<input class="form-control" name="quantity" type="number" id="quantity"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="price">Price</label>
<input class="form-control" name="price" type="text" id="price"/>
<small class="text-danger">This price will be added to the main price of product on frontend.</small>
</div>
</div>
<div class="col-md-12">
<button class="btn btn-sm btn-primary" id="add_attributes_info">
<i class="fa fa-plus"></i> Add
</button>
</div>
</div>
</form>
Controller:
public function addAttribute(Request $request)
{
$productAttribute = ProductAttribute::create($request->data);
if ($productAttribute) {
return response()->json(['message' => 'Product attribute added successfully.']);
} else {
return response()->json(['message' => 'Something went wrong while submitting product attribute.']);
}
}
You should use:
$productAttribute = ProductAttribute::create($request->all());
However you should keep in mind this is very risky without validation.
You should add input validation and then use:
$productAttribute = ProductAttribute::create($request->validated());
Use $request->all();
public function addAttribute(Request $request)
{
$productAttribute = ProductAttribute::create($request->all());
if ($productAttribute) {
return response()->json(['message' => 'Product attribute added successfully.']);
} else {
return response()->json(['message' => 'Something went wrong while submitting product attribute.']);
}
}
PS : I made some changes to get it works
Hope this help
<head>
<title></title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function submitForm() {
$.ajax({
type: "POST",
url: '../admin/products/attributes/add',
data: $('#frmattributes').serialize(),
success: function(msg) {
console.log('success' + msg);
}
});
}
</script>
</head>
<body>
<form id="frmattributes">
<h3 class="tile-title">Add Attributes To Product</h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="values">Select an value <span class="m-l-5 text-danger"> *</span></label>
<select id="attribute_values" name="value" class="form-control custom-select mt-15">
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="quantity">Quantity</label>
<input class="form-control" name="quantity" type="number" id="quantity" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="price">Price</label>
<input class="form-control" name="price" type="text" id="price" />
<small class="text-danger">This price will be added to the main price of product on frontend.</small>
</div>
</div>
<div class="col-md-12">
<button class="btn btn-sm btn-primary" id="add_attributes_info" type="button" onclick="submitForm()">
<i class="fa fa-plus"></i> Add
</button>
</div>
</div>
</form>
</body>
</html>
So in the controller, change the $request->data with :
$productAttribute = ProductAttribute::create($request->all());
or also check what the request contains, before creating you can check using:
dd($request->all());
I want to display the form validation error within the Modal, but the errors are being displayed in a new page
View
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-body">
<div id="modelError">hi</div>
<?php echo form_open('welcome/add_data','id="myform"'); ?>
<div class="form-group">
<label for="user_name" class="col-sm-4 control-label">User Name</label>
<div class="col-sm-12">
<input class="form-control" type="text" name="user_name" id="user_name">
</div>
</div>
<div class="form-group">
<label for="name" class="col-sm-4 control-label">Name</label>
<div class="col-sm-12">
<input class="form-control" type="text" name="name" id="name">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary" id="add">Save</button>
</div>
<?php echo form_close(); ?>
</div>
</div>
</div>
Ajax
<script>
$(document).ready(function () {
$(document).on('submit','#myform',function(event){
event.preventDefault();
let name=$("#name").val();
let user_name=$("#user_name").val();
$.ajax({
url:"<?php echo base_url(). 'welcome/add_data';?>",
method: 'POST',
data:new FormData(this),
contentType:false,
processData:false,
success: function(data) {
var myObj = JSON.parse(data);
var msg = '<div class="alert alert-danger alert-dismissable">'+myObj.error+'</div>';
$('#modelError').html(msg);
},
error: function() {
alert('Error get data from ajax');
}
}
});
})
})
</script>
Controller
public function add_data(){
$this->form_validation->set_rules('name', 'Name', 'required');
$this->form_validation->set_rules('user_name', 'User Name', 'required');
if ($this->form_validation->run() == FALSE) {
$this->msg['error'] = validation_errors();
echo json_encode($this->msg);
}
else {
$data=array(
'name'=>$this->input->post('name'),
'user_name'=>$this->input->post('user_name'),
);
$this->Test_model->add_data($data);
redirect('welcome',"refresh");
}
}
I expect the errors within the Modal (pop up window), but the errors are displayed in a new page "localhost/ajax/welcome/add_data"
I have tried lots of code snippets from stackoverflow but none of them works.
i was creating vue file for inpute Excel or csv file laravel 5.7
i was using Maatwebsite/Laravel-Excel
dont know how to route there things it if my first time to make app like laravel with vue JS
Don't know what to doo
there is Vue file
<template>
<div class="container">
<div class="row mt-5">
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h3 class="card-title">Students</h3>
<div class="card-tools">
<button class="btn btn-success" data-toggle="modal" data-target="#exampleModal">Add New <i class="fas fa-user-plus"></i></button>
<button class="btn btn-primary" data-toggle="modal" data-target="#importModel">Import <i class="fas fa-file-excel"></i></button>
<button class="btn btn-warning" data-toggle="modal" data-target="#export">Export <i class="fas fa-file-excel"></i></button>
</div>
</div>
</div>
<!-- /.card -->
</div>
</div><!-- /.row -->
<!-- Modal -->
<div class="modal fade" id="importModel" tabindex="-1" role="dialog" aria-labelledby="importModelLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="importModelLabel">Import Excel</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form method="POST" enctype="multipart/form-data">
<div class="modal-body">
<div class="form-group">
<label>Import</label>
<input type="file" name="excel_file"
class="form-control" :class="{ 'is-invalid': form.errors.has('excel_file') }">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save Student</button>
</div>
</form>
</div>
</div>
</div>
<!--Exit Modal-->
</div>
</template>
<script>
export default {
data(){
return{
form: new Form({
first_name:'',
last_name:'',
email:'',
password:'',
designation:''
})
}
},
mounted() {
console.log('Component mounted.')
}
}
</script>
set a post route to import data in web.php file
that will route the things as pr laravelExcel
Route::post('importExcel', 'API/StudentMasterController#import');
in a controller file
public function import()
{
Excel::import(new StudentImport, request()->file('excel_file'));
//return redirect('/')->with('success', 'All good!');
}
and in a APP/import/studentmaster.php file
public function model(array $row)
{
return new Student_master([
'EnrollmentNo' => $row[22],
]);
}
this is vue views and js my code :
<form method="POST" action="#" class="form-horizontal" #submit.prevent="createUpload" enctype="multipart/form-data">
<div class="box-body">
<div class="form-group row"><label for="name" class="col-sm-2 form-control-label">Parameter</label>
<div class="col-sm-10">
<input type="file" class="form-control" id="result_file" ref="myFiles" placeholder="Name Parameter" required="required" #change="previewFiles($event)">
<input type="hidden" name="result_file2" class="form-control" id="title" v-model="datafileupload.result_file3" placeholder="Name Parameter" required="required">
<input type="hidden" name="hasilcek" class="form-control" id="hasilcek" v-model="datafileupload.hasilcek3" placeholder="Name Parameter" required="required">
<input type="hidden" class="form-control" v-model="datapush.filename">
<input type="hidden" class="form-control" v-model="datapush.size">
</div><br><br><br>
<div v-if="this.hasilcekexcel > 0" class="alert alert-warning">File {{ namafile }} exists , do you want to replace it ?</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" #click="doSomethingOnHidden" >Close</button>
<input type="submit" class="btn btn-primary" id="submit_upload2" v-if="this.hasilcekexcel > 0" value="Replace">
<input type="submit" class="btn btn-primary" id="submit_upload" v-if="this.hasilcekexcel == 0" value="Upload">
</div>
</form>
js upload :
createUpload () {
var data = new FormData();
var file = this.$refs.myFiles.files[0];
var size = this.$refs.myFiles.files[0].size;
data.append('filenya', file);
data.append('namasifile', this.datafileupload.result_file3);
data.append('angkacek', this.datafileupload.hasilcek3);
axios.post('excelupload/upload', data)
.then(response => {
this.pesertas.push(response.data.data);
this.showModal =false;
});
},
controller :
$excelupload = new Exceluploads;
$hasilcek = $request->angkacek;
$requestfile = $request->namasifile;
if ($request->filenya != '') {
$input = Input::all();
$size = $request->file('filenya')->getClientSize();
$file = array_get($input,'result_file');
$userID = Auth::user()->id;
$uploaded_by = Auth::user()->name;
$destinationPath = 'excel';
// GET THE FILE EXTENSION
$extension = 'xls';
$fileName = $requestfile.'.'.$extension;
if ($hasilcek > 0) {
File::delete($destinationPath.'/'.$fileName);
$upload_success = $request->filenya->move($destinationPath, $fileName);
return response()->json(['data' => Exceluploads::find($excelupload->id)]);
}else if ($hasilcek == 0) {
$upload_success = $request->filenya->move($destinationPath, $fileName);
$excelupload->filename = $fileName;
$excelupload->directory = $destinationPath.'/'.$fileName;
$excelupload->size = $size;
//1 = not custome
$excelupload->type = 1;
$excelupload->uploaded_by = $uploaded_by;
$excelupload->save();
return response()->json(['data' => Exceluploads::find($excelupload->id)]);
}
}
I'm trying to update some data in Model using API in Laravel and Vue.js
but I can't do this because axios doesn't send any data to server, I'm checking the data right before sending and they exist (I use FormData.append to add all fields)
I check data before sending using the code:
for(var pair of formData.entries()) {
console.log(pair[0]+ ': '+ pair[1]);
}
and I get this result:
You can check the appropriate code:
[function for updating]
updateStartup() {
let formData = new FormData();
formData.append('startup_logo', this.update_startup.startup_logo);
formData.append('country_id', this.update_startup.country_id);
formData.append('category_id', this.update_startup.category_id);
formData.append('startup_name', this.update_startup.startup_name);
formData.append('startup_url', this.update_startup.startup_url);
formData.append('startup_bg_color', this.update_startup.startup_bg_color);
formData.append('startup_description', this.update_startup.startup_description);
formData.append('startup_public', this.update_startup.startup_public);
axios.put('/api/startup/' + this.update_startup.id, formData, { headers: {
'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW',
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error.response);
});
}
[controller method where I should receive data]:
public function update(Request $request, $id) {
return $request; // just for checking if I get data
...
}
[HTML with vue.js where I use object which I send in updateStartup function]:
<!-- Modal edit -->
<div class="modal fade editStartUp" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<img src="/admin/images/modal-cross.png" alt="Close">
</button>
</div>
<div class="modal-body">
<form method="POST" enctype="multipart/form-data" #submit.prevent="updateStartup">
<h4 class="sel-c-t">Select category</h4>
<div class="submit-fields-wr">
<select name="category" v-model="update_startup.category_id" class="selectpicker select-small" data-live-search="true" #change="updateCategoryDetails()">
<option v-for="category in categories" :value="category.id" :selected="category.id == update_startup.category_id ? 'selected' : ''" >{{ category.name }}</option>
</select>
<select v-if="update_startup.is_admin" name="country" v-model="update_startup.country_id" class="selectpicker select-small" data-live-search="true" #change="updateCountryDetails()">
<option v-for="country in countries" :value="country.id" :selected="country.id == update_startup.country_id ? 'selected' : '' ">{{country.name }}</option>
</select>
</div>
<div class="submit-fields-wr">
<input type="text" placeholder="Startup name" v-model="update_startup.startup_name">
<input type="url" v-model="update_startup.startup_url" placeholder="URL">
</div>
<textarea v-model="update_startup.startup_description" name="startup_description" placeholder="Describe your startup in a sentence.">
</textarea>
<div v-if="!update_startup.is_admin">
<h4 class="sel-c-t bold">Contact details:</h4>
<div class="submit-fields-wr">
<select name="country" v-model="update_startup.country_id" class="selectpicker select-small" data-live-search="true" #change="updateCountryDetails()">
<option v-for="country in countries" :value="country.id" :selected="country.id == update_startup.country_id ? 'selected' : '' ">{{country.name }}</option>
</select>
<input type="text" placeholder="Your Name" v-model="update_startup.contact_name">
</div>
<div class="submit-fields-wr">
<input type="text" v-model="update_startup.contact_phone" placeholder="Your phone number">
<input type="email" v-model="update_startup.contact_email" placeholder="Your email address">
</div>
</div>
<p class="upl-txt">Company’s logo.<span>(upload as a png file, less than 3mb)</span></p>
<div class="file-upload">
<div class="logo-preview-wr">
<div class="img-logo-preview">
<img :src="update_startup.startup_logo" alt="logo preview" id="img_preview">
</div>
</div>
<label for="upload" class="file-upload_label">Browse</label>
<input id="upload" #change="onFileUpdated" class="file-upload_input" type="file" name="file-upload">
</div>
<div class="preview-divider"></div>
<h4 class="sel-c-t bold">Preview:</h4>
<div class="preview-wrapper-row">
<a href="#" class="start-up-wr">
<div class="start-up-part-1 edit">
<div class="flag-cat-wr">
<div class="flag-wr">
<img :src="update_startup.country_flag" :alt="update_startup.country_name">
</div>
<div class="category-wr">
{{ update_startup.category_name }}
</div>
</div>
<img :src="update_startup.startup_logo" :alt="update_startup.startup_name" class="start-up-logo">
</div>
<div class="start-up-part-2">
<h4 class="startup-name">{{ update_startup.startup_name }}</h4>
<p class="startup-description">
{{ update_startup.startup_description }}
</p>
</div>
</a>
<div class="color-picker-btns-wr">
<div>
<input type="text" class="color_picker" v-model="update_startup.startup_bg_color">
<button class="colo_picker_btn">Background Color</button>
</div>
<div class="modal-bottom-btns">
<div class="btn-deactivate-active">
<button type="submit" class="btn-deactivate" #click="deactivateExistingStartup()">Deactivate</button>
<button type="submit" class="btn-activate" #click="activateExistingStartup()">Activate</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Modal edit -->
[Additional info - also when I open modal(where I have form for updating) I change form data accordingly to startup id]:
showUpdateStartup(startup) {
setTimeout(() => {
$('.selectpicker').selectpicker('refresh');
}, 50);
this.update_startup.id = startup.id;
this.update_startup.category_id = startup.category.id;
this.update_startup.category_name = startup.category.name;
this.update_startup.startup_name = startup.name;
this.update_startup.startup_description = startup.description;
this.update_startup.startup_url = startup.url;
this.update_startup.startup_logo = startup.logo;
this.update_startup.startup_bg_color = startup.startup_bg_color;
this.update_startup.contact_id = startup.contact.id;
this.update_startup.contact_name = startup.contact.name;
this.update_startup.contact_phone = startup.contact.phone;
this.update_startup.contact_email = startup.contact.email;
this.update_startup.country_id = startup.contact.country.id;
this.update_startup.country_flag = startup.contact.country.flag;
this.update_startup.country_name = startup.contact.country.name;
this.update_startup.is_admin = startup.contact.is_admin;
this.update_startup.startup_public = startup.public;
},
Let me know if you have any additional questions
Thank you guys a lot for any help and ideas!
Try using formData.append('_method', 'PATCH') with axios.post method.
Return the input data instead of the Request object from your controller:
return $request->input();
I have a problem with my function that saves data into database,
Basically user puts name into a form and when I do console.log I do get that value, I then call my function in controller and everything looks sucessfully - no errors but when I check in mysql name = NULL, why?
My form:
<div class="modal fade" id="myModalHorizontal" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<button type="button" class="close"
data-dismiss="modal">
<span aria-hidden="true">×</span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title" id="myModalLabel">
Website Name
</h4>
</div>
<div class="modal-body">
<form action="{{ action('BuilderController#postDB') }}"
class="form-horizontal" role="form" method = "POST">
<div class="form-group">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" id="code" name="newCode" value="">
<label class="col-sm-2 control-label"
for="website_name">Name</label>
<div class="col-sm-10">
<input type="text" class="form-control"
id="website_name" placeholder="Website Name"/>
</div>
</div>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="form-control margin btn btn-danger"
data-dismiss="modal">
Close
</button>
<button onClick=" updateDatabase(this);" type="submit" class="form-control margin btn btn-success" id="getRequest changes">
Save Website
</button>
</div>
</div>
</div></form>
</div>
JS:
var web_name;
function updateDatabase()
{
code2 = document.getElementById("content-link2").innerHTML;
var newCode = document.getElementById('code').value = code2;
web_name = ($('#website_name').val());
console.log(web_name);
console.log(newCode);
Controller:
public function postDB(Request $request) {
$newName = $request->input('web_name');
$newLat = $request->input('newCode');
$websites = new Website();
$websites->name = $newName;
$websites->html = $newLat;
$websites->save();
// Now we go to our other function
return $this->website($newName);
}
public function website($newName)
{
// Return our "website" object
$html = Website::where('name', $newName)->first();
// Pass the contents of the "html" property to the view
return view('layouts/website', [
'html' => $html->html
]);
}
You need to add name attribute to input element:
<input name="website_name" ...