Ths script generates a number:
function updateDue() {
var kmold1 = parseInt(<?php echo $km; ?>);
var kmnew1 = parseInt(document.getElementById("kminput").value);
var tot = kmnew1 - kmold1;
document.getElementById("kmtot").innerHTML = tot;
document.getElementById("kmnew").innerHTML = kmnew1;
document.getElementById("kmold").innerHTML = kmold;
}
The number is displayed on a webpage with this code:
Diff in Km: <span name="kmtot" id="kmtot" value=""></span><br>
This is part of an form that is used to post to an other file.
How can I send the output of id="kmtot" to the next php file?
I have tried:
Diff in Km: <span name="kmtot" id="kmtot" value=""></span><br>
Not working.
<input type="hidden" name="kmtot" id="kmtot">
If I add this, the number of id="kmtot" is not displayed on the webpage, and is not transfered.
Any hints or solutions?
If you are using jQuery, use this code:
$.ajax({
url: 'your-php-file.php',
method: 'post',
data: {
'kmtot': $('#kmtot').val(),
},
success: function(data) {
console.log(data);
}
})
In your-php-file.php, $_POST['kmtot'] will return the value of your element with the ID kmtot.
If you are not using jQuery, you could use Fetch API.
Related
I'm catching data from Database with Ajax.
In the second Ajax request I try to put the variables from first Ajax request to the new DOM elements from second request but there the variables have same value from last array possition.
I have no idea why .
unfortunately I didn't find the information about that.
a simple example:
//Firt ajax request
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "connect/get-fistinformations.php",
data: {
folder_type:folder_type
},
dataType: "json",
for(var first_key in json){
var info = json[first_key];
//If I put there some alert - alert('some_alert'); - the rest of the code works fine
//Catching Data with Json - working correctly
var folder_id = info[0];
var folder_name = info[1];
var folder_date = info[2];
folder_id;
//Second ajax request
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: 'connect/get-secondinformations.php',
data: {
folder_type:folder_type,
folder_id:folder_id
},
dataType: 'json',
success: function(json){
for(var s_key in json){
var second_info = json[s_key];
//Catching more data from other Data table - working correclty
var count = second_info[0];
var route = second_info[1];
var distance = second_info[2];
var price = second_info[3];
var price_per_km = +(price) / (+(route) + +(distance));
//Without the alert from the firt ajax request
//There inside new elements I try to put variable from first Ajax catching (folder_id, folder_name,folder_date)
//But every time when I add new elemets to DOM, these three variables have same value - from last arrray position
//For example folder_id = '50' | folder_name = 'Some folder name' | folder_date = '2020-07-04'
//New elements for DOM
if(count>0){
var full_line_folder = '<div class="full-line-folder folder">'+
'<i class="some-line"></i>'+
'<span class="folder-name">'+folder_name+'</span>'+
'<span class="folder-comment">Utworzono: '+folder_date+'<br />Pozycje: '+count+'<br />Dystans: '+route+'km<br />Stawka: '+price_per_km+' €/km<br />Puste kilometry: '+distance+'km</span>'+
'<input type="radio" name="folderid" value="'+folder_id+'" style="display:none;" checked/>'+
'</div>';
$(full_line_folder).appendTo(point);
}else{
var empty_line_folder = '<div class="empty-line-folder folder">'+
'<i class="empty-line"></i>'+
'<span class="folder-name">'+folder_name+'</span>'+
'<span class="folder-comment">Utworzono:'+folder_date+'<br />Pozycje: 0<br />Dystans: 0km<br />Stawka: 0 €/km<br />Puste kilometry: 0km</span>'+
'<input type="radio" name="folderid" value="'+folder_id +'" style="display:none;" checked/>'+
'</div>';
$(empty_line_folder).appendTo(point);
}
}
},
error: function(note){
alert('error');
}
});
}
},
error: function(note){
alert('error');
}
});
The problem is that your first loop proceeds to the next iteration before the data arrives for the ajax request it makes. Mostly, by the time your first ajax response arrives, the loop is already gone and any external variables you try access will have their last values.
There are many workarounds for this. I don't think discussion all that is the scope of this answer.
Your options:
Use closures correctly.
Serialize the requests by using async/await
I have a small website and it is complete. I am just a senior and it is just for a project on learning how to code. Everything works to perfection on the source computer that it was all coded on. I then exported the files and tried on several other computers. The files open up and everything looks okay, but two out of the five HTML buttons won't work. Is there a common reason why this is happening?
This is the java function for the button
$('#createPassSubmit').click(function() {
var create = true;
var location = $('[name="reason"]').val();
var passnumber = $('#passnumber').val();
var note = $('[name="notes"]').val();
var student = $('#studentID').val();
var teacher = $('#teacherID').val();
var dataString = "CreatePass="+create+"&reason="+location+"¬es="+note+"&studentID="+student+"&teacherID="+teacher+"&passnumber="+passnumber;
$.ajax({
method: 'POST',
url: 'ajax.php',
data: dataString,
success: function(data) {
if(JSON.parse(data) === 'ERROR') {
alert("Pass " + passnumber + " is currently in use");
}
else {
$('#form input[type=text]').val('');
$("#form select").val('')
$('#sname').val('');
}
}
});
});
});
Then this is the HTML button its self
<input type="button" id="createPassSubmit" value="Create">
I'm using Firefox and working on a page when I notice that & turns into &.
Usually I can fix this by using html_entitiy_decode() - but in this case it's not working.
Then I discovered this. The alert is fired once the page is loaded.
Before
After
The data is loaded using PHP / Yii - not through JS / Ajax. I am however adding / removing brands using JS Knockout.
<ul data-bind="template: { name: 'brand-item-template', data: $root.brands}">
<li>
<span id="<?= $brand->id?>" data-bind="text: brand_name, attr: {'id': brand_id}"><?= $brand->name; ?></span>
</li>
</ul>
Update
I've discovered that this JS Knockout code is what makes the change. But this code should not be triggered until I add a brand. So why is this affecting my &s?
It's the self.addBrand = function() that makes the change. If I remove this function and leave the rest as it is, everything is fine. Can it be a Knockout bug?
$('#store.manage-special-offers').exists(function(){
Store.mangeSpecialOffers();
});
function manageBrandListModel() {
var self = this;
var store_id = $('.data-item-id').val();
var exiting_list = $('.brand-list ul').clone();
// Data
self.brands = ko.observableArray(create_list(exiting_list));
self.brand_name = ko.observable();
self.brand_id = ko.observable();
self.store_id = ko.observable(store_id);
// This is the function that makes the chage
self.addBrand = function() {
if (self.brand_name() != "") {
// Update DB
$('#store.manage-brands').exists(function(){
$.ajax({
url: site_url + '/associatebrand',
type: "POST",
dataType: 'json',
data: {
Brand: {
brandId : self.brand_id(),
storeId : self.store_id(),
add : true
}
},
success: function (data) {
// Add brand to GUI list
self.brands.push(new brand(self.brand_id(), self.brand_name()));
self.brand_name("");
}
});
});
}
}.bind(self);
(...)
function create_list(exiting_list){
var arr_list = [];
$(exiting_list).find('li').each(function(e,li){
var id = $(li).find('span').prop('id');
var name = $(li).find('span').html(); // <--- This is the problem. Must be .text()
arr_list.push(new brand(id,name));
});
return arr_list;
}
Can anyone explain why this is happening?
The credit should really go to both JeremyCook and Quentin for pointing me in the right direction.
$(exiting_list).find('li').each(function(e,li){
var id = $(li).find('span').prop('id');
var name = $(li).find('span').html(); // <--- This is the problem. Must be .text()
arr_list.push(new brand(id,name));
});
What I did wrong was that I used .html() and the text was returned in HTML format. Changing this to .text() solved my problem.
As a noob, I'm trying to parse a weather.com RSS feed for display on my site. The code below successfully retrieves the data and displays it as an alert. My question is how to take this further and parse the resulting feed instead of just displaying it? The goal is to take parts of the response and embed it into the HTML on the page. For example, if I wanted to output a table that has a row with the current temperature, what would be the syntax?
<script>
function parseRSS(url, callback) {
$.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function(data) {
callback(data.responseData.feed);
}
});
}
parseRSS('http://rss.weather.com/weather/rss/local/USAK0012?cm_ven=LWO&cm_cat=rss&par=LWO_rss',
function(json)
{
alert("Result: " + JSON.stringify(json));
});
</script>
If it helps anyone, here is how I ended up doing it. I went with the feed from accuweather.com, instead of weather.com, just because I happened to get it working first.
1) Obtained the value of the feed "title" field, which contained the current weather values that I needed.
var weatherFeed = json;
var currentConditions = weatherFeed.entries[0].title;
2) Extracted the specific elements, for example currentTemperature:
var firstColonIndex = currentConditions.indexOf(":");
var secondColonIndex = currentConditions.indexOf(":", firstColonIndex + 1);
var currentTemperature = currentConditions.substring(secondColonIndex + 1);
3) Built the HTML using jQuery and embedded the extracted weather values, then put the whole thing within a Div element on my page:
<div class="tile-content" id="MyCityWeather">
<script type="text/javascript">
var weatherElement = "#MyCityWeather";
var temperatureElement = $("<h2/>",
{
style: "margin-left: 25px!important; font-size: 46px!important;"
});
temperatureElement.append(currentTemperature);
temperatureElement.appendTo(weatherElement);
</script>
</div>
I have an ASP.NET MVC application. I'm trying to let the user upload files to the server. I need to use the HTML 5 File API. Currently, I have the following code:
<div><input id="filesToUpload" type="file" multiple="multiple" /></div>
<div><input type="button" value="upload" onclick="return uploadFiles();" /></div>
function uploadFiles() {
var files = null; // How do I get the files collection from "filesToUpload" here?
if ((files == null) || (files.length)) {
alert("Please choose at least one file to upload.");
return;
}
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
reader.readAsBinaryString(f);
uploadFile(reader.result);
}
}
function uploadFile(f) {
// TODO: I'm not sure how to finish my actual AJAX request to post the file back to the server.
$.ajax({
url: "/uploadFile",
type: "PUT",
contentType: "application/json",
success: function (result) {
alert("File Uploaded!");
},
error: function (p1, p2, p3) {
alert("Upload Failed");
}
});
}
As you can see from the code, I have some knowledge gaps that I am trying to fill in.
How do I get the files collection from the "filesToUpload" HTML
element via JQuery? The reason I want this approach is because I do
not want to begin uploading until the user actually clicks the
"upload" button I've shown below.
What do I set as the "data" value in my $.ajax attempt?
What should the contentType be in my $.ajax attempt?
Thank you very much for your help!