Ajax autocomplete doesn't work with looping result data - ajax

I have an edit page in laravel where there is multiple data product that using foreach to display, and i want to autocomplete the name of product using ajax but it doesn't work. but i dont get any error messages.
here is the code
#foreach($product as $item){
<input type="text" name="product" id="product" value="{{ $item->name }}"/>
<input type="number" name="qty" id="qty" value="{{ $item->quantity }}"/>
<input type="number" name="price" id="price" value="{{ $item->price }}"/>
}
and the script
$(document).ready(function(){
$('#product').autocomplete({
source: function(request, response){
console.log(request.term)
$.ajax({
url:"{{ route('autocompleteproduct')}}",
dataType: "json",
data: {
search: request.term
},
success: function(data){
response(data);
},error:function(){
alert('error');
}
});
},
select: function(event, ui){
$('#product').val(ui.item.label);
return false;
}
});
});

As I mentioned in my Comment, ID's on divs should be unique, Here you are looping over items spamming the the id of "#product" on each one. use a class, or be more specific with each products actual id
below I have removed the IDs off each input as you are not using any labels they are not required. I have also wrapped them in a class to loop over each one so we can target the children specifically
#foreach($product as $item)
<div class="product-inputs" id="product-{{ $item->id }}">
<input type="text" name="product" value="{{ $item->name }}">
<input type="number" name="qty" value="{{ $item->quantity }}">
<input type="number" name="price" value="{{ $item->price }}">
</div>
#endfor
$(document).ready(function(){
$('.product-inputs').each(function() {
var id = $(this).attr('id');
var input = $('#' + id + ' input[name=product]');
input.autocomplete({
source: function(request, response){
console.log(request.term)
$.ajax({
url:"{{ route('autocompleteproduct')}}",
dataType: "json",
data: {
search: request.term
},
success: function(data){
response(data);
},error:function(){
alert('error');
}
});
},
select: function(event, ui){
input.val(ui.item.label);
return false;
}
});
});
});

Related

My ajax request return status error 405 on laravel

I'm using laravel 6. IT returns me error 405 when using external ajax.js file to handle my form.
message: The POST method is not supported for this route. Supported methods: GET, HEAD.
This is my form in blade:
<form >
#csrf
<div class="form-group">
<label>Name:</label>
<input type="text" name="name" class="form-control" placeholder="Name" required="">
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" name="password" class="form-control" placeholder="Password" required="">
</div>
<div class="form-group">
<strong>Email:</strong>
<input type="email" name="email" class="form-control" placeholder="Email" required="">
</div>
<div class="form-group">
<button class="btn btn-success btn-submit">Submit</button>
</div>
</form>
my ajax.js:
$(document).on('submit','#employeeSignupFrom',function (e) {
var token = $('input[name="_token"]').attr('value')
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': token
}
});
$.ajax({
$url:'/signupemployee',
type:'post',
data: $(this).serialize(),
contentType:'json',
success: function( response, textStatus, jQxhr ){
alert('done')
},
error: function( jqXhr, textStatus, errorThrown ){
alert('error!');
}
});
e.preventDefault()
})
the route(web.php):
Route::post('/signupemployee','FormsController#signupEmployee');
and my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class FormsControllers extends Controller
{
public function signupEmployee(Request $request){
$employeeInfo=$request->all();
return response()->json(['alert'=>'done!']);
}
}
First remove $ sign from your url:
//$url:'/signupemployee', <- remove $
url:'/signupemployee',
Second change contentType to:
contentType: 'application/json',
Finally your ajax should be something like this:
$.ajax({
url: '/signupemployee', //<- $ sign should deleted
type: 'POST',
data: data,
contentType: 'application/json', //<- not just json
headers: {
'X-CSRF-TOKEN': token
}
})

Laravel ajax only the first button excute the other button will not response

