I want to load some ajax data after selected a value from dropdown in textbox.
Eg: After selecting a teacher from dropdown, teachers remaining credit and credit_taken value should be load. How do I do it with ajax?
NB: Here teacher value has selected from another dropdown selecting in Ajax
<script>
$('#teacher').on('change',function(e){
var teach_id = $('#teacher option:selected').attr('value');
var info=$.get("{{url('ajax-teach')}}",{teach_id:teach_id});
info.done(function(data){
$.each(data,function(index,subcatObj){
/// Here will be the loaded code ///
});
});
info.fail(function(){
alert('ok');
});
});
</script>
Here is my controller:
Route::get('ajax-teach',function(Request $request){
$teach_id = $request::input(['teach_id']);
$teachers=\App\Teacher::where('teacher_id','=',$teach_id)->get();
return Response::json($teachers);
});
Here is the view Page:
<div class="form-group">
<label for="">Teacher</label>
<select class="form-control input-sm" required name="teacher_id" id="teacher" >
<option value=""></option>
</select>
</div>
<div class="form-group">
<label>Credit to be Taken</label>
<input type="text" name="credit_taken" id="credit_taken" class="form-control" required placeholder="Credit to be Taken">
</div>
<div class="form-group">
<label>Remaining Credit</label>
<input type="text" name="remaining_credit" class="form-control" required placeholder="Remaining Credit">
</div>
In your routes (routes/web.php)
Route::get( '/ajaxteach', array(
'as' => 'ajaxteach',
'uses' => 'TeachController#get_teach'
) );
In your controller (app/Http/Controllers/TeachController.php)
class TeachController extends Controller
{
public function get_teach(Illuminate\Http\Request $request)
{
$teach_id = $request->get('teach_id');
$teachers=\App\Teacher::where('teacher_id','=',$dept_id)->get();
return response()->json(['response' => $teachers]);
}
}
Then in your AJAX script you can use at least one of the following ways
use absolute url in javascript code
var base_url = 'http://localhost/laravel'
$.ajax({
type: "GET",
url : base_url+"/ajaxteach",
data : dataString,
success : function(data){
console.log(data);
}
use url() with route
$.ajax({
type: "POST",
url : "{{url('ajaxteach')}}",
data : dataString,
success : function(data){
console.log(data);
}
Related
How to set value to customerNumber(field from Marketing table) from database when I select an option from Request Number drop down list?
<div class="col-sm-2">
<label class="label" for="request_id">Request Number:</label>
<select class="form-control option" id="request_id">
<option >0 - Request Number</option>
#foreach ($customer_requests as $customer_request)
<option value={{$customer_request->id}}>{{$customer_request->id}} -{{$customer_request->requestNumber}} </option>
#endforeach
</select>
</div>
<div class="col-sm-2">
<label class="label" for="customerNumber" >Customer Number:</label>
<input type="text" class="form-control text" id="customerNumber" name="customerNumber">
</div>
I am a learner of laravel and I want to know should jQuery be used or not? And how?
<script>
$("#request_id").on({
click: function() {
}, keypress: function() {
$( this ).addClass( "inside" );
var val = $(this).val();
var data = Marketing::find(val);
$("#customerNumber").attr("value", data[customerNumber] );
}
});
</script>
for the jquery you can try like this one:
$('#request_id').change(function() {
var req_id= $(this).val();
$.ajax({
url:'{{url('/get/ref')}}/'+req_id,
method:'GET',
contentType: false,
processData: false,
success:function(result){
$("#customerNumber").val(result);
}
});
});
then, create a new controller to return customerNumber. something like:
public function customerNumber($req_id = 0){
$data = Marketing::find($req_id);
return $data->customerNumber;
}
I have a form, which I have divided in to there parts using tabs, in my second tab I'm using a select option and then try to auto fill 2 text box's and one text area using Ajax ,but although console log shows that ajax return the object but it doesn't fill the required fields.
tab
<div class="tab-pane fade " id="package_details">
select option
<select name="package" id="packageid" >
<option selected > Select a Package </option>
#foreach($package as $c)
<option value="{{$c->id}}">{{$c->tour_name}}</option>
#endforeach
</select>
Text fields i need auto filling
<input type="number" name="no_of_days" id="no_of_days" class="form-control"
placeholder="Days" >
<input type="number" name="cost" id="cost" class="form-control"
placeholder="Price" >
<textarea rows="4" cols="50" class="form-control" id="description" name="description" placeholder=" Package Details" ></textarea>
my Ajax code
$(document).on('change', '#packageid', function(e) {
e.preventDefault();
var pkid = $(this).val();
$.ajax({
type:'POST',
url: "{{ route('package.tour') }}",
dataType: "json",
data:{
'_token':$('input[name=_token]').val(),
'selectedid': pkid
},
success: function(data){
// console.log(data);
$('#description').val(data.description);
$('#no_of_days').val(data.no_of_days);
$('#cost').val(data.cost);
}
});
});
Function in my controller
public function getPackage(Request $request)
{
$data = packages::where('id', $request->selectedid)->get();
return response()->json($data);
}
what is wrong with my Ajax / JQuery code ?
check using like this in ajax response :
$("textarea#description").val(data.description);
$("input#no_of_days").val(data.no_of_days);
$("input#cost").val(data.cost);
I finally figured out ,since response is an array i had to use $("#description").val(data[0].description); and it works !
I have some problems with receiving data when using an ajax call to EDIT my data. I'm trying to get data that the user has filled in but every time my data is empty or 'null'. Do i need to pass data in ajax call? Or are there other ways in laravel to get the data?
My code at the moment as we speak:
showuser.blade.php
<div class="comments">
#if(count($user->cars))
<h1>Auto in reparatie</h1>
<hr>
#foreach($user->cars as $car)
<!-- Form to show each car and edit / delete the cars -->
<!--<form action="{{ action('CarController#edit', [$user->id, $car->id]) }}" method="POST">-->
<form>
<div class="form-group">
<label for="brand">Merk:</label><br>
<select name="brand">
#foreach($brands as $brand)
<option value="{{$brand->id}}"{{ $brand->id == $car->brand_id ? ' selected="selected"' : '' }}>{{$brand->brandname}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="year">Bouwjaar:</label><br>
<input type="text" value="{{$car->year}}" name="year">
</div>
<div class="form-group">
<label for="licentsplate">Kenteken:</label><br>
<input type="text" value="{{$car->licensplate}}" name="licenseplate">
</div>
<div style="float: left; width: 80px">
<input type="submit" class="btn btn-primary" value="Edit" id="{{$car->id}}" name="editcar" />
</div>
</form>
<form>
<div class="form-group">
<button class="btn btn-primary" name="deletecar" id="{{$car->id}}">Delete</button>
</div>
</form>
#endforeach
#endif
</div>
Script
<script type="text/javascript">
$( document ).ready(function() {
$('[name="editcar"]').click(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: '/users/{{$user->id}}/cars/'+this.id,
success:function(data){
if(!data.error){
location.reload(true);
}
}
})
});
});
</script>
Routes
Route::post('/users/{userId}/cars/{carId}', 'CarController#edit');
CarController.php
// Function to edit a car by ID
public function edit($userId, $carId)
{
$car = Car::where('id', $carId)->where('user_id', $userId)->first();
$car->brand_id = request('brand');
dd(request('year'));
$car->year = request('year');
$car->licensplate = ('licenseplate');
$car->save();
}
If I dump and die request('brand'), request('year'), request('licenseplate') i get 'null'.
EDIT:
If I dd $car in my controller, i get the car that i need. Means that there is no problemen finding the right car.
Thx for reading!
You aren't posting any data in the AJAX request. Pass the form values through in an object.
var form = $(this).find('form');
var licenseval = form.find('input[name=licenseplate]').val();
var yearval = form.find('input[name=year]').val();
var brandval = form.find('select[name=brand]').find(":selected").val();
$.ajax({
type: "POST",
data: {licenseplate: licenseval, year: yearval, brand: brandval}
url: '/users/{{$user->id}}/cars/'+this.id,
success:function(data){
if(!data.error){
location.reload(true);
}
}
});
Change following lines:
public function edit($userId, $carId)
to
public function edit(Request $request, $userId, $carId)
and use
use Illuminate\Http\Request;
after that you can get $userId, $carId to use inside the controller function.
As per your ajax call you are only calling the route
Route::post('/users/{userId}/cars/{carId}', 'CarController#edit');
but you are not passing any other value. Your application is working as expected.
$.ajax({
type: "POST",
url: '/users/{{$user->id}}/cars/'+this.id,
//data: dataObject, ----->Missing Data which you want to pass (brand, year, licenceplate)
success:function(data){
//...
}
})
You are iterating through multiple $cars you need to get current car's data and pass to ajax call.
I am trying to display an <input> value base on a selected value of a dropdown list using jquery ajax.
This is the markup for my form -
<div class="form-group">
<label for="" class="control-label">District</label>
<div class="element">
<select class="form-control" id="district">
<?php echo $option; ?>
</select>
</div>
</div>
<div class="form-group">
<label for="" class="control-label">Province</label>
<div class="element">
<input type="text" class="form-control province" placeholder="Province" value="" disabled>
</div>
</div>
Just I need to display province input's value When selecting a district from above dropdown.
This is my ajax code -
$("#district").change(function(event) {
var id = $("#district").val();
//alert(data);
/* Send the data using post and put the results in a div */
$.ajax({
url: "./includes/process_province.php",
type: "post",
data: id,
success: function(){
alert('Submitted successfully');
},
error:function(){
alert("failure");
}
});
// Prevent default posting of form
event.preventDefault();
});
When I selecting a district from the dropdown its going to this alert alert('Submitted successfully');. But I am not sure how to display PHP processing value in my text field.
This is my PHP code from proccess_province.php
// Require the configuration file before any PHP code:
require('./configuration.inc.php');
// Need the database connection:
require('../'.MYDB);
if(isset($_POST['id'])) {
$province_id = (int)$_POST['id'];
// Select exsiting data for an user and display them in the form for modify
$prep_stmt = " SELECT province
FROM province
WHERE province_id = ?";
$stmt = $mysqli->prepare($prep_stmt);
if ($stmt) {
// Bind "$userId" to parameter.
$stmt->bind_param('i', $province_id);
// Execute the prepared query.
$stmt->execute();
$stmt->store_result();
// get variables from result.
$stmt->bind_result($province);
// Fetch all the records:
$stmt->fetch();
$db_province = filter_var($province, FILTER_SANITIZE_STRING);
//echo $province;
} else {
echo 'Database error';
}
echo $db_province;
}
Hope somebody may help me out.
Thank you.
Since you echo the value of the province in the ajax file, you need to set the value based on that response. Try this:
$.ajax({
url: "./includes/process_province.php",
type: "post",
data: id,
success: function(data){
$('#province').val(data);
alert('Submitted successfully');
},
error:function(){
alert("failure");
}
});
And your markup:
<div class="form-group">
<label for="" class="control-label">Province</label>
<div class="element">
<input id="province" type="text" class="form-control province" placeholder="Province" value="">
</div>
</div>
If you want to set the value of input same as your select option value, you can change your success callback to this-
$.ajax({
url: "./includes/process_province.php",
type: "post",
data: id,
success: function(){
$('.province').val(id);
},
error:function(){
alert("failure");
}
});
Or, if you are bothered about the ajax response and populate the value of input based on the ajax response, you can access the data being returned as follows-
$.ajax({
url: "./includes/process_province.php",
type: "post",
data: id,
success: function(data){
// access data here and do something
},
error:function(){
alert("failure");
}
});
Add to php file -
$db_province = filter_var($province, FILTER_SANITIZE_STRING);
echo json_encode($db_province);
at the end.
On the html page -
<input type="text" id="province" class="form-control province" placeholder="Province" value="" readonly>
then set the response to the field value -
success: function(response){
$('#province').val(response)
alert('Submitted successfully');
},
In the the form change the code as,
<div class="form-group">
<label for="" class="control-label">Province</label>
<div class="element">
<input type="text" id="province" class="form-control province" placeholder="Province" value="">
</div>
</div>
In script section use,
<script type="text/javascript">
$("#district").change(function(event) {
var id = $("#district option:selected").val();
/* Send the data using post and put the results in a div */
$.ajax({
url: "./includes/process_province.php",
type: "post",
data: {id : id},
dataType: "json",
success: function(){
$('#province').val(data.province);
alert('Submitted successfully');
},
error:function(){
alert("failure");
}
});
// Prevent default posting of form
event.preventDefault();
});
</script>
In the proccess_province.php file, instead of
echo $db_province;
use,
echo json_encode(array('province' => $db_province));
Hope it helps.
I am trying to save data submitted from a form into my mysql database and and then update the div element with the last posted item prepended to the list in the div.
Right now I am only trying to get a response back, I'm not worried about having the formatting correct at the moment.
My problem is the form won't submit with e.preventDefault(); in place, but without it the form does the normal method of posting to the db then refreshing the page.
Here is my AJAX call:
$(document).ready(function() {
$('form#feedInput').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: $('.feed-input').val(),
dataType: "html",
success: function(data){
debugger;
$('#feed-container').prepend(data);
},
error: function() { alert("Error posting feed."); }
});
});
});
I don't think it's necessary for me to post my controller code, seeing as how my issue is the form won't make it past the e.preventDefault(); function.
How can I get this form to submit via AJAX if the e.preventDefault() function is stopping it before it can reach the $.ajax() function?
The data attribute of the ajax call is invalid. It should be either in JSON format { key: $('.feed-input').val() } or in query format 'key='+$('.feed-input').val().
Also there is an unnecessary debugger variable in the success method.
A working code could be:
$('form#feedInput').submit(function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: form.serialize(), // <--- THIS IS THE CHANGE
dataType: "html",
success: function(data){
$('#feed-container').prepend(data);
},
error: function() { alert("Error posting feed."); }
});
});
Html part in view
<form id="comment" method="post">
<h2>Enter Your Details</h2>
<center><div id="result"></div></center>
<div class="form_fld">
<label>Name</label>
<input type="text" placeholder="Enter Your Full Name" name="name" required="">
</div>
<div class="form_fld">
<label>Email ID</label>
<input type="text" placeholder="Enter Email ID" name="email" required="">
</div>
<div class="form_fld">
<label>Contact Number</label>
<input type="text" placeholder="Enter Contact Number" name="contact" required="">
</div>
<div class="form_fld">
<label>Developer</label>
<select name="developer">
<option>Lotus</option>
<option>Ekta</option>
<option>Proviso</option>
<option>Dosti</option>
<option>All</option>
</select>
</div>
<div class="form_fld">
<button type="submit" id="send">Submit</button>
</div>
</form>
After Html Part Just put ajax request
<script type="text/javascript" src="<?php echo base_url('assets/'); ?>js/jquery.js"></script>
<script>
$(function(){
$("#comment").submit(function(){
dataString = $("#comment").serialize();
$.ajax({
type: "POST",
url: "home/contact",
data: dataString,
success: function(data){
// alert('Successful!');
$("#result").html('Successfully updated record!');
$("#result").addClass("alert alert-success");
}
});
return false; //stop the actual form post !important!
});
});
</script>
Within Controller
public function contact()
{
$ip = $_SERVER['REMOTE_ADDR'];
$data = array('name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'number' => $this->input->post('contact'),
'developer' => $this->input->post('developer'),
'ip' => $ip,
'date' => date("d/m/Y"));
$result = $this->User_model->contact($data);
print_r($result);
}
You don't have to use preventDefault(); you can use return false; in the end of function submit() but I doubt this is the problem.
You should also use url encoding on $('.feed-input').val() use encodeURIComponent for this.
You should also check if you have errors in your console.
To determine if default action is prevented you can use e.isDefaultPrevented(). By default action in this case I mean submit action of the form with id feedInput.
You didn't name your param in data. Check jquery ajax examples.
You are probably getting an error e.preventDefault(); is not stopping the ajax.
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: $("#form").serializeArray(),
success: function(resp){
$('#container').html(resp);
},
error: function(resp) { alert(JSON.stringify(resp)); }
});