Better PHP with Json - php

Hi currently i have an app on Zend php framework, and i heavily using json to fetch data from controller. Now i am not sure whether the way i parse json data into hmtl within javascript are good or not. Below are my sample code.
controller:
public function searchAction()
{
$search = $this->getRequest()->getParam('search');
$user = new Application_Model_User();
$userMapper = new Application_Model_Mapper_UserMapper();
$usersearch = $userMapper->findByString($search);
for($i=0; $i<count($usersearch); $i++)
{
$usersearch[$i]['pic'] = $this->view->getLoginUserImage($usersearch[$i]['social_id'],$usersearch[$i]['login_type'],null,null,square);
}
$this->_helper->json($usersearch);
}
View: member.phtml
<div class="container">
<div class="clearfix page-header">
<h1 class="heading">Member Search</h1>
</div>
<div class="clearfix layout-block layout-a">
<div class="column column-alpha member-search-container">
<div class="search-input-container clearfix">
<form action="/member_search?query=" class="member-search-form" id="member-search-form" method="get" name="member_search_form" data-component-bound="true">
<fieldset>
<legend>Member Search</legend>
<label for="name_field">
<strong> Name</strong>
</label>
<span class="formNote">
(e.g. Bob Smith, Bob S.)
</span><br>
<input type="hidden" name="action_search" value="Search">
<input class="name-field" id="story-title" name="query" size="90" type="text" placeholder="search" autocomplete="off" style="width:220px;">
<div id="search-box"></div>
<div class="auto-name" style="display: none;"></div>
</fieldset>
</form>
</div>
<div class="member-search-results">
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
});
$('#story-title').keyup(function(e){
var searchbox = $(this).val();
if(searchbox == '')
{
$(".similar_story_block").hide();
}else {
$.ajax({
url:"<?= $this->baseUrl('index/search')?>",
data:{'search':$('#story-title').val()},
dataType:"json",
type:"POST",
cache:false,
success:function(data){
if(data.length > 0)
{
var divHtml = '<div class="similar_story_block" style="display: block;">'+
'<div class="head">'+
'<p>People</p>'+
''+
'</div>'+
'<ul>';
for(var count=0; count<data.length;count++)
{
if(data[count]['reviews_num'] != null )
{
data[count]['reviews_num']
}
else
{
data[count]['reviews_num'] = 0
}
divHtml+='<li>'+
'<a class="pushstate no-confirm" href="' + baseUrl + 'user/' + data[count]['user_unique_name'] + '">'+
'<div class="image">'+
'<img alt="" src="'+data[count]['pic']+'">'+
'</div>'+
'<div class="fleft col-400">'+
'<p>'+ data[count]['name'] +'</p>'+
'<span>'+data[count]['reviews_num']+' Reviews</span>'+
'</div>'+
'</a>'+
'</li>';
}
divHtml += '</ul></div>';
$("#search-box").html(divHtml);
$(".search-box").show();
}
else {
$("#search-box").html('');
$(".search-box").hide();
}
}
}) }
});
function closeSearchBox(event)
{
disabledEventPreventDefault(event);
$(".similar_story_block").hide();
}
</script>
Currently the above code will do a live query of members who already signup to the site. The code work very well, but i am not sure if this is right way of doing. Below is how it looks on chrome debug console
it seems i am exposing too much of details. It would be appreciated if anyone can suggest a better way of fetch a data from controller, or how it can be done by using partial template.
Thanks for your help !!!

You can either render your template via PHP and send HTML down the wire, or you can send JSON and render your template using JavaScript.
I would suggest the latter using something like HandlebarsJS.
Define the HTML template:
<script id="member-template" type="text/x-handlebars-template">
<p>Name: {{ name }}</p>
<p>Role: {{ role }}</p>
</script>
Our example JSON data:
var data = {"name": "Bob", "role": "Manager"};
Render our template with our JSON data:
var template = Handlebars.compile($("#member-template").html());
var html = template(data);
The html variable will be your compiled HTML that you can insert witin your <div class="member-search-results"> div.

I think if your project has a lot of visitors and this operation uses often you can relay this function to them. It's could reduce little load on the server. But it could work only if you have very many visitors (pageview). But if your project not so big you can't feel the difference and "PHP way" could be easier on my mind.