I need your help guys im stuck because when i click the first button it will execute but the other button it will not excute im using ajax for the form and i use foreach. If someone know how to solve please tell me.
This is my current view code:
<tbody>
#foreach($customers as $name => $member)
#foreach($member->slice(0,1) as $value)
<tr>
<td>{{$value->id}}</td>
<td>{{$value->MATNR}}</td>
<td>{{$value->MAKTX}}</td>
<td>
<select class="form-control">
<option>{{$value->UNIT1}}({{$value->CONV1}})</option>
<option>{{$value->UNIT2}}({{$value->CONV2}})</option>
</select>
</td>
<td>
<select class="form-control">
#foreach($member as $value)
<option value="{{$value->CHARG}}">{{$value->CHARG}}</option>
#endforeach
</select>
</td>
<td>{{$value->VERME}}</td>
<td>
<form name="ajaxForm" id="ajaxForm" class="form-horizontal" novalidate="">
<input type="text" name="_token" value="{{ csrf_token() }}">
<input type="text" name="id" value="{{$value->id}}">
<button type="button" class="btn btn-primary" id="btnSave" value="add">Save</button>
</form>
</td>
</tr>
#endforeach
#endforeach
</tbody>
This is my current controller code
public function cart() {
if (Request::isMethod('post')) {
$id = Request::get('id');
$customers = DB::table('Materials')->select('Materials.MATNR','Materials.MAGRV','Materials.CONV1','Materials.id','Materials.CONV1','Materials.UNIT1','Materials.CONV2','Materials.UNIT2','Materials.MHDHB','Materials.MAKTX','Inventory.CHARG','Inventory.VERME')->join('Inventory',function($join){
$join->on('Inventory.MATNR','LIKE',DB::raw("CONCAT('%',Materials.MATNR,'%')"));
})->groupBy('Materials.MATNR','Materials.MAGRV','Materials.CONV1','Materials.id','Materials.CONV1','Materials.UNIT1','Materials.CONV2','Materials.UNIT2','Materials.MHDHB','Materials.MAKTX','Inventory.CHARG','Inventory.VERME')->find($id);
$cart = ShoppingCart::add($customers->id, $customers->CHARG, 5, 100.00, ['MAKTX' => $customers->MAKTX, 'kg' => $customers->VERME]);
}
}
And my current route
Route::post('/cart', 'system\request_customer#cart');
Ajax current code
$(document).ready(function(){
$("#btnSave").click(function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
})
e.preventDefault();
$.ajax({
type: 'POST',
url: 'cart',
data: $('#ajaxForm').serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
So this is my new view
<form method="POST" class="form-horizontal ajaxForm">
<input type="hidden" id="token" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="id" id="id" value="{{$value->id}}">
<input type="hidden" name="MATNR" value="{{$value->MATNR}}">
<button>Submit</button>
</form>
and my new ajax
$(".ajaxForm").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: 'cart',
type: 'POST',
data: formData,
success: function (data) {
console.log(data)
},
cache: false,
contentType: false,
processData: false
});
});
I had the same problem. I solved it by replacing id with class. I don't know why this is a solution, but it worked in my case. To make it easier for you, here is what you have to do. Just try it, according to me, It must work!
Replace every #ajaxForm with .ajaxForm.
Replace <form name="ajaxForm" id="ajaxForm" class="form-horizontal" novalidate=""> with <form name="ajaxForm" class="form-horizontal ajaxForm" novalidate="">
Let me know if it works. It worked in my case. In my case, I was having the same error. I mean, only first button or submit button worked.
If you are JQuery expert or know the reason behind this, please let me know!

Two ajax call for two forms, latter not working

