I have multiple select box on my form.
<form id="form">
<?php
for($i = 1; $i<=9; $i++)
{
?>
<input type="hidden" name="modelID" value="1"/>
<div>
Process <?php echo $i; ?>
<select class="process" name="process[]" id="Process<?php echo $i; ?>">
<option value="">Choose One</option>
<option value="P1">Process 1</option>
<option value="P2">Process 2</option>
<option value="P3">Process 3</option>
</select>
</div>
<?php
}
</form>
And now I need to get the value of each value for select box that only filled to PHP.
Example I only choose Process 2, then store it to PHP to be Process 2: P2.
And on the PHP I need to save it to table.
//maybe using foreach?
$insert = oci_parse($c1, "INSERT INTO tbl_process(MODELID, PROCESS1, PROCESS2, PROCESS3) VALUES('1', '', '', '')");
//ONLY insert filled select box, on my example PROCESS2 will be filled P2 to table column.
And the JS
$('#btnSave').on('click', function()
{
var modelID = $("#modelID").val();
var form_data = $("#form").serialize();
alert(form_data);
$.ajax(
{
'type': 'post',
'url': 'saveProcess',
'data': {
'form_data': form_data
},
'success': function(response)
{
}
});
});
My question, how to ONLY insert filled select box, on my example PROCESS2 will be filled P2 to table column?
What you can do is only pass the modelID and processID using the ajax call.
Whenever the user changes the process you save the data through the ajax call.
<form id="form">
<?php for($i = 1; $i<=9; $i++) { ?>
Process <?php echo $i; ?>
<select class="process" modelID="<?php echo $i; ?>">
<option value="P1">Process 1</option>
<option value="P2">Process 2</option>
<option value="P3">Process 3</option>
</select>
<br>
<?php } ?>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('.process').change(function(){
var modelID = $(this).attr('modelID');
var processID = $(this).val();
$.ajax({
url: 'saveProcess.php',
dataType: 'json',
type: 'post',
data: {'modelID':modelID, 'processID':processID},
success: function( data, textStatus, jQxhr ){
console.log(data);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
});
});
</script>
Related
I have two separate files, bargraph.html and data.php.
Part of bargraph:
<form method="POST" name="dataform" action="" id='dataForm'>
<select id="data1" name="data1">
<option value=""></option>
<option value="DateRecorded">DateRecorded</option>
<option value="InletVoltage">InletVoltage</option>
<option value="InletCurrent">InletCurrent</option>
<option value="ActivePower">ActivePower</option>
<option value="ApparentPower">ApparentPower</option>
<option value="PowerFactor">PowerFactor</option>
<option value="SystemID">SystemID</option>
</select>
<select id ="data2" name="data2">
<option value=""></option>
<option value="DateRecorded">DateRecorded</option>
<option value="InletVoltage">InletVoltage</option>
<option value="InletCurrent">InletCurrent</option>
<option value="ActivePower">ActivePower</option>
<option value="ApparentPower">ApparentPower</option>
<option value="PowerFactor">PowerFactor</option>
<option value="SystemID">SystemID</option>
</select>
<button type="button" id="submitButton" name="submitButton">Submit</button>
</form>
<script type="text/javascript">
$('#submitButton').click(function(e) {
var data1 = $("#data1").val();
var data2 = $("#data2").val();
$.ajax({
type: 'post',
url: 'data.php',
dataType: 'html',
data: {data1:data1,data2:data2},
success: function(data){
console.log(data);
console.log('#dataForm');
},
error: function (xhr, ajaxOptions, thrownError){
console.log(thrownError);
},
complete: function(){
}
});
e.preventDefault();
});
</script>
Part of data.php:
if (isset($_POST['data1'])) {
$opp1 = $_POST['data1'];
} else {
$opp1 = 'SystemID';
}
if (isset($_POST['data2'])) {
$opp2 = $_POST['data2'];
} else {
$opp2 = 'ApparentPower';
}
$sql = "SELECT $opp1, $opp2 FROM RaritanMachineDataa";
$result = sqlsrv_query($conn, $sql);
$data = array();
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
$row = preg_replace("/[^0-9]/", "", $row);
$data[] = $row;
}
sqlsrv_free_stmt($result);
sqlsrv_close($conn);
echo json_encode($data);
?>
When I select from the two drop down menus, in my browser console, it prints that chosen data in JSON format and the values from my database, however when I load the data.php file via browser URL, it is printing SystemID and ApparentPower and not the chosen data. Why is this? Can someone help me please?
See below screenshot of browser console printing the chosen data from drop downs.
https://imgur.com/rdxgWaB
and screenshot of data.php loaded via browser after choosing from drop down InletCurrent and ActivePower.
https://imgur.com/a/eiDeTLs
The problem is dataType: 'html'
You post the json data but define the html
Try to change to json :
$.ajax({
type: 'post',
url: 'data.php',
dataType: 'json',
data: {data1:data1,data2:data2},
success: function(data){
console.log(data);
console.log('#dataForm');
},
error: function (xhr, ajaxOptions, thrownError){
console.log(thrownError);
},
complete: function(){
}
});
My page keeps refreshing when I select an item from a listbox. I'm new to Ajax and still learning from it. Here's my code I want to make Ajax code for this one.
<form id="myform" action="home_log.php" method="post">
<label1>Room Type:*</label1>
<select name="roomtype" onchange="this.form.submit();">
<option value="Standard Room A">Standard Room A</option>
<option value="Standard Room B">Standard Room B</option>
<option value="Deluxe Room">Deluxe Room</option>
</select>
</form><br>
<label1>Room Number:*</label1>
<div id="form_output">
<?php
$roomtype = isset($_POST['roomtype']) ? $_POST['roomtype'] : '';
echo "<select>";
include_once 'includes/dbh-inc.php';
$result = $conn->query("select RoomName from tblroom_sample where RoomType='".$roomtype."'");
while ($row = $result->fetch_assoc()) {
unset($roomtype);
$RoomName = $row['RoomName'];
echo '<option value="'.$RoomName.'">'.$RoomName.'</option>';
}
echo "</select>";
?>
</div>
Ajax:
$(document).ready(function () {
$('#myform').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "GET",
data: $(this).serialize(),
success: function (data) {
$("#form_output").html(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
I have a form, having two list boxes and based on the selected field from the first list, I have to fetch data from the database to create second list box.
I am trying to acheive this with post method, but unable to understand why mey second list is not populating with data...
PHP to fetch data for second list box
if (isset($_POST['val']))
{
$value = $_POST['val'];
$smt3 = $db->prepare('select floor from test where name_id =?');
$smt3->execute(array($value));
$HF_id = $smt3->fetchAll();
}
HTML to for the list boxes
<select class="Name" name="Profile_Name1" id="PC1">
<option value="A">AA</option>
<option value="B">BB</option>
<option value="c">CC</option>
<option value="d">DD</option>
</select>
<label>Home Floor </label>
<select name="Home_Floor" id="hfid"> <br />
<option value="">Home_Floor</option>
<?php foreach ($HF_id as $row){echo '<option value="' . $row['floor'] . '">' . $row ['floor'] . '</option>';}?>
</select>
Jquery
$('#PC1').on('click', function() {
$.post('user_info1.php', 'val=' + $(this).val(), function (response) {
$.ajax({
url: 'user_info1.php', //This is the current doc
type: "POST",
data: ({val: + $(this).val()}),
success: function(data){
}
});
You seem to expect the post function to trigger a loading of the page specified by the URL parameter.
Try something along the lines of this:
HTML
<select class="Name" name="Profile_Name1" id="PC1">
<option value="A">AA</option>
<option value="B">BB</option>
<option value="C">CC</option>
<option value="D">DD</option>
</select>
<label>Home Floor </label>
<select name="Home_Floor" id="hfid">
</select>
loaddata.php
if (isset($_POST['val']))
{
$value = $_POST['val'];
$smt3 = $db->prepare('select floor from test where name_id =?');
$smt3->execute(array($value));
$HF_id = $smt3->fetchAll();
$HF_array=array();
foreach ($HF_id as $row)
{
$HF_array[]=$row['floor'];
}
}
echo json_encode($HF_array);
javascript/jquery
jQuery('#PC1').on('click', function() {
jQuery.ajax({
url: 'loaddata.php',
type: "POST",
data: ({val: + $(this).val()}),
success: function(data){
//data should come as JSON string in the form of ['item1','item2','item3'] use JSON.parse to convert to object:
jQuery.each(JSON.parse(data), function(key, datavalue) {
jQuery('#hfid').append(
jQuery('<option>', { value : datavalue })
.text(datavalue)
);//end of append
});//end of each
}//end of success function
});//end of ajax datastruct and ajax call
});//end of on-click-function
How do I want to post a form using jquery serialize function? I tried to post the form value but on the php part, the value is not shown. Below are my codes:
html
<form name="myform">
ID : <input type="text" name="id_staff" id="id_staff">
<select name="sort" id="sort">
<option value="0">Choose Status</option>
<option value="1">All</option>
<option value="2">Pending</option>
<option value="3">Approve</option>
<option value="4">Not Approve</option>
</select> <input type="button" id="submit" value="Papar" />
<div id="loader"></div>
</form>
jQuery
$(document).on("click", "#submit", function(e){
e.preventDefault();
var sort = $("#sort").val(),
id_staff = $("#id_staff").val(),
data = $('form').serialize();
$.post('result.php',
{
data : data
}, function(data){
$("#loader").fadeOut(400);
$("#result").html(data);
});
});
PHP
if(isset($_REQUEST["sort"])){
$sort = $_REQUEST['sort'];
$id_staff = $_REQUEST['id_staff'];
echo "Your Id : $id_staff <p/>";
echo "You choose : $sort";
}
If I console.log(data), I get: id_staff=12345&sort=1
Your server is receiving a string that looks something like this (which it should if you're using jQuery serialize()):
"param1=someVal¶m2=someOtherVal"
...something like this is probably all you need:
$params = array();
parse_str($_GET, $params);
$params should then be an array that contains all the form element as indexes
If you are using .serialize, you can get rid of this:
var sort = $("#sort").val(),
id_staff = $("#id_staff").val(),
You data will be available as follows with .serialize:
your-url.com/sort=yoursortvalue&id_staff=youridstaff
It should be:
$(document).ready(function(e) {
$("#myform").submit(function() {
var datastring = $( this ).serialize();
$.post('result.php',
{
data : datastring
}, function(data){
$("#loader").fadeOut(400);
$("#result").html(data);
});
})
})
On PHP side you simple need to access it using the $_GET['sort'].
Edit:
To view the data, you should define a div with id result so that the result returned is displayed within this div.
Example:
<div id="result"></div>
<form name="myform">
ID : <input type="text" name="id_staff" id="id_staff">
<select name="sort" id="sort">
<option value="0">Choose Status</option>
<option value="1">All</option>
<option value="2">Pending</option>
<option value="3">Approve</option>
<option value="4">Not Approve</option>
</select> <input type="button" id="submit" value="Papar" />
<div id="loader"></div>
</form>
I am able to do it this way:
jQuery
<script type="text/javascript">
$(document).ready(function() {
var form = $("#myform");
$("#myform").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'result.php',
data: form.serialize(),
success: function(response) {
console.log(response);
$("#result").html(response);
},
error: function() {
alert('Error Submitting');
}
})
})
})
</script>
PHP
if(isset($_POST["id_staff"])){
$sort = $_POST['sort'];
$id_staff = $_POST['id_staff'];
echo "<p>Your Id : $id_staff</p>";
echo "You choose : $sort";
}
Do give a comment if it need improvement or better solution.
This question is SOLVED - solution is on the bottom of the question.
Let's say I have this form:
<form id="form1" action="" method="POST">
<select name="cars">
<option value="">Choose a car</option>
<option value="Ferrari">Ferrari</option>
<option value="Lamborghini">Lamborghini</option>
</select>
<select name="colors">
<option value="">Choose a color</option>
<option value="Green">Green</option>
<option value="Red">Red</option>
</select>
Php:
$cars = $_POST['cars'];
$colors = $_POST['colors'];
echo "Car: ".$cars." - Color: ".$colors."";
Ajax:
<script type='text/javascript'>
$('select[name="colors"]').on('change', function(){
$.ajax({
type: "POST",
url: "phpfile.php",
data: $("#form1").serialize(),
success: function(data){
$('#target1').html(data);
}
});
return false;
})
</script>
I want to show on html the results:
<div id="target1"></div>
I want to show the results when I choose the color (The 2nd dropdown):
onchange="this.form.submit()"
IT IS DONE:)
I used this code and it I am getting what I want:
<script type='text/javascript'>
$("#colorID").on("change", function() {
var $form = $("#form1");
var method = $form.attr("method") ? $form.attr("method").toUpperCase() : "GET";
$.ajax({
url: 'phpfile.php',
data: $form.serialize(),
type: method,
success: function(data){
$('#target1').html(data);
}
});
});
</script>
Technically you dont need ajax to get what your asking for but heres jQuery ajax example:
Change your HTML to:
<select name="colors" onchange="this.form.submit()">
<option value="">Choose a color</option>
<option value="Green">Green</option>
<option value="Red">Red</option>
</select>
$( "#form1" ).submit(function( event ) {
event.preventDeafault();
alert('form submitted');
$.ajax({
type: "POST",
url: "<YOUR PHP FILE PATH>",
data: $("#form1").serialize(),
success: function(data){
alert('ajax success');
$('#target1').html(data);
}else{
alert('ajax error');
}
});
return false;
})
In your PHP:
print_r($_POST);
$car = $_POST['car'];
$color = $_POST['color'];
echo "<p>Car: ".$car." - Color: ".$color."</p>";
This is untested - I've just typed it out on my phone during my lunch break!
To debug the php add this line ( to unsure the post worked):
print_r($_POST);
Use your browser developer tools to debug your AJAX and JS
I've add alerts to help you debug - you can remove these when its working