Search with ajax on click and show results in same page laravel - javascript

I've setup a view which contains a search form:
<form>
<input type="hidden" id="product_id" value="{{$tour->id}}">
<div class="form-group col-md-4">
<label>Date:</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control pull-right" id="start" placeholder="Start Date">
</div>
</div>
<div class="form-group col-md-4">
<label>End:</label>
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="text" class="form-control pull-right" id="end" placeholder="End Date">
</div>
</div>
<div class="form-group col-md-4" id="dateprice-search">
<label></label>
<button type="submit" class="btn" id="btn-search" >
Search
</button>
</div>
The below is the ajax code to handle the request of the form:
$(document).ready(function() {
$('#dateprice-search').on('click', '#btn-search', function() {
$.ajax({
type: 'post',
url: '/date-price',
data: {
'_token': $('input[name=_token]').val(),
'product_id': $("#product_id").val(),
'start': $("#start").val(),
'end': $("#end").val()
},
success: function(data) {
$('.shadow-z-1').show();
$('.shadow-z-1').append("<tr class='liquid-row><td>" + data.start + "</td><td>"+ data.end + "</td><td>" + data.end + "</td><td><a class='btn-m btn btn-m-success'>Available</a></td></tr>");
}
});
});
});
Route:
Route::post('/date-price','GetPublicController#datePrice')
->name('searchDate');
And finally method in controller to give the results:
public function datePrice(Request $request){
$start = $request->start;
$end = $request->end;
$dates = DatePrice::where('tour_id','=',$request->product_id)
->whereBetween('start', array($request->start, $request->end))
->whereBetween('end', array($request->start, $request->end))
->get();
return response()->json($dates);
}
At first the url looks like this before submitting the form http://localhost:8000/trips/popular/trekking/test and url becomes http://localhost:8000/trips/popular/trekking/test? after clicking the search button. Console section of inspect element shows no error in script. What mistake I had made over here ?

It mean your form submiting to same page due to type="submit"
1) change to type="button"
<button type="button" class="btn" id="btn-search" >
2) Here click event should be for button not to div so change the selector and add e.preventDefault(); in jquery to prevent the default submit .
$('#btn-search').on('click', '#btn-search', function() { e.preventDefault(); });
note :
1st : your action attribute missing so form will be submit same page .
2nd : your method attribute missing so it will take default GET method

You have given button type as submit, either remove it as
<button type="button" class="btn" id="btn-search" >
Search
</button>
or use the jquery preventDeafult() function to prevent the default behavior of submit button i.e form submit in your button click event as
$(document).ready(function() {
$('#dateprice-search').on('click', '#btn-search', function(e) {
e.preventDefault();
//your ajax code
});
});

Related

laravel ajax form won't execute submit button