I've tried everything. The form posts fine when not using Ajax, I switch the places so it would be first, I deleted everything and just gave it an alert to show when clicking submit... I can't pin-point the problem.
The second ajax just won't submit!
$(document).ready(function() {
$('#writeform').submit(function(event) {
var formData = {
'from': $('input[name=from]').val(),
'to': $('input[name=to]').val(),
'textbox': $('input[name=textbox]').val()
};
$.ajax({
type: 'POST',
url: 'process.php',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
// ajax the login
$(document).ready(function() {
$('#loginform').submit(function(event) {
var formData = {
'username': $('input[name=username]').val(),
'pass': $('input[name=pass]').val()
};
$.ajax({
type: 'POST',
url: 'login.php',
data: formData,
dataType: 'json',
encode: true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
function loadLogDiv(){
$("#logfunction").load("login.php");
}
$(document).ready(function () {
$.ajaxSetup({
cache: false
});
loadLogDiv();
setInterval( loadLogDiv, 4000);
});
Heres the page itself:
<div id="loginpage">
<form id="loginform" action="login.php" method="POST">
<div id="username">
<label for="username">User Name</label>
<input type="text" name="username" placeholder="User Name" />
<!-- errors will go here -->
</div>
<div id="pass">
<label for="pass">Password</label>
<input type="password" name="pass" placeholder="Password" />
<!-- errors will go here -->
</div>
<input type="submit">Submit</input>
</form>
<div id="logfunction"></div>
</div>
<div id="footer">
<form id="writeform" action="process.php" method="POST">
<div id="from">
<label for="from">From</label>
<select name="from">
<?php
$result = mysqli_query($conn, "SELECT user_name FROM `users`");
while($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['user_name'] . "'>" . $row['user_name'] . "</option>";
}
?>
</select>
</div>
<div id="to">
<label for="to">To</label>
<select name="to">
<?php
$result = mysqli_query($conn, "SELECT user_name FROM `users`");
while($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['user_name'] . "'>" . $row['user_name'] . "</option>";
}
?>
</select>
</div>
<div id="textbox">
<label for="textbox">Text</label>
<input type="text" name="textbox" placeholder="text" />
</div>
<input type="submit">Submit</input>
</form>

500 (Internal Server Error) For Ajax POST in Laravel

Please can someone provide a simple example for ajax in laravel 5.1. I have tried everything and still no success. Tried the other solutions here but no luck, maybe it is my copy of laravel, I really don't understand. I just want to see how its done correctly. Please help me out. Thanks.
Route: Route::post('/signin', 'UserController#ajax');
<form action="signin" method="POST" id="form1">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<fieldset>
<p><label for="email">E-mail address</label></p>
<p><input type="email" value="{{ old('email') }}" onBlur="if(this.value=='')this.value='mail#address.com'" onFocus="if(this.value=='mail#address.com')this.value=''" name="email"></p> <!-- JS because of IE support; better: placeholder="mail#address.com" -->
<p><label for="password">Password</label></p>
<p><input type="password" name='password' value="password" onBlur="if(this.value=='')this.value='password'" onFocus="if(this.value=='password')this.value=''"></p> <!-- JS because of IE support; better: placeholder="password" -->
<p><input type="submit" value="Login" name="submit" id="sign"></p>
</fieldset>
</form>
for the controller:
public function ajax(Request $request)
{
if(Request::ajax()) {
$data = Request::all();
print_r($data);
]);
}
And ajax:
$('#sign').click(function(event) {
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
var inputs = $('#form1').serialize();
$.ajax({
url: 'http://localhost/laravel/public/signin',
type: 'POST',
dataType: 'json',
data: inputs,
success: function (data) {
console.log(data);
}
})
return false;
});

Ajax not working for many form on same page

in a view im repating the same form and posting it via ajax, my concern is the ajax is working for 1st form but not working from second form, below is the code im using.
<form action="http://localhost/comment" method="post" accept-charset="utf-8">
<input type="text" name="comment_text" value="" id="comment_text" size="35" class="comment_text">
<input type="submit" id="post_comment" name="post_comment" value="submit comment" class="post_comment" >
</form>
<form action="http://localhost/comment" method="post" accept-charset="utf-8">
<input type="text" name="comment_text" value="" id="comment_text" size="35" class="comment_text">
<input type="submit" id="post_comment" name="post_comment" value="submit comment" class="post_comment" >
</form>
<form action="http://localhost/comment" method="post" accept-charset="utf-8">
<input type="text" name="comment_text" value="" id="comment_text" size="35" class="comment_text">
<input type="submit" id="post_comment" name="post_comment" value="submit comment" class="post_comment" >
</form>
<form action="http://localhost/comment" method="post" accept-charset="utf-8">
<input type="text" name="comment_text" value="" id="comment_text" size="35" class="comment_text">
<input type="submit" id="post_comment" name="post_comment" value="submit comment" class="post_comment" >
</form>
<script type="text/javascript">
$('.post_comment').click(function() {
var form_data = {
csrfsecurity: $("input[name=csrfsecurity]").val(),
post_text: $('.comment_text').val()
};
$.ajax({
url: "<?php echo site_url('/comment'); ?>",
type: 'POST',
data: form_data,
success: function(response){
$(".home_user_feeds").html("markUpCreatedUsingResponseFromServer");
}
});
return false;
});
</script>
Your problem is post_text: $('.comment_text', this).val() which will give you the value of the first selected .comment, what you want is the .comment in the current form. Try
<script type="text/javascript">
$('.post_comment').click(function() {
var form_data = {
csrfsecurity: $("input[name=csrfsecurity]").val(),
post_text: $(this).closest('form').find('.comment_text').val()
};
$.ajax({
url: "<?php echo site_url('/comment'); ?>",
type: 'POST',
data: form_data,
success: function(response){
$(".home_user_feeds").html("markUpCreatedUsingResponseFromServer");
}
});
return false;
});
</script>
Also element ids should be unique.

Resources