I am trying to fetch a row on a selection of a particular ID, now when the user selects any value of a drop-down the respective values have to come into text boxes, I am using ajax for the same,I am getting output from my PHP file But they are in array form like ("rahul", "9594233709"). When I am trying to put them in there respective fields I am not able to do it.
Here is my complete code. I am trying to fetch a row on a selection of a particular ID, now when the user selects any value of a drop-down the respective values have to come into text boxes, I am using ajax for the same,I am getting output from my PHP file But they are in array form like ("rahul", "9594233709").
When I am trying to put them in their respective fields I am not able to do it.here is my complete code. I am expecting That location has to move in the location column and mobile has to be in Mobile column, Array is coming perfectly in the front end. For example: ["9594233705", "Gorakhpur"]
<script >
$(document).ready(function(){
$('#reg_number').change(function(){
var reg_number = $(this).val();
$.ajax
({
type: "POST",
url: "details.php",
data: {post_id:reg_number},
dataType: "text",
cache: false,
success:function(data)
{
$('#u_mobile1').val(data);
$('#u_location1').val(data);
}
});
});
});
</script>
if($_POST['post_id'])
{
$id=$_POST['post_id'];
$sql="SELECT u_mobile,u_location FROM system_users WHERE u_userid=".$id;
$result = mysqli_query($con,$sql);
$data = array();
while($row = mysqli_fetch_array($result))
{
$u_mobile = $row['u_mobile'];
$u_location = $row['u_location'];
$data[0]=$u_mobile ;
$data[1]= $u_location ;
// $data[] = array('u_mobile' => $u_mobile, 'u_location' => $u_location);
} echo json_encode($data);
}
<div class="col-md-6">
<div class="form-group form-group-default required">
<label>Company Mobile Number:</label>
<input type="number" class="form-control" required="" id="u_mobile1" name="u_mobile1" value="" >
</div>
</div>
<div class="col-md-6">
<div class="form-group form-group-default required">
<label class="">Location</label>
<input type="number" class="form-control" required="" id="u_location1" name="u_location1" value="">
</select>
</div>
</div>
if i didn't get it wrong, you want to parse response Json data and add to inputs.
If this is the case you can use javascript JSON.parse(); function. Because you getting data as a json list.
$.ajax
({
type: "POST",
url: "details.php",
data: {post_id:reg_number},
dataType: "text",
cache: false,
success:function(data)
{
var resp = JSON.parse(data);
document.getElementById("u_mobile").value=resp.u_mobile;
document.getElementById("u_location").value=resp.u_location;
}
});
Related
I am working with two forms where if user submitted first form the data is inserted using ajax to database and user is redirected to second form(Both Forms are in same file).
When user which is present on second form presses back button the value on the input type text for form1 one to be fetched from db which is stored when user submitted the first form.
My doubt is how can we pass value from ajax call to input type text
Here is my code which i have done uptill now
//Form 1
<form id="titlechange">
<div id="step1">
<input type="text" name="tbl_title" id="title" value="" class="form-control">
<input type="text" name="tbl_description" id="description" value="" class="form-control">
<button type="button" onclick="addTitle()" name="firstsubmit" class="update-btn" >Next</button>
</div>
</form>
//Form 2
<form id="detailsubmit">
<div id="step2">
<div class = "data"> //input type hidden retreived after submitting from 1 inside class data
<input type="hidden" value="<?php echo $insertData ?>" class="form-control">
</div>
<input type="text" name="city" id="city" value="" class="form-control">
<input type="text" name="state" id="state" value="" class="form-control">
<button type="button" onclick="addTitle()" name="firstsubmit" class="update-btn" >Next</button>
<button type="button" onclick="editModeForStep1()" name="firstsubmit" class="update-btn" >Back</button>
</div>
</form>
Ajax Call for back button
function editModeForStep1()
{
var formData = new FormData($('#detailsubmit')[0]);
formData.append('action', 'retreive');
$.ajax({
method: 'post',
processData: false,
contentType: false,
cache: false,
enctype: 'multipart/form-data',
url: 'ClientData.php',
data: formData,
success:function(msg){
//what should be written here for displaying value received from `ClientData.php` to value attribute of input type text in form 1
$('#step1').addClass('in active');
alert('success');
}
});
}
ClientData.php
if(isset($_POST["action"]) && $_POST["action"]=="retreive"){
$insertData = $_POST['insertdata'];
$slideOne = $objMaster->getSlideForEdit($insertData);
foreach($slideOne as $key=>$value)
{
echo $title = $value['title'];
echo $description = $value['description'];
}
}
First, let's change ClientData.php to return data in a more usable form.
if(isset($_POST["action"]) && $_POST["action"]=="retreive"){
$insertData = $_POST['insertdata'];
//select first row of results for getSlideForEdit by adding `[0]`
$slideOne = $objMaster->getSlideForEdit($insertData)[0];
//notice array keys match form1 form elements ID
//notice there is no need for a loop here
echo json_encode(
array(
'title' => $slideOne['title'],
'description' => $slideOne['description']
)
);
//if you want to update EVERYTHING from $slideOne, you can just do
//echo json_encode($slideOne);
//instead of the above json_encode()
}
Now our return will contain JSON data instead of plain strings. We can update your success method to update those input boxes.
...
data: formData,
//set dataType to json because we are receiving json from the server
dataType: 'json',
success:function(msg){
$('#step1').addClass('in active');
//if you don't set dataType to json you can also do
//msg = JSON.parse(msg);
//loop through returned array.
$.each(msg, function(index, value) {
//select element by index e.g `#title`, set value
$('#' + index).val(value);
});
alert('success');
}
This solution will dynamically update any input on your page as long as you return a key=>value pair for it from your server.
What I need
I need when someone change my calendar, a php script should run in background and fetch some data and show it in the form fields accordingly. To do that, I have the following HTML code and Ajax script
$("#normalShiftDate").change(function() {
var FD = new FormData($('#dailyEditor')[0]);
$.ajax({
type: "POST",
url: "supervisorEditAjax.php",
processData: false,
contentType: false,
data: FD,
success: function(result) {
$('#normalShiftOperator').val(result["normalShiftOa"]);
$("#normalShiftOperatorDuration").val(result["normalShiftOperatorDuration"]);
$("#normalShiftPinCount").val(result["normalShiftPinCount"]);
},
error: function() {
alert('Some error occurred!');
}
});
});
<div class="form-group">
<div class="row">
<div class="col-sm text-center" id="normalShiftOaDiv" class="">
<label for="currentOa">Current OA?</label><br>
<input type="radio" name="currentOa" id="normalShiftOa" value="normalShiftOa">
</div>
<div class="col-sm" id="normalShiftOperatorNameDiv">
<label for="normalShiftOperator">Normal Shift</label>
<select class="form-control" id="normalShiftOperator" name="normalShiftOperator">
<option></option>
<option>A</option>
<option>B</option>
</select>
</div>
<div class="col-sm" id="normalShiftOperatorDurationDiv">
<label for="normalShiftOperatorDuration">Duration</label>
<select class="form-control" id="normalShiftOperatorDuration" name="normalShiftOperatorDuration">
<option></option>
<option>1</option>
<option>2</option>
</select>
</div>
<div class="col-sm">
<label for="normalShiftPinCount">Pin Count</label>
<input type="number" class="form-control" id="normalShiftPinCount" name="normalShiftPinCount" value="23">
</div>
<div class="col-sm">
<label for="normalShiftDate">Date</label>
<input type="date" class="form-control" id="normalShiftDate" name="normalShiftDate">
</div>
<div class="col-sm">
<button type="submit" class="btn btn-primary" style="margin-top: 30px;" id="normalShiftUpdate" name="normalShiftUpdate">Update</button>
</div>
</div>
</div>
I want to show the php variables $normalShiftOa, $normalShiftOperatorDuration and $normalShiftPinCount in the form fields with id normalShiftOperator, normalShiftOperatorDuration, normalShiftPinCount respectively when someone change calendar. Please see the contents of supervisorEditAjax.php. How can I show these three variables into the three id fields?
I only know how to show to one single field. But if there are multiple values to be shown in multiple fields, how can we do that?
Can someone please help?
Edit 1
Contents of supervisorEditAjax.php
<?php
$normalShiftOa = "A";
$normalShiftOperatorDuration = "2";
$normalShiftPinCount = "100";
$arr = array('normalShiftOa' => $normalShiftOa, 'normalShiftOperatorDuration' => $normalShiftOperatorDuration, 'normalShiftPinCount' => $normalShiftPinCount);
echo json_encode($arr);?>
I tried to use some Json method. But it is not working
After many trial and error, I am able to show it in the respective form fields. The issue was at the Ajax part. Basically I need to parse the Json object in order to get the specific values. Replace the AJAX code as below and it works fine
< script >
$("#normalShiftDate").change(function() {
var FD = new FormData($('#dailyEditor')[0]);
$.ajax({
type: "POST",
url: "supervisorEditAjax.php",
processData: false,
contentType: false,
data: FD,
success: function(result) {
var returnedData = JSON.parse(result); //This is the change done to the code
$('#normalShiftOperator').val(returnedData["normalShiftOa"]);
$("#normalShiftOperatorDuration").val(returnedData["normalShiftOperatorDuration"]);
$("#normalShiftPinCount").val(returnedData["normalShiftPinCount"]);
},
error: function() {
alert('Some error occurred!');
}
});
});
</script>
Please read more about JSON.parse here
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 a form that posts data to a server side page where the data is inserted into a mysql database and then a row count of the database is performed and the result returned to the form page where it is then displayed.
I am using an ajax to fetch the row count data and I'm wondering if it is possible to delay the Ajax call until the data has been inserted into the database so I can get an accurate row count that would include the data just submitted? The current code works but only shows a row count before the form has been submitted. I have to reload the page to get a true result.
Form.php
<form class="form-inline" action="" id="myform" form="" method="post">
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="name"></label>
<div class="col-md-8">
<input id="name" name="name" type="text" placeholder="name" class="form-control input-lg" required>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="submit1"></label>
<div class="col-md-4">
<button id="submitButtonId" name="submit1" class="btn btn-primary btn-xl">Submit</button>
</div>
</div>
</form>
<div id="count"></div>
</div>
The jquery
<script>
//Post data from form
$(document).ready(function(){
$("#submitButtonId").on("click",function(e){
e.preventDefault();
var formdata = $(this.form).serialize();
$.post('server.php', formdata,
function(data){
//Reset Form
$('#myform')[0].reset();
});
return false;
});
});
</script>
<script>
//Fetch Rowcount from server.php
$(document).ready(function(){
$.ajax({
url: 'data.php',
dataType: "json",
success: function (data) {
$("#count").html(data.count);
}
});
});
</script>
Server.php
<?php
//Connect to db
include_once("db_conx.php");
if( isset($_POST['name']) ){
$name= mysqli_real_escape_string($db_conx,$_POST['name']);
//Update Database
$stmt = $db_conx->prepare('INSERT INTO myTable set name=?');
$stmt->bind_param('s',$name);
$stmt->execute();
}
//Count Rows
$sql="SELECT name FROM myTable";
$query = mysqli_query($db_conx, $sql);
// Return the number of rows in result set
$rowcount=mysqli_num_rows($query);
// send output
$my_data=array(count=>"$rowcount");
echo json_encode($my_data,true);
?>
Call the ajax that fetches the row count inside the response of the first ajax post.
<script>
//Post data from form
$(document).ready(function(){
$("#submitButtonId").on("click",function(e){
e.preventDefault();
var formdata = $(this.form).serialize();
$.post('server.php', formdata,
function(data){
//Reset Form
$('#myform')[0].reset();
fetchRowCount();
});
return false;
});
});
function fetchRowCount() {
$.ajax({
url: 'data.php',
dataType: "json",
success: function (data) {
$("#count").html(data.count);
}
});
}
</script>
you can call the count row function after the post like this:
$.post('server.php', formdata,
function(data) {
//Reset Form
$('#myform')[0].reset();
$.ajax({
url: 'data.php',
dataType: "json",
success: function(data) {
$("#count").html(data.count);
});)
});
If I've understand correctly from the code, I see that the Fetch Rowcount is executed on $(document).ready.
It means that once (and everytime) the page is loaded, it is executed.
So it happens this:
1) the page is loaded
2) the Fetch rowcount is executed
3) You submit
4) you have to reload the page to go to point 2.
So the solution is to execute the row fetch as a callback function after the submit is executed, not on document ready.
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.