Jquery pass value to radio button - php

I used jquery ajax code to run search function.
here's my ajax so far :
$('button[type="search"]').click(function(e) {
$.ajax({
url: "{{ route('fine.search') }}",
type: "POST",
data: {
'_token' : '{{csrf_token() }}',
'driver_id' : $('select[name="driver_id"]').val(),
'fine_date' : $('input[name="fine_date"]').val(),
},
success: function(data) {
if(data.status == true) {
var result= $('#search-result');
$.each(data.getCarbyDriver, function(i, data) {
PlateEle = $('<input/>').attr({ type: 'radio', name:'rad'});
$("#search-result").html(data.plate_no);
StartEle = $('<div />').html(data.start_time);
EndEle = $('<div />').html(data.end_time);
});
$('#search-result').append(PlateEle, StartEle, EndEle);
}
},
error: function(data) {
}
});
});
and the data being returned like this on my network (inpect element) :
car_id:5
driver_id:1
end_time:"2016-11-16 18:00:00"
plate_no:"DFE82846J"
start_time:"2016-11-16 08:00:00"
working_date:"2016-11-16 00:00:00"
here's the form blade code so far :
<div class="row top">
<div class="col-xs-4 col-sm-4 col-md-4">
<div class="form-group">
<label class="control-label">Driver Name:</label>
{!! Form::select('driver_id', $driver, null, array('class' => 'form-control')) !!}
</div>
</div>
<div class="col-xs-4 col-sm-4 col-md-4">
<div class="form-group">
<label>Fine Date:</label>
{!! Form::text('fine_date', null, array('id' => 'datetimepicker', 'class' => 'form-control')) !!}
</div>
</div>
<div class="col-xs-4 col-sm-4 col-md-4">
<div class="form-group filter-btn">
<button class='btn btn-info' type='search'>Search</button>
</div>
</div>
</div>
<div class="row mid ">
<div class="col-xs-4 col-sm-4 col-md-4">
<div id="search-result"></div>
</div>
</div>
the issue is I can't save. it throws error car_id' cannot be null'.
how do i pass car_id into my radio, so once i clicked on radio button it save car_id by plate_no
im using laravel 5.3

It's unclear to me where you have PlateEle, StartEle and EndEle defined. Are those global vars defined elsewhere in your javascript?
Either way, as I understand it, car_id is being returned by the ajax POST, so it's in the data var returned to your success function?
If you want to set the value in the radio element you're creating dynamically I think it would be this:
PlateEle = $('<input/>').attr({ type: 'radio', name:'rad'}).val(data.car_id);
Here is an example I mocked up. I am creating a data object like what I believe you're saying is being returned. When I load this page I get a radio input created. Does this work for you?
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var result= $('#search-result');
//mocking up what I assume your data object looks like
var data = {};
data.car_id=5;
data.driver_id=1;
data.end_time="2016-11-16 18:00:00";
data.plate_no="DFE82846J";
data.start_time="2016-11-16 08:00:00";
data.working_date="2016-11-16 00:00:00";
PlateEle = $('<input/>').attr({ type: 'radio', name:'rad'}).val(data.car_id);
console.log(PlateEle);
$("#search-result").html(data.plate_no);
StartEle = $('<div />').html(data.start_time);
EndEle = $('<div />').html(data.end_time);
$('#search-result').append(PlateEle, StartEle, EndEle);
});
</script>
</head>
<body>
<div id="search-result"></div>
</body>
</html>

To save the value on your input radio this could should make the trick:
$.ajax({
url: "{{ route('fine.search') }}",
type: "POST",
data: {
'_token' : '{{csrf_token() }}',
'driver_id' : $('select[name="driver_id"]').val(),
'fine_date' : $('input[name="fine_date"]').val(),
},
success: function(data) {
if(data.status == true) {
var result= $('#search-result');
$.each(data.getCarbyDriver, function(i, data) {
PlateEle = $('<input type="radio" name="rad" val="'+data.car_id+'">'+data.car_id+'</input>');
$("#search-result").html(data.plate_no);
StartEle = $('<div />').html(data.start_time);
EndEle = $('<div />').html(data.end_time);
});
$('#search-result').append(PlateEle, StartEle, EndEle);
}
},
error: function(data) {
}
});