Related

Insert data into mysql database using ajax in php multiform

Hey I am trying to insert into mysql/php/ajax with multiforms on a page.
The insert works fine, but form nr 2, sets form nr 1´s data into the mysql DB.
I have 4 forms on each page, it is a firecheck on a dorm, where I need to check 28 kitchens if they keep the standard firerules.
so what I need is the little goldcorn to make this work :) so each form, only respond on the data in that form.
Here is my code:
<div class="content">
<a class="hide" id="1a" name="1a">1A</a><br>
<form action="" id="1a" method="" name="1a" novalidate="novalidate">
<div class="wrapper">
<div class="table">
<br>
<br>
<div class="row header">
<div class="cell">
1A
</div>
<div class="cell"></div>
</div>
<div class="row">
<div class="cell" data-title="Entre">
Døre
</div>
<div class="cell" data-title="Hvad du skal ordne">
<textarea cols="60" id="door" name="door" rows="3">Ok</textarea>
</div>
</div>
<div class="row">
<div class="cell" data-title="Entre">
Skilte
</div>
<div class="cell" data-title="Hvad du skal ordne">
<textarea cols="60" id="skilt" name="skilt" rows="3">Ok</textarea>
</div>
</div>
<div class="row">
<div class="cell" data-title="Entre">
Nødlys
</div>
<div class="cell" data-title="Hvad du skal ordne">
<textarea cols="60" id="lys" name="lys" rows="3">Ok</textarea>
</div>
</div>
<div class="row">
<div class="cell" data-title="Entre">
Brandtæppe
</div>
<div class="cell" data-title="Hvad du skal ordne">
<textarea cols="60" id="b_t" name="b_t" rows="3">Ok</textarea>
</div>
</div>
<div class="row">
<div class="cell" data-title="Entre">
Brandspørjte
</div>
<div class="cell" data-title="Hvad du skal ordne">
<textarea cols="60" id="b_s" name="b_s" rows="3">Ok</textarea>
</div>
</div>
</div>
<input id="dato" name="dato" type="hidden" value="<?php echo date(">") ?> <!--class = "btn btn-success btn-block" -->/>
<button class = "send" id = "insert-data1a" name = "insert-data1a" onclick = "insertData1a()" type = "button">Insert Data</button><br>
<p id = "message1a"></p>
</div><!--end wrapper -->
</form>
</div><!--end content -->
<script type = "text/javascript">
function insertData1a() {
var door = $("#door").val();
var skilt = $("#skilt").val();
var lys = $("#lys").val();
var b_t = $("#b_t").val();
var b_s = $("#b_s").val();
var dato = $("#dato").val();
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "insert-data1a.php",
data: {door: door, skilt: skilt, lys: lys, b_t: b_t, b_s: b_s, dato: dato},
dataType: "JSON",
success: function (data) {
$("#message1a").html(data);
$("p").addClass("alert alert-success");
},
error: function (err) {
alert(err);
}
});
}
</script>
the next form, looks the same, but new insert-data name and form name.
Insert Data
<script type="text/javascript">
function insertData1b() {
var door = $("#door").val();
var skilt = $("#skilt").val();
var lys = $("#lys").val();
var b_t = $("#b_t").val();
var b_s = $("#b_s").val();
var dato = $("#dato").val();
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "insert-data1b.php",
data: {door: door, skilt: skilt, lys: lys, b_t: b_t, b_s: b_s, dato: dato},
dataType: "JSON",
success: function (data) {
$("#message1b").html(data);
$("p").addClass("alert alert-success");
},
error: function (err) {
alert(err);
}
});
}
</script>
<?php
include('db.php');
$door=$_POST['door'];
$skilt=$_POST['skilt'];
$lys=$_POST['lys'];
$b_t=$_POST['b_t'];
$b_s=$_POST['b_s'];
$dato=$_POST['dato'];
$stmt = $DBcon->prepare("INSERT INTO 1_a(door,skilt,lys,b_t,b_s,dato)
VALUES(:door,:skilt,:lys,:b_t,:b_s,:dato)");
$stmt->bindparam(':door', $door);
$stmt->bindparam(':skilt', $skilt);
$stmt->bindparam(':lys', $lys);
$stmt->bindparam(':b_t', $b_t);
$stmt->bindparam(':b_s', $b_s);
$stmt->bindparam(':dato', $dato);
if($stmt->execute())
{
$res="Data Inserted Successfully:";
echo json_encode($res);
}
else {
$error="Not Inserted,Some Probelm occur.";
echo json_encode($error);
}
?>
the one for b, looks almost the same
$stmt = $DBcon->prepare("INSERT INTO 1_b(door,skilt,lys,b_t,b_s,dato)
VALUES(:door,:skilt,:lys,:b_t,:b_s,:dato)");
In addition to Bakayaro's answer, if all your forms got the same fields, you can optimize your code to use only one javascript function and one PHP insert script.
Factorise your code ! Rembember one thing : DRY (Don't Repeat Yourself)
HTML
Add a click listener on each .send button instead of using onclick() on them
Add specific ID on each different form, with kitchen ID
Add data to .send button with related form's kitchen ID
Example for kitchen 1A:
<!-- Add specific ID with kitchen ID -->
<form action="" id="kitchen1a" method="" name="1a" novalidate="novalidate">
...
<!-- Add data to each .send button with related form's kitchen and remove onclick() -->
<!-- data-kitchen="1a" -->
<button class = "send" id = "insert-data1a" name = "insert-data1a" data-kitchen="1a" type = "button">Insert Data</button>
Don't use same ID on different HTML elements, as your a and form tag.
Javascript
Use click listener
Get active form's data from each field's name
Working example based on your code:
$('.send').on('click', function(e) {
var kitchen = $(this).data('kitchen');
var form = $('#kitchen' + kitchen);
var data = {
door: form.find('[name="door"]').val(),
skilt: form.find('[name="skilt"]').val(),
lys: form.find('[name="lys"]').val(),
b_t: form.find('[name="b_t"]').val(),
b_s: form.find('[name="b_s"]').val(),
dato: form.find('[name="dato"]').val(),
// add active kitchen in your POST data
kitchen: kitchen,
};
// AJAX code to send data to php file.
$.ajax({
type: "POST",
// use same PHP script for each forms
url: "insert.php",
data: data,
dataType: "JSON",
success: function (data) {
// use kitchen's specific message tag
$("#message" + kitchen).html(data);
$("p").addClass("alert alert-success");
},
error: function (err) {
// alert(err);
console.log(err);
}
});
});
PHP file
Use one single PHP script for each form and generate table name in your SQL query from given kitchen value.
Working example based on your code:
$kitchen = $_POST['kitchen'];
// if your kitchens are all formatted like this : 1a, 2c, 14a, ...
preg_match('/(\d)+([a-z])/', $kitchen, $matches);
$stmt = $DBcon->prepare("INSERT INTO " . $matches[1] . '_' . $matches[2] . "(door,skilt,lys,b_t,b_s,dato)
VALUES(:door,:skilt,:lys,:b_t,:b_s,:dato)");
Generated query for your 1a form:
INSERT INTO 1_a(door,skilt,lys,b_t,b_s,dato) VALUES(:door,:skilt,:lys,:b_t,:b_s,:dato)
If I do understand well, you have multiple forms on one page and the second form posts the values of the first form.
I think the problem is that you're using tha same ids on the fields of the forms.
Take a look at:
var door = $("#door").val();
var skilt = $("#skilt").val();
var lys = $("#lys").val();
var b_t = $("#b_t").val();
var b_s = $("#b_s").val();
var dato = $("#dato").val();
These are the fields from insertData1a() function and it's the same in the other function:
var door = $("#door").val();
var skilt = $("#skilt").val();
var lys = $("#lys").val();
var b_t = $("#b_t").val();
var b_s = $("#b_s").val();
var dato = $("#dato").val();
So basically the problem is that you're referencing the same fields in the second function.
The id attribute must be a unique id for an HTML element, so you should use different ids in each form or if you're already using different ids (you didn't post the html of the second form) you just have to rewrite the elements in your second function.

re render click event for added element backbone

I'm currently new in backbone.js. I use CodeIgniter as my PHP Framework.
I'm developing an existing system which uses a backbone.js library. My problem is easy if i will do it in jquery but since this uses a backbone.js, I should do it the same way. This what happens.
Once the page is loaded, i will populate the users inside a select box. then with a button 'ADD'. I will populate also the uses already added inside the ul element to list all the users with an x anchor if you want to delete the user.
I append the user in the list after success ajax in create warehouse user. I use jquery to append. Now the click event to delete is not working because backbone already done rendering the views. How to re render backbone click event for newly added element?
Below is my sample code
HTML CODE
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-list"></i> User Access
</div>
<div class="panel-body">
<div class="row">
<div class="col-lg-12">
<form method="POST" action="<?php echo base_url();?>warehouse/user" id="add-warehouse-user-form">
<div class="col-lg-4">
<div class="form-group">
<label for="users">Available Users </label>
<input type="hidden" name="wh_id" id="wh_id" value="<?php echo $warehouse->wh_id; ?>" />
<select class="form-control" name="users" id="users">
<?php if(!empty($users)){
foreach($users as $row){
//if(in_array('Head',$row->user_access) AND $row->status == 'ACTIVE'){
echo '<option value="'.$row->user_id.'">'.$row->first_name.' '.$row->last_name.'</option>';
//}
}
}?>
</select>
</div>
</div>
<div class="col-lg-1">
<div class="form-group">
<label for="users"> </label>
<input type="submit" class="btn btn-success form-control" value="Add" />
</div>
</div>
</form>
</div>
</div><br />
<div class="row">
<div class="col-lg-12">
<div class="col-lg-5">
<ul class="list-group" id="list_user">
<?php if(!empty($userlist)){
foreach ($userlist as $ul) {
echo '<li class="list-group-item">'.$ul['name'].' <span class="badge badge-delete"><a class="deleteUser" href="#" data-id="'.$ul['module_id'].'" data-uid="'.$ul['id'].'" data-name="'.$ul['name'].'">x</a></span></li>';
}
} ?>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
Warehouse model
var WarehouseUserModel = Backbone.Model.extend({
urlRoot: Config.apiBaseUrl + "/warehouse/user",
defaults: {
wh_id: "",
users: ""
}
});
var WarehouseUserDelModel = Backbone.Model.extend({
urlRoot: Config.apiBaseUrl + "/warehouse/user"
});
Warehouse View
var WarehouseView = Backbone.View.extend();
//-------------- add user to warehouse --------------//
var WarehouseUserAddNewView = Backbone.View.extend({
el: "#add-warehouse-user-form",
loaderEl: "#form-loader",
events:{
"submit": "createWarehouseUser"
},
createWarehouseUser: function (e) {
var self = this;
e.preventDefault();
var formData = Util.getFormData($(self.el));
var warehouseUser = new WarehouseUserModel(formData);
//disable form
$(self.el).find(" :input").prop("disabled", true);
//show loader
$(self.loaderEl).removeClass("hidden");
warehouseUser.save({}, {
success: function (model, res, options) {
if (res.status == "error") {
Util.formError(res.data);
var errorTemplate = _.template($("#toast-error-template").html());
toastr.error(errorTemplate({errors: res.data}));
//re-enable form
$(self.el).find(" :input").prop("disabled", "");
//hide loader
$(self.loaderEl).addClass("hidden");
} else {
//location.href = res.data.redirectUrl;
/** append user to list and remove from select box **/
$('#list_user').append('<li class="list-group-item">'+$("#users option[value='"+$("#users").val()+"']").text()+' <span class="badge badge-delete"><a class="deleteUser" href="#" data-id="'+res.data.id+'" data-uid="'+$("#users").val()+'" data-name="'+$("#users option[value='"+$("#users").val()+"']").text()+'">x</a></span></li>');
$("#users option[value='"+$("#users").val()+"']").remove();
//re-enable form
$(self.el).find(" :input").prop("disabled", "");
//hide loader
$(self.loaderEl).addClass("hidden");
}
}
});
},
initialize: function () {},
});
//-------------- remove user from warehouse --------------//
var WarehouseUserDeleteView = Backbone.View.extend({
el: ".deleteUser",
events:{
"click": "deleteWarehouseUser"
},
deleteWarehouseUser: function (e) {
elem = $(e.currentTarget)[0];
var self = this;
e.preventDefault();
var warehouseUser = new WarehouseUserDelModel({'id':$(elem).data('id')});
warehouseUser.destroy({
success: function (model, res, options) {
console.log(model);
console.log(res);
console.log(options);
if (res.status == "error") {
Util.formError(res.data);
var errorTemplate = _.template($("#toast-error-template").html());
toastr.error(errorTemplate({errors: res.data}));
} else {
/** append user to select box and remove from lists **/
$("#users").append("<option value='"+$(elem).data('uid')+"'>"+$(elem).data('name')+" </option>");
$(elem).parents('li.list-group-item').remove();
}
}
});
},
initialize: function () {},
});
new WarehouseUserAddNewView();
new WarehouseUserDeleteView();
The actual code that renders your list of users will probably always be jquery - backbone does not come with default render functionality. However, it is common practice to put code that will render the entire contents of the el in a render method of the view. That way it can be called initially, and then called again whenever conditions have changed.
It looks like your general approach is to use each view a bit like an event handler. Each has a single event attached, with one sizeable method to do some work. That's fine as long as it's working for you, but you can also have a more complicated view than handles multiple functions. I might recommend you use your WarehouseView to keep a list of users, and handles both a reusable render, and the delete method you have already written:
var WarehouseView = Backbone.View.extend({
el: '#list_user',
initialize: function(options) {
this.users = (options && options.users) || [];
// render once on intialize
this.render();
},
events: {
// listen for delete clicks on contained elements
'click .deleteUser': 'deleteWarehouseUser',
},
deleteWarehouseUser: function(ev) {
// your same method code should work here
},
render: function() {
// render the list of users you have
this.$el.html('');
for (var i = 0; i < this.users.length; i++) {
// use jquery to add the user to your list as a <li>
}
}
});
var warehouseView = new WarehouseView();
If you use this approach, then inside your add new user method you can do things like:
// ... create your user variable
warehouseView.users.push(user);
warehouseView.render();
The delete (client-side) can also consist of removing a particular user from your view's list, and then rerendering.
You can arrange backbone objects pretty much any way you like, but I hope this recommendation helps. Also note that once you feel more comfortable, creating a Backbone Collection for your users is the more "backbone-y" way to do things rather than a plain array.

Passing HTML form values / loading .php file

I'm trying to pass the parameter of a form $_POST['txtBody'] into a div via jquery/javascript.
the PHP file to be loaded:
ajax-rewriter.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
print_r($_POST);
$articleBody = strtolower($_POST['txt']);
echo "<pre><b>Original:</b><br /><br /><p>" . $articleBody . "</p></pre>";
$word = "";
$length = strlen($articleBody);
$OutputBody = "";
for ($i = 0; $i < $length; $i++) {
$word = $word . $articleBody[$i];
if ($i == $length - 1)
$comeCha = " ";
else
$comeCha = $articleBody[$i + 1];
$retStr = getWordPattern($word, $comeCha, "syn/en.syn");
if ($retStr != "") {
$OutputBody .= $retStr;
$word = "";
}
}
echo "<br>";
echo "<pre><b>Spun:</b><br /><br /><p>" . $OutputBody . $word . "</p></pre>";
}
?>
The HTML form:
<div id="mainContent"></div>
<div class="panel panel-primary">
<div class="panel-heading">Your article rewriter API is: (<span class="results"><b>http://www.wraithseo.com/api.php?rewriter=1&key=<?php echo $user['api_key']; ?></b></span>)</div>
<div class="panel-body">
<form id="frmAjax" action="rewriter.php" method="post" class="form-horizontal container-fluid" role="form">
<div class="row form-group">
<div class="col-sm-4 text-right"><label for="txtBody" class="control-label">Article:</label></div>
<div class="col-sm-8"><textarea class="form-control" id="txtBody" name="txtBody" required="required"></textarea></div>
</div>
<div class="row form-group">
<div class="col-sm-12 text-right">
<button type="submit" name="spinText" class="btn btn-default">Spin!</button>
</div>
</div>
</form>
</div>
<div class="panel-footer">Paste in an article above and hit <b>Spin</b>!</div>
</div>
<script>
$(document).ready(function(){
$('#frmAjax').submit(function(e) {
e.preventDefault(); // important so the submit doesn't clear the data...
$.ajax({
type: "POST",
url: "ajax-rewriter.php",
data:{ txt: <?php echo $_POST['txtBody']; ?> }
})
$("#mainContent").load('ajax-rewriter.php')
});
});
</script>
I have tried but cannot remember the proper way to pass the $_POST['txtBody'] value to the loaded .php file and show it in the div
Any help would be appreciated.
So it looks like you want to send whatever is typed into the <textarea class="form-control" id="txtBody" name="txtBody" required="required"></textarea> element to be passed to the php file ajax-rewriter.php for processing via JQuery ajax, correct?
I don't think you should be trying to get from your $_POST variable inside your AJAX request. Rather, you're sending the value of the textarea through your AJAX request (which is utilizing the POST method to send the data).
Here is what I believe you are looking for:
$(document).ready(function(){
$('#frmAjax').submit(function(e) {
var text = $('#txtBody').val(); // ADDED THIS
e.preventDefault();
$.ajax({
type: "POST",
url: "ajax-rewriter.php",
data:{textData : text} // MODIFIED THIS
})
$("#mainContent").load('ajax-rewriter.php')
});
});
Then, in your php file, you can get the text variable through the $_POST variable:
$data = $_POST["textData"];
You can then choose what to do whatever you want with the data in your php file. If you are trying to send the data via ajax to php, modify it via php, then send it back as a response to the ajax request, look into JQuery's success and complete callback functions that are part of the JQuery ajax call.
Here is an example using the success callback:
$.ajax({
type: "POST",
url: "email.php",
data: {fullName, phoneNumber, email, comments, response},
success: function(dataRetrieved){
$("#response").html(dataRetrieved);
}
});
The php file email.php receives the data via $_POST through the ajax request, processes it, and then the email.php file will echo data as output from the server. The data that is echoed is sent back as a response to the ajax request, which can be retrieved as a parameter in the success callback.

Jquery pass value to radio button

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!

jQuery parent usage

First time using jQuery parent and got confused, here's my html:
<div id="friends_inveni" class="friends_rec" style="">
<br>
<div style="height: 280px; overflow-y: auto;">
<div style="width:150px;float:left;font-size:11px;color:White;">
<input type="checkbox" name="friends" value="3265" id="friend_3265">
<img style="width:24px;vertical-align:middle;" src="https://graph.facebook.com/661382259/picture">
Test1
</div>
<div style="width:150px;float:left;font-size:11px;color:White;">
<input type="checkbox" name="friends" value="3265" id="friend_3265">
<img style="width:24px;vertical-align:middle;" src="https://graph.facebook.com/599567764/picture">
Test2
</div>
</div>
<br clear="all">
<div class="action_new_comment">
<textarea class="action_comment_input" onkeyup="check_height(this);" style="height:36px;"></textarea>
<br clear="all">
<a class="action_btn" style="font-size:11px;" name="comment" id="A1">Send Recommendation</a>
</div>
</div>
Here's my jQuery code:
jQuery(document).ready(function() {
$(".action_btn").live('click', function() {
var friends = new Array();
$(this).parents('.recommend').find('input:checked').each(function(k) { friends[k] = $(this).val(); });
var comment = $(this).parents('.recommend').find('textarea').val();
if (friends.length == 0) {
alert('Please select at least one friend.');
} else {
$.post("update.php",
{ uid: <?php echo $_SESSION['uid']; ?>, mid: <?php echo $_GET['mid']; ?>, friends: friends, comment: comment },
function() {
var newComment = $('<div class="bubble_confirmation"><h1>Recommendation Sent!</h1><br /><br > Send more</div>');
$(this).parents('.recommend').append(newComment.fadeIn());
$(this).parents('.recommend').find("input:checkbox:checked").attr("checked", "");
$(this).parents('.recommend').find('.action_comment_input').val('');
});
}
});
});
Issue is that:
1. I can't get the content of the textbox
2. I can't get the array of userid
Why is this?
It looks as though your HTML class friends_rec should be recommend, judging from your jQuery code.
Also, since we don't know what $(el) is, that should probably be $(this), instead.
Addition to what Herman said you should do:
var $parent = $(this).parents('.recommend:first')
inside of your ajax callback. The :first prevents jQuery from going up the whole tree to look for more elements of that classname after you've already found the element you're looking for and keeping it as a variable reference allows you to not create a new jQuery object each time you need to use it.

Categories