I am attempting to code the following script using jquery / ajax / php.
What happens is the php pulls all the records from the database and puts them into a select dropdown. When I select an item from the dropdown ajax pulls the price from the database and adds it into the span called priceeach1 . Well thats what its supposed to do, but my jquery is useless :-S .
The stockID comes from the select box value.
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#stock1').on('change', function (){
var newValue1 = $.getJSON('select2.php', {stockID: $(this).val()}, function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options += data[x]['priceeach'];
}
$('#priceeach1').text( options);
});
});
});
</script>
The HTML :
Price Each : £<span id="priceeach1"></span>
The select2.php :
<?php include 'connectmysqli.php'; ?>
<?php
$id = $_GET['stockID'];
$sql = 'SELECT * FROM stock WHERE stockID = ' . (int)$id;
$result = $db->query($sql);
$json = array();
while ($row = $result->fetch_assoc()) {
$json[] = array(
'priceeach' => $row['priceeach'],
);
}
echo json_encode($json);
?>
EDIT >> Ok I have now updated the code with the latest edits, this now WORKS.....apart from an odd problem......If I select the first or last item in the list no price is displayed, anything in between appears just fine..........
Try this,
var options = [];
for (var x = 0; x < data.length; x++) {
options = data[x]['priceeach'];
}
$('#priceeach1').text(options.join(','));
It should be like this you have to store price in the array options[] instead of option and then join them by any separator
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#stock').on('change', function (){
var newValue1 = $.getJSON('select2.php', {stockID: $(this).val()}, function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options[x] = data[x]['priceeach'];
}
$('#priceeach1').text(options.join(','));
});
});
});
</script>
You have to parse your JSON data to actual JSON Object before iterating it.
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#stock').on('change', function (){
var newValue1 = $.getJSON('select2.php', {stockID: $(this).val()}, function(data){
var jsonParsed = JSON.parse(data);
var options = '';
for (var x = 0; x < jsonParsed.length; x++) {
options[] = jsonParsed[x]['priceeach'];
}
$('#priceeach1').text(options.join(','));
});
});
});
</script>
Try to use this snipt:
for (var x = 0; x < data.length; x++) {
options += data[x]['priceeach'];
}
$('#priceeach1').text( options);
Related
I'm trying to dynamically update text on a PHP page via AJAX. But, instead of the text coming through at different intervals, it all comes at once. Maybe this is the wrong approach.
index.html
<html>
<head>
<title>Please Update!</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$.post("hello.php", function(data){
var success = $("#update");
success.css("color", "green");
success.html("> \r " + data + ".");
});
});
</script>
</head>
<body>
<div id="update"></div>
</body>
</html>
hello.php
<?php
echo "Hello World\n";
sleep(1);
echo "\rFoobar\n";
sleep(1);
echo "\rBazboo\n";
?>
I'd like the text to overwrite itself after one second but it comes barreling down the pipe all at once. ;_;
Not sure about this, but it might help you to do...
in PHP
<?php
$result[] = "Hello World\n";
$result[] = "\rFoobar\n";
$result[] = "\rBazboo\n";
print_r($result);
?>
in Ajax result
$.post("hello.php", function(data){
for(let i = 0; i < data.length; i++) {
setTimeout(() => {
// your stuff to do is here by 1 second interval...
var success = $("#update");
success.css("color", "green");
success.html("> \r " + data[i] + ".");
}, 1000*i);
}
});
Simple Representation
var data = ["Hello World\n","\rFoobar\n","\rBazboo\n"];
for(let i = 0; i < data.length; i++) {
setTimeout(() => {
console.log(data[i]);
}, 1000*i);
}
Like Antony suggested. You could create an array in php and encode it as Json
and then create a settimeout().
php
$data = array("Hello World","Foobar","BazBoo");
echo json_encode($data);
jQuery ~ JavaScript
$.ajax({
method: "GET",
url: "hello.php",
success: (res) => {
for (let i = 0; i < res.length; i++) {
setTimeout(() => {
// or use .html(res[i])
$("#update").text(res[i] + "<br>");
}, 1000 * i);
}
}
})
M using ajax to populate select tag drop down menu. Selecting an option from one select tag will fetch data to the next select tag from database through ajax.. M able to get the result but when an option is selected for which no data is available in database i want to show some message in the select tag as " No data found for this selection"
` $(document).ready(function(){
$("#sel_block").change(function(){
var blockid = $(this).val();
$.ajax({
url: 'getZone.php',
type: 'post',
data: {block:blockid},
dataType: 'json',
success:function(response){
var len = response.length;
$("#sel_zone").empty();
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['name'];
var temp="No Data Found";
if(response.length)
{
$("#sel_zone").append("<option value='"+id+"'>"+name+"</option>");
}
else
{
$("#sel_zone").append('<option value="">' + emptyMessage + '</option>');
}
}
}
});
});
});
`enter image description here
Write Now its showing blank when there is no data
Before looping through response you have to check its length. Didn't check this code, but it should work
var len = response.length;
$("#sel_zone").empty();
if(len == 0){
$("#sel_zone").append('<option value="">No Data Found</option>');
} else{
for( var i = 0; i<len; i++){
var id = response[i]['id'];
var name = response[i]['name'];
$("#sel_zone").append("<option value='"+id+"'>"+name+"</option>");
}
}
I created a form with a text field that has Spry Validation (ie javascript). The user can select the number of rows in the form from 1 to 10. I need the code below to also expand but I'm not familiar enough with javascript to make it work.
$divkey is the variable that controls how many rows are in the form.
Original
<script type="text/javascript">
var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1", "none", {validateOn:["change"], maxChars:20});
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
so I need the line 'var sprytextfield1...' to repeat based on $divkey with the next line being 'var sprytextfield2...' and so on. Can someone please rewrite this so it will work?
Trying to use php
<script type="text/javascript">
<?php for ($i = 0; $i < $divkey; $i++) { $num=$i+1; ?>
var sprytextfield<?php echo $num;?> = new Spry.Widget.ValidationTextField("sprytextfield<?php echo $num;?>", "none", {validateOn:["change"], maxChars:20});
<?php }?>
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
Trying to use javascript
<script type="text/javascript">
var numwrestler = <?php echo $wrestlerkey; ?>;
var sprytextfield = [];
for (var i = 0; i < numwrestler; i++) {
var num = i+1;
var sprytextfield[num] = new Spry.Widget.ValidationTextField("sprytextfield"+num, "none", {validateOn:["change"], maxChars:20});
}
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
I'd recommend that you use a Javascript array for this type of task.
Your code is mostly correct, but the var in your for loop is incorrect, and the creation of the num variable instead of just using i is redundant.
<script type="text/javascript">
var sprytextfield = new Array();
var numwrestler = <?php echo $wrestlerkey; ?>;
for(var i = 0; i < numwrestler; i++){
sprytextfield[i] = new Spry.Widget.ValidationTextField("sprytextfield"+(i+1), "none", {validateOn:["change"], maxChars:20});
}
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
Be sure that your PHP variable(s) are defined in the file before you include them in your script.
In your PHP code, you never define the variable divkey, by deafault the value will be 0.
Try:
<script type="text/javascript">
<?php $divkey = 10; for ($i = 0; $i < $divkey; $i++) { $num=$i+1; ?>
var sprytextfield<?php echo $num;?> = new Spry.Widget.ValidationTextField("sprytextfield<?php echo $num;?>", "none", {validateOn:["change"], maxChars:20});
<?php }?>
var sprytooltip1 = new Spry.Widget.Tooltip("sprytooltip1", "#sprytrigger1");
</script>
Please, note that the variable that you are using as index $num in every iteration of the loop will be increasing 2, because of the i++ and the $num=$i+1
Here I am getting the counter value using javascript.
I want to insert those counter value into my database.
How can I do it? Please suggest me.
<script language="JavaScript">
var counter = 1;
function moreFields() {
counter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i = 0; i < newField.length; i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
window.onload = moreFields;
</script>
please read W3school ajax tutorial and click on try it yourself button I am sure that you will easily get that :)
I am trying to develop a select box so that I can change the selected option dynamically
e.g.
selectbox option display message
---------------------------------------------
field 1 text
field 2 integer
field 3 bool
There are three select boxes. The first select box provide three options.
when select box 1 is selected, the other select boxes will have only 2 options (excluding the selected one)
When select box 2 is selected, the other select boxes will have only 1 option (excluding the selected two)
When a select box's value changes, the appropriate message is displayed.
All of the text that will be displayed is read in from a database as an array in the following format:
name text
id integer
address text
Then I create a select box with the three option
When I set select box 1's value as name, the text message is displayed, and so on.
How should I implement this? (I hope you get my idea) Thank you again for your help.
Thank you
I'd suggest something akin to the following:
var sel1 = document.getElementById('one'),
sel2 = document.getElementById('two'),
sel3 = document.getElementById('three'),
sels = document.getElementsByTagName('select'),
reset = document.getElementById('reset');
function disableOpts(elem) {
for (var i = 0, len = sels.length; i < len; i++) {
if (sels[i] != elem) {
var opts = sels[i].getElementsByTagName('option');
for (var c = 0, leng = opts.length; c < leng; c++) {
if (c == elem.selectedIndex) {
opts[c].disabled = true;
}
}
}
}
};
sel1.onchange = function() {
disableOpts(this);
};
sel2.onchange = function() {
disableOpts(this);
};
sel3.onchange = function() {
disableOpts(this);
};
JS Fiddle demo.
Edited to add the messages, as requested in comments (which I overlooked in the actual question...):
var sel1 = document.getElementById('one'),
sel2 = document.getElementById('two'),
sel3 = document.getElementById('three'),
sels = document.getElementsByTagName('select'),
reset = document.getElementById('reset'),
msgs = ['text','integer','boolean'];
function disableOpts(elem) {
for (var i = 0, len = sels.length; i < len; i++) {
if (sels[i] != elem) {
var opts = sels[i].getElementsByTagName('option');
for (var c = 0, leng = opts.length; c < leng; c++) {
if (c == elem.selectedIndex) {
opts[c].disabled = true;
}
}
}
}
hideMessage(elem);
};
function displayMessage(elem){
for (var i=0,len=sels.length;i<len;i++){
if (sels[i] == elem){
var span = elem.parentNode.getElementsByTagName('span')[0];
span.innerHTML = msgs[i];
span.style.display = 'block';
}
}
};
function hideMessage(elem){
for (var i=0,len=sels.length;i<len;i++){
if (sels[i] == elem){
var span = elem.parentNode.getElementsByTagName('span')[0];
span.innerHTML = '';
span.style.display = 'none';
}
}
};
sel1.onchange = function() {
disableOpts(this);
};
sel2.onchange = function() {
disableOpts(this);
};
sel3.onchange = function() {
disableOpts(this);
};
sel1.onfocus = function() {
displayMessage(this);
};
sel2.onfocus = function() {
displayMessage(this);
};
sel3.onfocus = function() {
displayMessage(this);
};
sel1.onblur = function() {
hideMessage(this);
sel2.onblur = function() {
hideMessage(this);
};};
sel3.onblur = function() {
hideMessage(this);
};
JS Fiddle demo.
Take a look at this plugin, maybe it can help you.
For the data than you can put a php foreach for the <option> element on the select.