Basically my form adds to blade by help of javascript and then i can fulfill data and hit the save button.
The issue is save button doesn't work.
Here is screen record of the process and error you can watch
Code
This function will add new row and form to view where you see in video i filled input and hit save button
var textFieldsCount = 0;
function addTextField(){
textFieldsCount++;
var textfieldhelper = '';
var my_row = $('<div class="row mt-20" id="textField-' + textFieldsCount + '">');
var my_html = '{{Form::open()}}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><div class="col-md-4">{{ Form::label('customsubspecifications', 'Specifications') }}<select class="form-control" id="specification_id" name="specification_id"><option value="">Select</option>'+specifications+'</select></div>';
my_html += '<div class="col-md-4">{{ Form::label('text_dec', 'Your Custom Input') }}'+
'<input class="text_dec form-control" onkeypress="myFunction()" type="text" name="text_dec[]" id="'+ textFieldsCount.toString() +'">'+
'</div>';
my_html += '<div class="col-md-4">{{ Form::label('', 'Actions') }}<br><button type="button" class="btn btn-danger btn-xs" onclick="removeTextField(\'textField-' + textFieldsCount.toString() + '\')">Remove</button><button type="button" class="btn btn-info btn-xs" onclick="addTextField();">Add New</button><button type="button" id="custmodalsave" class="myButton custmodalsave btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';
my_row.html(my_html);
$('#fields').append(my_row);
}
here is where thing happen and I actually try to send data to back-end
$("#custmodalsave").click(function(e){
e.preventDefault();
$.ajax({
type: "post",
url: "{{ url('admin/addnewcustomsubspecifications') }}",
data: {
'_token': $('input[name=_token]').val(),
'product_id': $('#product_id').val(),
'specification_id': $('#specification_id').val(),
'text_dec': $('.text_dec').val(),
'longtext_dec': $('.longtext_dec').val(),
},
success: function (data) {
$('#custspacmsg').append('<span class="text-success">Custom Specification added successfully in your product!</span>');
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});
});
just to be clear I attached output form of my first ajax code so you
can see how things are printed
<div class="row mt-20" id="textField-1">
<form method="POST" action="http://newsite.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">
<label for="customsubspecifications">Specifications</label>
<select class="form-control" id="specification_id" name="specification_id">
<option value="">Select</option>
<option value="1">CPU</option>
<option value="2">ram</option>
<option value="3">LCD</option>
<option value="4">Mouse</option>
<option value="5">Graphic</option>
<option value="6">Keyboard</option>
</select>
</div>
<div class="col-md-4">
<label for="text_dec">Your Custom Input</label>
<input class="text_dec form-control" onkeypress="myFunction()" name="text_dec[]" id="1" type="text">
</div>
<div class="col-md-4">
<label for="">Actions</label>
<br>
<button type="button" class="btn btn-danger btn-xs" onclick="removeTextField('textField-1')">Remove</button>
<button type="button" class="btn btn-info btn-xs" onclick="addTextField();">Add New</button>
<button type="button" id="custmodalsave" class="myButton custmodalsave btn btn-xs btn-success" style="display: inline-block;">Save</button>
</div>
</form>
</div>
PS: I should add that I have this function working on bootstrap modal
but i wanted to change modal the way you see in video (print by click in blade)
Back-End is working perfectly since I can save data by this Ajax code with modal. Whatever the issue is, is coming from here.
You're defining your click function as
$("#custmodalsave").click(function(e){
But, when this function is defined, $("#custmodalsave") is not available in your DOM as you're appending it:
$('#fields').append(my_row); // my_row contains `[...] id="custmodalsave"`
To fix this, simply use event delegation:
$("body").on("click", "#custmodalsave", function(e){ ... });
For more info on event delegation, please check out the jQuery reference:
http://api.jquery.com/on/

AJAX I must double click to submit second textarea! (Laravel)

$(document).ready(function (){
$('#myForm').submit(function (e) {
e.preventDefault(); //Do not submit the form
var dataflow=$(this).serialize(); //Get the inputs value
$.post('{{route('homepage.update')}}', dataflow, function (data){ //post.create is the route name
//The request is done, do something with the server response
});
});
});
I use this to save form without refresh
Here is my route
Route::post('/homepage/update', 'AdminController#Update')->name('homepage.update');
And my html
{{ csrf_field() }}
<div class="form-group">
<label for="title"><b class="fa fa-pencil"></b> Title</label>
<input id="title" class="form-control" value="{{ $article->title }}" name="title">
<br />
<label for="content"><b class="fa fa-home"></b> Desc</label>
<div class="box-body pad">
<textarea id="content" name="content" rows="10" cols="80">
{{ $article->content }}
</textarea>
</div>
</div>
<center>
<div class="form-group">
<button type="submit" class="btn btn-success btn-sm"><b class="fa fa-save"></b> Submit</button>
</form>
My function who update ajax data
public function HomePage(Request $r) {
$article = Article::find(1);
$article->title = $r->input('title');
$article->content = $r->input('content');
$article->homepage = 1;
$article->save();
}
The problem is i must click twice button to save two forms when i click one it submit only title! Please help how to fix that

Link in keyup function is not working

Here is screen shot of my problemI am using codeigniter and ajax.When keyup function is call on search bar then data is shown in suggestion box but when i click on link which is shown on suggestion box then this click is not working.No error of any script file.
Here is code of my view file:
<div class="container-fluid my_searchbar">
<div class="container my_searchbar_container">
<div class="nav nav-justified navbar-search navbar-nav">
<form class="search navbar-search" method="post" action="index.html" >
<div class="input-group">
<input type="text" name="search_area" id="search_area" placeholder="Search Area" class="form-control input-lg">
<div class="input-group-btn">
</div>
<input type="text" name="search_pro" id="search_pro" placeholder="Search Professional Category" class="form-control input-lg">
<ul id="show_search_pro" class="results" >
</ul>
<div class="input-group-btn">
Search
</div>
</div>
</form>
</div>
</div>
</div>
</div>
Here is my ajax code in view file.
$('#search_pro').keyup(function(){
// alert($(this).val());
var location_field = $('#search_area');
var search_cal_field = $(this);
$.ajax({
type: 'POST',
url: 'http://localhost/JustClick/User/search_professional',
cache : false,
dataType : 'html',
data :{location_id:location_field.val(), category_id:search_cal_field.val()},
success:function(data)
{
$('#show_search_pro').html(data);
}
});
});
Here is code of my controller through using ajax i get data on view page:
public function search_professional()
{
if($this->input->is_ajax_request())
{
$professional = $this->UserModel->search_professional($this->input->post('location_id',true),$this->input->post('category_id',true));
foreach ($professional as $row)
{
echo '
<li>
<a class="s_pro" href="'.base_url('Professional/show_professional_detail/'.$row->pro_id).'">'.$row->firstname.' '.$row->lastname.'<br /><span>Description...</span></a></li>';
}
}
else
{
show_404();
}
}
Help me how i solve this problem.

Ajax PUT method not hitting the server

I have a login form and I am trying to login using a PUT method as to store the logged-in username. But for some reason it's not hitting the server and not logging in. Could you please help?
I want this to go to the login page and failing to do so. Please help
Below is the code for the same:
HTML:
<form name="login" class="login-form request-form form-horizontal" method="post" id="login-user">
<p class="pl-sign">Please Sign In</p>
<div class="form-group" id="login-fields">
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"><span class="text--white glyphicon glyphicon-user"></span></i>
</span>
<input type="text" name="user" id="user" placeholder="Username" class="form-control" required/>
</div>
</div>
</div>
<div class="form-group" id="login-fields">
<div class="cols-sm-10">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"><span class="text--white glyphicon glyphicon-lock"></span></i>
</span>
<input type="password" name="pass" id="pass" placeholder="Password" class="form-control" required/>
</div>
</div>
</div>
<input class="view sign-in-app" type="submit" value="Sign In" id="submit-login" />
<div class="forgot-up">
forgot username/password ?
</div>
</form>
jQuery:
$("#login-user").validate({
submitHandler: userLogin
});
function userLogin() {
var username = $('#user').val();
var password = $('#pass').val();
var data = $("#login-user").serialize();
var userUrl = 'http://website.com/DatabaseName/Tablename/' + username + '/login?' + password + '';
console.log(data);
$.ajax({
url: userUrl,
type: 'PUT',
data: data,
success: function(data) {
if (data == 0) {
window.location.href = "http://website.com/page2.html";
} else if (data == -1) {
("#error").html('<span class="error">Incorrect username or password</span>');
} else {
$("#error").fadeIn(1000, function() {
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> ' + data + ' !</div>');
});
}
}
});
}
If you don't want a form submit to laod a new page (or relaod the current one if action isn't defined in the form), use preventDefault() method on the passed in event to the event handler
function userLogin(e) {
e.preventDefault();
... rest of your code
I'm assuming
submitHandler: userLogin
in the validate object will pass on the event object

Call function on 'Enter' press

Here is my HTML code:
<div class="panel-footer">
<div class="input-group">
<input id="btn-input" class="form-control input-sm chat_input message" type="text" placeholder="Write your message here..." ng-model="messageToSend">
<span class="input-group-btn">
<button id="btn_chat" class="btn btn-primary btn-sm btn_chat" value="79">Send</button>
</span>
</div>
</div>
And here is my jQuery code:
$('.message').keypress(function (e) {
if (e.which == 13) {
var msg = $(this).val();
var id = $(this).closest('span').next('button.btn_chat').val();
alert(id+" "+msg);
sendMessage(msg,id);
}
e.preventDefault();
});
Here is my send message function:
var sendMessage = function(messageToSend,id) {
// $log.debug(messageToSend);
id = parseInt(id);
if(messageToSend.length != 0){
$http.post('/chat/send/',{message:messageToSend,chat_room_id:id}).then(function (response) {
$log.debug(response.data);
$('input.message').val("");
});
}
};
Now I want to call my sendMessge function in it, when enter button press after message written.
But when I press enter button my jQuery not run. How can I solve this problem?
Angular provides mechanism, You can create a form and use ngSubmit to bind function to execute when form is submitted.
So, when Enter is pressed form will be submitted.
HTML
<div class="panel-footer">
<div class="input-group">
<form ng-submit="sendMessage(messageToSend, 79)">
<input id="btn-input" class="form-control input-sm chat_input message" type="text" placeholder="Write your message here..." ng-model="messageToSend" />
<span class="input-group-btn">
<button id="btn_chat" class="btn btn-primary btn-sm btn_chat" value="79">Send</button>
</span>
</form>
</div>
</div>
Add method in your controller
$scope.sendMessage = function(messageToSend,id) {
// $log.debug(messageToSend);
id = parseInt(id);
if(messageToSend.length != 0){
$http.post('/chat/send/',{message:messageToSend,chat_room_id:id}).then(function (response) {
$log.debug(response.data);
$('input.message').val("");
});
}
};
If you don't want to use form, then you can use ngKeyup
<input ng-keyup="$event.keyCode == 13 ? sendMessage(messageToSend, 79): null" ng-model="messageToSend" >
You are using the line
var id = $(this).closest('span').prev('button.btn_chat').val();
however, the $(this) in that case is an <input> element, which isn't inside a <span>. Therefore .closest('span') will be returning an empty set.

Categories