I'm trying to send multiple selected options to my controller but i can't
Code
route
Route::post('/spacssendto/{id}', 'ProductController#spacssendto')->name('spacssendto');
ajax
$("body").on("click", ".sendspacsdatato", function(e){
e.preventDefault();
var id = $("#product_id").val();
$.ajax({
type: "post",
url: '{{ url('admin/spacssendto') }}/'+encodeURI(id),
data: {
'_token': $('input[name=_token]').val(),
'product_id': $('#product_id').val(),
'subspecification_id': $('.subspecifications').val(),
},
success: function (data) {
alert(data);
},
error: function (data) {
alert(data);
}
});
});
controller
public function spacssendto(Request $request, $id) {
dd($request->all());
}
my form (output)
<form method="POST" action="http://sieffgsa.pp/admin/products/15" accept-charset="UTF-8">
<input name="_token" value="DLrcOa0eOm90e4aaGSYp2uCeiuKtbGCT9fCOUP16" type="hidden">
<input name="product_id" id="product_id" value="15" type="hidden">
<div class="col-md-4">ram</div>
<div class="col-md-6">
<select class="subspecifications form-control tagsselector" id="subspecifications" name="subspecifications[]" multiple="multiple">
<option value="3">2gig</option>
<option value="4">4gig</option>
</select>
</div>
<div class="col-md-2">
<label for="">Actions</label><br>
<button type="button" id="sendspacsdatato" class=" sendspacsdatato btn btn-xs btn-success">Save</button>
</div>
</form>
PS: This form printed by Ajax in my view so it means there is several
more forms involved (the same way) that's why i mostly used classes
and not id's. Yet when I hit save button I will get 3 times repeat in
network (if i have 3 form)
Errors
Error 500 in network
dd result:
array:3 [
"_token" => "DLrcOa0eOm90e4aaGSYp2uCeiuKtbGCT9fCOUP16"
"product_id" => "15"
"subspecification_id" => null
]
Question
How can I pass my multiple options (selected) to controller?
UPDATE
Thanks to Seva Kalashnikov I fixed the problem just for helping others I'll publish final results here so you can have full code, hope it helps.
javascript
$(document).ready(function() {
$("body").on("click", ".sendspacsdatato", function(e){
var form = $(this).closest('form');
var id = form.find('input[name="product_id"]').val();
// e.preventDefault();
$.ajax({
type: "post",
url: '{{ url('admin/spacssendto') }}',
data: {
'_token': $('input[name=_token]').val(),
'product_id': id,
'subspecifications': $(this).closest('form').find('select.subspecifications').val()
},
success: function (data) {
alert('Specifications added successfully.').fadeIn().delay(6000).fadeOut();
},
error: function (data) {
console.log('Error!');
}
});
});
});
controller
public function spacssendto(Request $request) {
$this->validate($request, array(
'product_id' => 'required',
'subspecifications' => 'required',
));
$product = Product::find($request->product_id);
$product->subspecifications()->sync($request->subspecifications, false);
}
You need to get select with css class subspecifications inside the same form element
'subspecification_id': $(this).closest('form').find('select.subspecifications').val()
Try this code:
$('.sendspacsdatato').click(function() {
var form = $(this).closest('form');
var id = form.find('input[name="product_id"]').val();
$.ajax({
type: "post",
url: '{{ url('admin/spacssendto') }}/'+encodeURI(id),
data: {
'_token': form.find('input[name=_token]').val(),
'product_id': id,
'subspecification_id': form.find('select.subspecifications').val(),
},
success: function (data) {
alert(data);
},
error: function (data) {
alert(data);
}
});
});
Related
i am using ajax to store the info but when i store or not store it returns a json page and i don't want it to return a json i want to add the item without relead the page and using calidation also
please help
here is my code
my route
Route::resource('products',App\Http\Controllers\ProductController::class);
my form
<form method="POST" id="productform">
#csrf
#method('POST')
<ul id="showerrors">
</ul>
<div class="form-group">
<label for="">name</label>
<input type="text" name="name" class="form-control">
</div>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</form>
and my ajax code
<script>
$(document).ready(function(){
$('#productform').submit(function(e){
e.preventDefault();
var data = {
'name' : $("input[name='name']").val(),
'_token' : $("input[name='token']").val(),
}
// console.log(data);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url:"/products",
type : "POST",
data:data,
dataType:'json',
success:function(response){
console.log(response.status);
if(response.status == 400){
$('#showerrors').empty();
$('#showerrors').addClass('alert alert-danger');
$.each(response.errors,function(key,value){
$('#showerrors').append('<li>'+value+'</li>')
});
}
else{
$("#successmessage").empty();
$("#successmessage").addClass('alert alert-success');
$("#successmessage").text(response.message);
$('#exampleModal').modal('toggle'); //or $('#IDModal').modal('hide');
conssole.log(response.message);
return false;
}
},
});
});
});
Try this solution
add id to input field
<input type="text" name="name" class="form-control" id="name">
changes in script
$(document).ready(function(){
$('#productform').submit(function(e){
e.preventDefault();
var name = $('#name').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url:"/products",
type : "POST",
data:{
name: name
},
dataType:'json',
success:function(response){
console.log(response.status);
if(response.status == 400){
$('#showerrors').empty();
$('#showerrors').addClass('alert alert-danger');
$.each(response.errors,function(key,value){
$('#showerrors').append('<li>'+value+'</li>')
});
}
else{
$("#successmessage").empty();
$("#successmessage").addClass('alert alert-success');
$("#successmessage").text(response.message);
$('#exampleModal').modal('toggle'); //or $('#IDModal').modal('hide');
conssole.log(response.message);
return false;
}
},
});
});
});
in your controller store function
suppose your model name is Product
public function store(Request $request)
{
...
$product = Product::create($request->only('name));
return response()->json([
'status' => 200,
'message' => 'Product created successfully.'
]);
}
I have a trouble when to upload img using ajax in laravel. I have an error in getClientOriginalExtension() I think that trouble in enctype in ajax because the controller can not read the upload file.
this is my view :
<form name="data-form" id="data-form" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="file" name="img_thumbnail" class="form-control">
</form>
<script type="text/javascript">
$(function () {
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
$('body').on('click', '#saveBtn', function(){
var url;
var registerForm = $("#data-form");
var formData = registerForm.serialize();
$(this).html('saving...');
$('#saveBtn').attr('disabled',true);
$.ajax({
enctype: 'multipart/form-data',
url: '{{ route('blog.store') }}',
type:'POST',
data:formData,
success:function(data) {
console.log(data);
if(data.errors) {
}
if(data.success) {
}
$('#saveBtn').html('Save Data');
$('#saveBtn').attr('disabled',false);
},
error: function (data) {
console.log('Error:', data);
$('#saveBtn').html('Save Data');
}
});
});
});
</script>
and this is my controller
$name_file = time().'.'.$request->img_thumbnail->getClientOriginalExtension();
$request->img_thumbnail->move(public_path('images'), $nama_file);
create.blade.php
#section('content')
<form id="submitform">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" id="name">
</div>
<div class="form-group">
<label for="photo">Photo</label>
<input type="file" name="photo" id="photo">
</div>
<button class="btn btn-primary" id="submitBtn" type="submit">
<span class="d-none spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span>
<span class="">Submit</span>
</button>
</form>
#endsection
#push('custom-scripts')
<script src="{{ asset('js/upload.js') }}"></script>
#endpush
upload.js
$(function () {
$('#submitBtn').on('click', (e) => {
e.preventDefault();
var formData = new FormData();
let name = $("input[name=name]").val();
let _token = $('meta[name="csrf-token"]').attr('content');
var photo = $('#photo').prop('files')[0];
formData.append('photo', photo);
formData.append('name', name);
$.ajax({
url: 'api/store',
type: 'POST',
contentType: 'multipart/form-data',
cache: false,
contentType: false,
processData: false,
data: formData,
success: (response) => {
// success
console.log(response);
},
error: (response) => {
console.log(response);
}
});
});
});
Controller
class MyController extends Controller
{
use StoreImageTrait;
public function store(Request $request)
{
$data = $request->all();
$data['photo'] = $this->verifyAndStoreImage($request, 'photo', 'students');
Student::create($data);
return response($data, 200);
}
}
StoreImageTrait
<?php
namespace App\Traits;
use Illuminate\Http\Request;
trait StoreImageTrait
{
public function verifyAndStoreImage(Request $request, $filename = 'image', $directory = 'unknown')
{
if ($request->hasFile($filename)) {
if (!$request->file($filename)->isValid()) {
flash('Invalid image')->error()->important();
return redirect()->back()->withInput();
}
return $request->file($filename)->store('image/' . $directory, 'public');
}
return null;
}
}
<form name="data-form" id="data-form" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="file" name="img_thumbnail" class="form-control">
</form>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready( function () {
$("form#data-form").on("submit",function (e) {
e.preventDefault();
var formData = new FormData(this);
//Ajax functionality here
$.ajax({
url : '{{route('blog.store')}}',
type : "post",
data : formData,
dataType : 'json',
success:function (data) {
console.log(data);
if(data.errors) {
}
if(data.success) {
}
$('#saveBtn').html('Save Data');
$('#saveBtn').attr('disabled',false);
}, // success end
contentType: false,
processData: false
}); // ajax end
}); // form submit end
}); //document end
I am poor in AJAX and trying to submit the form and insert the record to the custom table since a couple of days but not getting it to work.
I am getting 400 Bad request error on console. Please have a look at the code.
In fact, I have tried multiple ways to submit data but none of them
works.
HTML
<form class="addtocartform" id="gsAddToCart" method="POST">
<label class="gs-label" for="options">Options</label>
<select class="gs-select-box" id="product_option" name="product_option">
<option value="0">Somnath</option>
<option value="1">Dwarka</option>
<option value="2">Rameshwaram</option>
</select>
<label class="gs-label" for="qty">Qty.</label>
<input class="gs-number" id="qty" min="1" name="qty" step="1" type="number" value="1">
<button class="gs-button order-button add-to-cart-button">
<i class="fa fa-cart-plus"></i>
<span class="gs-button-label">Add to Cart</span>
</button>
<input id="product" name="product" type="hidden" value="160"/>
<input id="group_id" name="group_id" type="hidden" value="194"/>
</input>
</form>
WordPress Hooks - Enqueue scripts
function gs_enqueue_ajax_scripts()
{
wp_register_script('gs-ajax', GROUP_SHOP_ROOT . 'public/js/add-to-cart-ajax.js', ['jquery'], 1.0, TRUE);
wp_localize_script('gs-ajax', 'ajax_vars', [
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('gs_nonce'),
]);
wp_enqueue_script('gs-ajax');
}
add_action('wp_enqueue_scripts', 'gs_enqueue_ajax_scripts');
WordPress Hooks - Process and Insert Data
function gs_add_to_cart_ajax()
{
check_ajax_referer('gs_nonce', $_POST[ 'nonce' ], FALSE);
// validating stuffs ..
$cart = new Group_Shop_Cart();
$cart->add_to_cart($_POST[ 'group_id' ], $_POST[ 'product' ], $_POST[ 'qty' ], $_POST[ 'product_option' ]);
wp_die();
}
add_action('wp_ajax_gs_add_to_cart_ajax', 'gs_add_to_cart_ajax');
add_action('wp_ajax_nopriv_gs_add_to_cart_ajax', 'gs_add_to_cart_ajax');
Javascript
(function ($) {
$(document).on("click", ".add-to-cart-button", function () {
let data = JSON.stringify({
action: 'gs_add_to_cart_ajax',
group_id: $('#group_id').val(),
product: $('#product').val(),
qty: $('#qty').val(),
product_option: $('#product_option').val(),
});
$('form.addtocartform').on('submit', function (e) {
e.preventDefault();
$.ajax({
method: 'POST',
dataType: 'json',
nonce: ajax_vars.nonce,
url: ajax_vars.ajax_url,
data: data,
success: function (response) {
alert("Success");
}
});
});
});
})(jQuery);
I have no idea what is wrong in this code that not submitting.
Modified Code
$.ajax({
method: 'POST',
dataType: 'json',
nonce: ajax_vars.nonce,
url: ajax_vars.ajax_url,
data: {
action: 'gs_add_to_cart_ajax',
group_id: $('#group_id').val(),
product: $('#product').val(),
qty: $('#qty').val(),
product_option: $('#product_option').val(),
},
success: function (response) {
alert("Success");
}
});
I have a problem with my search.
Problem 1
Currently if I type in the field it is searching however the search never ever stops, so if I type hello, it will make about 500 requests within a minute.
Problem 2
I am searching in film table to find matching 'title' as well as find business name corresponding to business_id in business table.
Problem 3
Each time request is made it brings back master page again i.e. loading all js and css (which might be why it is making so many requests?) but if I don't extend master, result blade doesn't work.
however even if I input 'e' it brings me back 'guardians of the galaxy' which doesn't have 'e' My thoughts are that it is searching throught business table as well somehow. They have both eloquent one to one relationships
Controller:
public function cinema_search($cinema_value) {
$cinema_text = $cinema_value;
if ($cinema_text==NULL) {
$data = Film::all();
} else {
$data = Film::where('title', 'LIKE', '%'.$cinema_text.'%')->with('business')->get();
}
return view('cinemasearch')->with('results',$data);
}
Form::
<form id="cinema_display">
<div class="form-group">
<input type="text" class="form-control" id="search_cinemas" onkeyup="search_cinema(this.value);" placeholder="Search film">
</div>
<div id="show"
</div>
</div>
</form>
ajax:
function search_cinema(cinema_value) {
$.ajax({
url: '/cinemasearch/' + cinema_value,
type: 'post',
dataType: 'html',
success: function(data) {
$('#show').append(data);
$('.se-pre-con').fadeOut('slow', function () {
$(".container").css({ opacity: 1.0 });
});
},
error: function(data) {
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
cinemasearch.blade(results):
#extends('master') #section('title', 'Live Oldham') #section('content')
#section('content')
<table style="width:100%">
#if (isset($results) && count($results) > 0)
#foreach( $results as $film )
<tr>
<td>{{ $film->business->name }}</td>
<td>{{ $film->title }}</td>
<td>{{ $film->times}}</td>
</tr>
#endforeach
#endif
</table>
#endsection
function search_data(search_value) {
$.ajax({
url: '/searching/' + search_value,
type: 'post',
dataType: 'html',
success: function(data) {
$('#show_search_result').append(data);
$('.se-pre-con').fadeOut('slow', function () {
$(".container").css({ opacity: 1.0 });
});
},
error: function(data) {
$('body').html(data);
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
function tram_stops(tram_value) {
$.ajax({
url: '/tramsearch/' + tram_value,
type: 'post',
dataType: 'html',
success: function(data) {
$("#display").html(data);
var tram_value = tram_value;
},
error: function(data) {
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
/*
setInterval(tram_stops, (30 * 1000));
*/
function search_cinema(cinema_value) {
$.ajax({
url: '/cinemasearch/' + cinema_value,
type: 'post',
dataType: 'html',
success: function(data) {
var items = JSON.parse(data);
var showElement = $('#show');
showElement.html('');
$.each(data, function() {
showElement.append(this.title +' '+ this.times+'<br />');
});
},
error: function(data) {
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
You are returning the wrong response type from cinema_search. Ajax expects a JsonResponse, not what the view helper returns which is \Illuminate\Http\Response. Put your search results in:
return response()->json(['results' => $data]);
to start with if you just want the data. If you want to actually return the rendered view file, you would need to do:
return response()->json(['results' => view('cinemasearch')->with('results',$data)->render()]);
then inject that into your DOM. The problem with rendering server side is nothing is bound client side so if you have any interaction requiring JS, you'll need to create those manually in your success callback.
Problem 1:
Remove the keyUp event in your html and add an event in Jquery.
Your HTML structure is not correct
This:
<form id="cinema_display">
<div class="form-group">
<input type="text" class="form-control" id="search_cinemas" onkeyup="search_cinema(this.value);" placeholder="Search film">
</div>
<div id="show"
</div>
</div>
</form>
Should be:
<form id="cinema_display">
<div class="form-group">
<input type="text" class="form-control" id="search_cinemas" onkeyup="search_cinema(this.value);" placeholder="Search film">
<div id="show">
</div>
</div>
</form>
Then again you should consider to remove the onkeyup event. And change add it in Jquery to something like this:
Problem 2 & 3: I would recommend a raw Query and return an json instead of a view. And you shouldn't check if($cinema_text === NULL) this won't be the case ever. Unless you put NULL in your url and even then it will be an String and not NULL and if('NULL' === NULL) returns false look at this post for the diff of == and ===.
public function cinema_search($cinema_value) {
$cinema_text = $cinema_value;
if (empty($cinema_text)) {
$data = Film::all();
} else {
$data = DB::select('*')
->from('films')
->join('businesses', 'businesses.id', '=', 'films.business_id')
->where('films.title', 'LIKE', '%'.$cinema_text.'%')
->orWhere('bussiness.title', 'LIKE', '%'.$cinema_text.'%')
->get();
}
return response()->json(['results' => $data]);
}
Then in your JavaScript do something like this:
$( document ).ready(function() {
console.log( "ready!" );
$( "#search_cinemas" ).change(function() {
search_cinema(this.value);
console.log( "New value"+this.value+"!" );
});
function search_cinema(cinema_value) {
console.log('setup ajax');
$.ajax({
url: '/cinemasearch/' + cinema_value,
type: 'post',
success: function(data) {
console.log('success!');
var showElement = $('#show');
showElement.html('');
$.each(items, function() {
showElement.append(this.title +' '+ this.times+'<br />');
});
},
error: function(data) {
console.log(data);
},
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
}
});
I am newer to ajax. I want to add two fields using ajax and codeigniter.. When i click the submit button the two fields are added but the alert message is not showing also the page is not refreshing. Can any one solve my issue.. Thanks in advance..
This is my Form
<form action="" id="suggestionsform" method="post">
<div class="form-group">
<label for="suggname">Name</label>
<input type="text" class="form-control" name="suggname" id="suggname" placeholder="Enter Your Name" required="required">
</div>
<div class="form-group">
<label for="suggmessage">Suggestion</label>
<textarea class="form-control" rows="4" name="suggmessage" id="suggmessage"
placeholder="Enter Your Suggestions"></textarea>
</div>
<button type="submit" class="btn btn-default" id="suggestions">Submit</button>
</form>
This is my ajax codeing
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(data) {
if (data=='true')
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Controller Coding
public function addSuggestion()
{
$data=array(
'name' => $this->input->post('name'),
'messages' => $this->input->post('suggestion'),
'date' => now()
);
$data=$this->Helen_model->setSuggestion($data);
echo json_encode($data);
}
Model Coding
public function setSuggestion($data){
$this->db->insert('messages', $data);
return $this->db->insert_id();
}
You can achieve like this..
Model
Return true status if insert successful.
public function setSuggestion($data){
$res = $this->db->insert('messages', $data);
if($res){
$result = array('status'=>true,'message'=>'successful');
}
else
{
$result = array('status'=>false,'message'=>'failed');
}
return $result;
}
JS
Check status in success function
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(response) {
data = eval(response);//or data = JSON.parse(response)
if (data.status ===true)
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Try to use echo '{"status": "success"}; on your controller response.
That i see on your script you are shown database response.