Well, adding or changing value of radio buttons is simple. For your ID in database you could also use some data-* attribute on your radio button. But remember, data-* on your form elements will not be sent to the server, if the form is submitted in browser. For more details see my working code example below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test Radio Button</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
var $rdBtn = null;
var $txtReader = null;
var $txtRdBtnValueReader = null;
function doReady() {
$rdBtn = $("#myRdBtn");
$txtReader = $("#txtDataReader");
$txtRdBtnValueReader = $("#txtRdBtnValueReader");
$("#btnSetValue")
.click(function () {
// note the jQuery .val("some text") issue at this point. You will need .attr("value") for setting
// .val() is just helpful for reading the current value!
$rdBtn.attr("value", "my new value");
$txtRdBtnValueReader.attr("value", $rdBtn.val());
});
$("#btnSetDataValue")
.click(function () {
$rdBtn.data("mykey", "myval");
$txtReader.attr("value", $rdBtn.data("mykey"));
});
}
$(document).ready(doReady);
</script>
</head>
<body>
<button type="button" id="btnSetValue">set Value</button>
<button type="button" id="btnSetDataValue">set data-* value</button>
<div id="myRadioButtonWrapper">
<label for="myRdBtn">your value choice</label>
<input type="radio" id="myRdBtn" name="myRdBtn" value="to be replaced" />
<br />
<label for="txtRdBtnValueReader">radio value</label>
<input type="text" id="txtRdBtnValueReader" name="txtRdBtnValueReader" readonly />
<br />
<label for="txtDataReader">data-mykey value</label>
<input type="text" id="txtDataReader" name="txtDataReader" readonly />
</div>
</body>
</html>
It is also a common way if you need more data assigned to an input field to serialize its value as json. So, that you could have a whole object sent to the server. It's easy to parse again in PHP. Maybe this could help you, too. Good luck!

Related

Ajax jquery(post) doesn't pass data to php [duplicate]

This question already has answers here:
Receive JSON POST with PHP
(12 answers)
Closed 9 months ago.
I am trying to pass data to my php page:
<?php
var_dump($_POST);
if (isset($_POST['goal']) && isset($_POST['amount'])){
$goal = $_POST['goal'];
$amount = $_POST['amount'];
$array = array(
"goal" => $goal,
"amount" => $amount
);
echo json_encode($array);
}
However as a result of var_dump $_POST I keep getting an empty array, for some reason my ajax doesn't pass the neccessary data. I tried console.logging the value of fields that I am using and their value is correct it's just that data doesn't pass on the php page.
ajax:
<script type="text/javascript">
$(document).ready(function () {
//use button click event
$("#goalBTN").click(function (e){
e.preventDefault();
let amount = $("#amount").val();
let goal = $("#goal_name").val();
$.ajax({
method: "post",
url: "target-modal-code.php",
data:JSON.stringify( {
amount: amount,
goal: goal
}),
contentType:"application/json",
success: function (response){
$("#response").text(response);
console.log(amount);
console.log(goal);
},
error: function(response) {
alert(JSON.stringify(response));
}
})
});
});
</script>
And my form is inside a modal :
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="enrollLabel">Change your goal</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form action="target-modal-code.php" name="target-form" id="target-form">
<div class="modal-body">
<form action="">
<div class="mb-3 input-control">
<label for="amount">Cost</label>
<input type="number" class="form-control" id="amount" name="amount"
placeholder="Amount">
<small class="message" id="message-password"></small>
<br>
</div>
<div class="mb-3 input-control">
<label for="goal_name">Goal</label>
<input type="text" class="form-control" id="goal_name" name="goal_name"
placeholder="Goal">
<small class="message" id="message-password"></small>
<br>
</div>
</form>
</div>
<p class="response" id="response"></p>
<div class="modal-footer">
<div class="response">
</div>
<button type="button" id="goalBTN" class="btn btn-warning">Save changes</button>
</div>
</form>
</div>
</div>
Updated answer after some live testing with Network tab in firefox web dev tools
The problem is that the current ajax code is not sending any of the elements because of wrong content-type. Let it detect content-type automatically. For jq ajax, default seems to be contentType: application/x-www-form-urlencoded even if you don't provide it specifically.
So, this worked:
<script type="text/javascript">
$(document).ready(function () {
//use button click event
$("#goalBTN").click(function (e){
e.preventDefault();
// let amount = $("#amount").val();
// let goal = $("#goal_name").val();
var formData = {
amount: $("#amount").val(),
goal_name: $("#goal_name").val(),
};
$.ajax({
method: "post",
url: "target-modal-code.php",
// datatype:"json",
//data:JSON.stringify(formData),
data: formData,
//contentType:"application/json",
//encode: true,
success: function (response){
$("#response").text(response);
// console.log(amount);
// console.log(goal);
console.log(formData);
},
error: function(response) {
alert(JSON.stringify(response));
}
})
});
});
</script>
After little bit of fiddling, I noticed that it works if you DON'T provide it contentType at all. Otherwise, AJAX won't send GET or POST params to the server.... dont know why. I know it's weird but that's how it is in jquery ajax.
I have intentionally kept the comments for you to see what all I have tried.
So to summarize,
Don't stringify the form data,
Don't provide contentType to ajax
request.
Cheers.!
format send ajax:
$.ajax({
...
data : {
foo : 'bar',
bar : 'foo'
},
...
});
in your case: change data send format like:
data: {
amount: amount,
goal: goal
}

