I have the following code:
Papa.parse("/drivencarstock.csv", {
download: true,
header: true,
step: function(row) {
console.log("Row:", row.data);
},
complete: function() {
console.log("All done!");
}
});
As you can see I am parsing the 'drivencarstock.csv' file and it outputs into my console perfectly however now I am just wondering how I can output this as a json file on my server?
I can't see how this might be done?
Thanks, Nick
The first step would be to actually collect the parsed data in a variable, such as an array. Then in the step you'd add the row.data to this array. Once complete you could POST the data using AJAX.
For example:
// create the array to hold the data
var myRows = [];
Papa.parse("/drivencarstock.csv", {
download: true,
header: true,
step: function(row) {
// push the row data into the array
myRows.push(row.data);
},
complete: function() {
// upload using jQuery's AJAX
$.ajax({
url: '/path/on/your/server',
method: 'post',
data: myRows,
success: function(response) {
console.log('upload complete', response);
},
error: function() {
console.error('an error occurred');
}
});
}
});
Now, there are a couple of optimisations that could be made, such as posting the array every time it contains a fair amount of data and properly responding to the AJAX success/error callbacks, but this should get you going.
Related
I need to send a value from a input form to a nodejs server, which triggers a calculation with this value and needs to update an p element with the result of the calculation on the client side.
How can this be done?
This is what i have:
//Server side:
app.post('/calculate/:id', function(req, res){
var title = 'Tax Calculation';
var tax= taxcalculation(req.params.id);
res.render('index', {
title: title,
tax: tax,
});
});
//Client side:
var income= document.getElementById("income");
var tax = document.getElementById("tax")
$(income).on('change', function() {
console.log("changed");
$.ajax({
type: 'POST',
url: '/calculate/'+income.value,
success: function() {
$('#tax').html('<%= tax %>');
},
error: function() { // if error occured
alert("Error occured, please try again");
},
});
});
Okay, so you don't give a lot of data, but this sounds as simple as sending a response with the results to the client side in your Node web service that does the calculations and append the result to the P element
Your server code to handle the ajax call should output a json response which will contain the content for the <p>. It should not re-render the whole index page. I don't do a lot of node.js so I'll leave that for you to figure out.
The ajax success function should accept a response as a parameter, and then operate on that response.
Assuming the server response to this ajax request is of the format {"tax": 15.99}:
$.ajax({
type: 'POST',
url: '/calculate/'+income.value,
success: function(response) {
if (response.tax || response.tax === 0) {
$('#tax').html(response.tax);
}
},
error: function() { // if error occured
alert("Error occured, please try again");
},
});
Im develop web apps that have a form.In that's form, i want to make multi select item with remote data (ajax) because i have more than 1800 data.
Im using Select2 for this. But i got an error when try to make it.
Uncaught TypeError: s.results is not a function
This is my init code:
// ----- DIAGNOSE SELECTION ----- //
var res5 = str.replace("antrian", "diagnosa").replace("periksa", "getData");
$("#diagnosa").select2({
placeholder: "Ketik untuk mencari diagnosa pasien...",
minimumInputLength: 3,
multiple: true,
ajax: {
url: res5,
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
var results = [];
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
$.each(data, function(index, item){
results.push({
id: item.kd_diagnosa,
text: item.nm_diagnosa
});
});
console.log(results);
return {
results: results
};
},
cache: true
}
});
// ----- DIAGNOSE SELECTION ----- //
My select2.js
https://jsfiddle.net/22m3tqbf/
My select2.css
https://jsfiddle.net/fgqontcs/
Please help me. If you need any data, i can provide it. Thanks in advanced
I am trying to build a WebApp which consumes REST API's with Flask.
I am getting my JSON object back successfully from my API but I am unable to display it in the HTML UI.
Consider I am trying to print userid from the JSON file, I am getting the error part only.
Can someone please point me out what is going wrong :
Here is my JSON Object which returns:
Here is my JS file:
$(document).ready(function() {
console.log("ready!");
$('#try-again').hide();
// on form submission ...
$('form').on('submit', function() {
console.log("the form has beeen submitted");
// grab values
valueOne = $('input[name="location"]').val();
console.log(valueOne)
$.ajax({
type: "POST",
url: "/",
data : { 'first': valueOne},
success: function(result) {
if (!$.isEmptyObject({result})) {
$('input').hide();
$('#try-again').show();
$('#result').html(result.userid[0])
$(document).ready(function() {
console.log("ready!");
$('#try-again').hide();
// on form submission ...
$('form').on('submit', function() {
console.log("the form has beeen submitted");
// grab values
valueOne = $('input[name="location"]').val();
console.log(valueOne)
$.ajax({
type: "POST",
url: "/",
data : { 'first': valueOne},
success: function(result) {
if (!$.isEmptyObject({result})) {
$('input').hide();
$('#try-again').show();
$('#result').html(result.userid)
$('#result').html('result.userid')
} else {
$('#result').html('Something went terribly wrong! Please try again.')
}
},
error: function(error) {
console.log(error)
}
});
});
$('#try-again').on('click', function(){
$('input').val('').show();
$('#try-again').hide();
$('#result').html('');
});
});
} else {
$('#result').html('Something went terribly wrong! Please try again.')
}
},
error: function(error) {
console.log(error)
}
});
});
$('#try-again').on('click', function(){
$('input').val('').show();
$('#try-again').hide();
$('#result').html('');
});
});
My JSON DATA:
[{"case": 2005608875,
"filepath": "/x/eng/cs-data/latx/dev/20150510_uploads/wilp/perfstat_20150415_001256/node/10.95.172.19/output.data",
"datatype": "perf8",
"perfdateend": "2015-04-15T02:15:37-04:00",
"userid": "wilp",
"filename": "perfstat_20150415_001256.zip",
"version": "v8.1 ",
"perfdate": "2015-04-15T01:14:24-04:00"}]
There are a couple of issues here, and none of them have anything to do with Flask.
You check the length of the returned JSON object. However, in JS objects do not have a length property, so result.length returns undefined which is not greater than 0.
Since you are using jQuery, you can use its isEmptyObject function to check that your object is not empty.
Also, inside that if statement you are inserting the literal string 'result.userid' into your HTML, instead of the actual userid value of the returned JSON.
if (!$.isEmptyObject(result)) {
...
$('#result').html(result.userid)
}
I am trying to get access to the data returned from an ajaxSubmit request.
$("#searchbutton").on('click', function() {
$("#searchform").ajaxSubmit({
success: function(data) {
populate('#registrationform', data);
},
resetForm: true
});
});
The data that is returned is not being recognise by my populate function, If i do however with raw data,
$("#searchbutton").on('click', function() {
$("#searchform").ajaxSubmit({
success: function(data) {
populate('#registrationform', {studentId: 1, firstName: 'Kay'});
},
resetForm: true
});
});
my populate function works. Any ideas why the data returned is not recognised?
My guess is that the data is actually coming back as a String, NOT a JavaScript object. If you are inspecting with console.log(data), this distinction would be very easy to miss.
Looking at the documentation for the success method and the dataType option, it is quite possible that your server's response is being taken for a simple String. Try explicitly setting dataType: "json" and see what comes back. That, or deserialize to an object with JSON.parse().
Use it like,
$("#searchbutton").on('click', function() {
$("#searchform").ajaxSubmit({
success: function(data) {// data should be return as json
populate('#registrationform',{studentId: data.id, firstName: data.name});
},
resetForm: true
});
});
I have a fetch() in the callback function of $.post(). The fetch() grabs the data from the backend and updates the collection just fine, however when its time to run either its success or error callbacks, nothing happens! I placed console.log()s in both its callbacks and they never appear in the Javascript console.
Any idea what happened?
A method in a View
create_set: function() {
var self = this;
// Post data to server
$.post('api/create_set', {
user_id: $('#user_id').val(),
post_id: this.post_id,
set_name: $('#new_set_name').val()
}, function() {
// Update list of Sets
self.setList.fetch({
data: {
user_id: $('#user_id').val(),
post_id: this.post_id
},
processData: true
}, {
success: function() {
// Highlight the first class in list
$(self.setListView.el).children('div:first').addClass('active');
console.log('success'); // DOESNT RUN!
}
}, {
error: function() {
console.log('error'); // DOESNT RUN!
}
});
console.log('hello'); // RUNS!
});
}
success and error should be the properties of options object that you pass to fetch, you don't have to create separate objects for them:
self.setList.fetch({
data: {...},
processData: true,
success: function(){...},
error: function(){...}
})