I want to get some data via Ajax, but there must be some mistake because the result is empty
script:
<script>
function showUser(value) {
var values = $(this).serialize();
$.ajax({
url: "test.php",
data: {
id: value
},
type: "POST",
success: function(data){
$("#result").html(data);
}
})
}
</script>
html:
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
</form>
<br>
<div id="result"></div>
test.php:
<?php
$id = #$_POST['id'];
$pdo = $db->query('SELECT * FROM people WHERE id = "' . $id . '"');
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
echo $row['id'];
}
?>
HTML:-
<select id ="myselect" name="users" onchange="showUser()">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Joseph Swanson</option>
<option value="4">Glenn Quagmire</option>
</select>
<br>
<div id="result"></div>
Javascript:-
<script>
function showUser() {
$.ajax({
url: "test.php",
data: {
id: $( "#myselect option:selected" ).val();
},
type: "POST",
success: function(data){
$("#result").html(data);
}
});
}
</script>
PHP:-
<?php
if(isset($_POST['id'])){
$id = $_POST['id'];
// i don't know from where $db is coming so check yourself
$pdo = $db->query('SELECT * FROM people WHERE id = "'.$id.'" LIMIT 1');
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
echo $row['id'];
}
}else{
echo "Please select value from select box";
}
?>
Note:-
Meanwhile read about prepared statements and use them to prevent from SQL Injection. Thanks
If you dont want to use jquery, you can do something like this:-
var http = new XMLHttpRequest();
var url = "****Some URL (php etc to process the sql data)******";
var p = hex_sha512(userPass.value);
var params = "email="+userEmail.value+"&p="+p+"&adminStat=true";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
http.onreadystatechange = function() {
if (http.readyState == 4) {
//Todo
// check addition stat and go to the destination page
if (http.responseText == "success") {
window.location = "*****Destination URL********";
} else {
alert("error");
}
}
};
Related
This code comes from a guide I've seen in YouTube.
I'm trying to populate the second dropdown based on the choices on the first dropdown, in my test page its working, however when I tried to attach it to my main page, the second dropdown is not turning into a dropdown.
I've tried to re-code it, but still the problem persist.
This is for the AJAX
<?php
include('db.php');
if($_POST['id']){
$id=$_POST['id'];
if($id==0){
echo "<option value='0'>Select Type</option>";
}else{
$sql = mysqli_query($con,"SELECT * FROM `ConcernType` WHERE Concern_Id='$id'");
while($row = mysqli_fetch_array($sql)){
echo '<option value="'.$row['ConcernType_id'].'">'.$row['ConcernType_name'].'</option>';
}
}
}
?>
This is for the index.php
<label>Concern Category :</label><select name="concerncategory" class="concerncategory">
<option value="0">Select Category</option>
<?php
include('db.php');
$sql = mysqli_query($con,"select * from ConcernCategory");
while($row=mysqli_fetch_array($sql))
{
echo '<option value="'.$row['Concern_Id'].'">'.$row['ConcernCategory_name'].'</option>';
} ?>
</select><br/><br/>
<label>Concern Type :</label><select name="concerntype" class="concerntype">
<option value="0">Select Type</option>
</select>
<br /><br />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".concerncategory").change(function()
{
var Concern_Id=$(this).val();
var post_id = 'id='+ Concern_Id;
$.ajax ({
type: "POST", url: "ajax.php", data: post_id, cache: false,
success: function(Type) {
$(".concerntype").html(Type);
} }); }); });
</script>
Here are some screenshots.
https://ibb.co/2NTTdG8
https://ibb.co/fFXBzFS
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);
}
});
});
});
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
I am using a JS/Ajax function to echo Selected values from select boxes. I am populating these select boxes with values from MySQL DB. The function works with text input fields but now that I am using it with these select boxes I am getting no response.
Can I echo the selected value from a select box with the JS? or Is there a better way? EXAMPLE
JS
<script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "index.php",
dataType: 'json',
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');}
});
return false;
}
$('#category_form').on('change', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
});
});
</script>
PHP/HTML
try {
$pdo = get_database_connection();
$sql = "SELECT *
FROM `categories`
WHERE `master_id` = 0";
$statement = $pdo->query($sql);
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo 'There was a problem';
}
<form action="" method="post" id="category_form'" name="category_form'">
<select name="main" id="main" size="7" class="update">
<option value="">Select one</option>
<?php if (!empty($list)) { ?>
<?php foreach($list as $row) { ?>
<option value="<?php echo $row['id']; ?>">
<?php echo $row['name']; ?>
</option>
<?php } ?>
<?php } ?>
</select>
<select name="subc1" id="subc1" size="7" class="update"
disabled="disabled" hidden="hidden">
<option value="">----</option>
</select>
<select name="subc2" id="subc2" size="7" class="update"
disabled="disabled" hidden="hidden">
<option value="">----</option>
</select>
<select name="subc3" id="subc3" size="7" class="update"
disabled="disabled" hidden="hidden">
<option value="">----</option>
</select>
</form>
<div id="special"></div>
It looks like you're selecting the wrong element with jQuery.
Change:
$('#category_form').on('change', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
});
To:
$('#main').on('change', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
});