I wanna display json data to a card in html page using ajax

Output of my requirement
I have tried many times to get the required result in html page.
am calling a function when i check a box in html ,the function giving back result of json data and this json data i wanna display dynamically into my card style.
Here is hmtl code:
<div id="filter"style="margin-top:100px;margin-left:100px">
<h2>Filter options</h2>
<div>
<input type="checkbox" id="Samsung" checked>
<label for="Samsung">Samsung</label>
</div>
<div>
<input type="checkbox" id="iPhone" checked>
<label for="iPhone">iPhone</label>
</div>
<div>
<input type="checkbox" id="HTC" checked>
<label for="HTC">HTC</label>
</div>
<div>
<input type="checkbox" id="LG" checked>
<label for="LG">LG</label>
</div>
<div>
<input type="checkbox" id="Nokia" checked>
<label for="Nokia">Nokia</label>
</div>
</div>
<table id="phones" >
<thead>
</thead>
<tbody >
<div style="margin-top:100px;margin-left:100px;margin-right:100px" >
<div>
<label style="margin-bottom:50px;margin-left:80px"><h2>Find your best hotel</h2></label>
</div>
<div class="col-xs-12 col-sm-4" style="background-color:lavender;height:310px;width:310px"><label id="hotel_image"></label></div>
<div class="col-xs-12 col-sm-6" style="background-color:lavenderblush;"><label id="hotel_name"></label></div><br>
<div class="col-xs-12 col-sm-3" style="background-color:lavender;margin-left:100px;margin-top:10px"><label id="hotel_price"></label></div>
<div class="col-xs-12 col-sm-3" style="background-color:#ccc;margin-top:220px;margin-left:300px"><label id="book_me"></label></div>
</div>
</tbody>
</table>
Here is javascript code:
<script>
function getPhoneFilterOptions(){
var opts = [];
$checkboxes.each(function(){
if(this.checked){
opts.push(this.id);
}
});
return opts;
}
function updatePhones(opts){
$.ajax({
type: "POST",
url: "submit.php",
dataType : 'json',
cache: false,
data: {filterOpts: opts},
success: function(data){
$.each(data, function() {
$.each(this, function(k , v) {
if(k==='img_path'){
v = "<a href='image_description.html'><image src='img_path' height='300px' width='300px' ></a>";
("#hotel_image").html(v);
} else if (k==='price'){
("#hotel_price").html(v);
} else if (k==='brand'){
("#hotel_name").html(v);
}
})
});
}
})
}
var $checkboxes = $("input:checkbox");
$checkboxes.on("change", function(){
var opts = getPhoneFilterOptions();
updatePhones(opts);
});
$checkboxes.trigger("change");
</script>
am geeting data json data from submit.php like this:
[
{
"img_path":"photo1.jpg",
"price":"2000",
"brand":"AAMSOTO"
},
{
"img_path":"photo4.jpg",
"price":"2500",
"brand":"AfMSOTO"
},
{
"img_path":"photo2.jpg",
"price":"3000",
"brand":"CAMSOTO"
},
{
"img_path":"photo3.jpg",
"price":"4000",
"brand":"BAMSOTO"
}
]
Assuming data is a javascript object the following inside your success method should work:
Make sure data is a javascript object, if its not you will have to use JSON.parse() to turn the JSON data into one.
$.each(data, function() {
var imageUrl = this['img_path']
var price = this['price']
var brand = this['brand']
const img = document.createElement('img');
img.src = imgUrl;
document.getElementById('#hotel_image').appendChild(img);
document.getElementById('#hotel_price').appendChild(document.createTextNode(price));
document.getElementById('#hotel_name').appendChild(document.createTextNode(brand));
}

Laravel 5: Request data is null when using an Ajax Post Request

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.

ajax submit form with file

I have form, with ajax, that contain textarea and upload file field
I can submit only one of them.
how can I fix that?
I want to send "info" + "filesData" to the server.
Please advise.
Thank you in advanced
AJAX :
$(function() {
$("#submit").click(function() {
var file_data = $('#files').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
var files_data = form_data;
alert(files_data);
var act = 'add';
var $form = $("#addCommentForm");
var info = $form.serialize();
info += '&act=' + act ;
alert(info);
$.ajax({
type: "POST",
url: "ajax/addPost.php",
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: files_data,
success: function(data)
{
// alert(data); // show response from the php script.
$('#commentsBox').html(data);
$("#addCommentForm")[0].reset();
}
});
return false;
});
});
HTML:
<form class="form-horizontal" action='#' method="post" id="addCommentForm" enctype="multipart/form-data">
<div class="form-group">
<div class="col-md-8 col-xs-12">
<textarea class="form-control" name="post[text]"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-xs-12">
<input type="file" class="form-control" name="file" id="files">
</div>
</div>
<div class="form-group">
<label class="col-xs-2 control-label" for="textinput"></label>
<div class="col-md-8 col-xs-12">
<a class="btn btn-primary" id="submit">submit</a>
</div>
</div>
</form>
PHP
print_r ($_FILES);
print_r ($_POST);
In $.ajax call, subtitute the value of data parameter (filesData) by:
{ field1 : field1value, field2 : field2value, .... }
use as many field/value pairs as you need
you also can get the values directly like this:
{ field1 : $('#commentsBox').text(), field2 : $('#yourinput').val(), .... }

How to get Ajax to execute within an Ajax generated FancyBox?

I'm facing a problem using the FancyBox plugin. I'm trying to submit a form with Ajax and just print a nice little success message, no validation just yet, trying to get it to work. I can submit with jQuery and display the value of any input within the FancyBox. However when I try to execute Ajax it just closes the FancyBox down. I'm not an expert...
The FancyBox's content is generated using Ajax because it requires data from a database.
Here are the important code parts: (Texts are German...)
The file loaded into the FancyBox using Ajax
<script>
$("#submit").click(function() {
var login = $("#login").val();
$.ajax({
type: "POST",
url: "handleuseredit.php",
cache: false,
data: { login: login },
success: function(data){
if(data=='ok')
{
alert('Richtig.');
}
else
{
alert('Falsche Benutzername/Passwort Kombination.');
}
}
});
});
</script>
<div class="login">
<div class="widget_header">
<h4 class="widget_header_title wwIcon i_16_wysiwyg">Benutzer Bearbeiten</h4>
</div>
<div class="widget_contents lgNoPadding">
<form method="post" id="form-edit">
<p id="errormessagehere"></p>
<div class="line_grid">
<div class="g_3 g_3M"><span class="label">Benutzername</span></div>
<div class="g_9 g_9M">
<input type="text" name="login" id="login" value="<?php echo getusername($_GET['u']) ?>" class="simple_field tooltip" placeholder="Benutzername" autocomplete="off"></div>
<div class="clear"></div>
</div>
<div class="line_grid">
<div class="g_3 g_3M"><span class="label">Passwort</span></div>
<div class="g_9 g_9M">
********
</div>
<div class="clear"></div>
</div>
<div class="line_grid">
<div class="g_6">Abschicken
</div>
<div class="clear"></div>
</div>
</form>
</div>
</div>
Here's how I call the Fancy box
$(document).ready(function() {
$(".fancybox").fancybox({
'scrolling' : 'no',
'padding' : 0,
'titleShow' : false
});
});
handleuseredit.php just echoes "ok" to fullfill the data variable requirement.
You can test something like this with the version 2 of fancybox (http://fancyapps.com/fancybox/):
<script>
$("#submit").click(function() {
var login = $("#login").val();
$.ajax({
type: "POST",
url: "handleuseredit.php",
cache: false,
data: { login: login },
success: function(data){
if(data=='ok')
{
$.fancybox( '<h1>Richtig.</h1>' );
}
else
{
$.fancybox( '<h1>Falsche Benutzername/Passwort Kombination.</h1>' );
}
}
});
});
</script>

Categories