Updating values on page without refreshing in Node.js - javascript

I am trying to update values on my page when I user selects what they want to filter but I do not want to refresh the webpage constantly. As an example, think of a real estate website where you filter based on location and the types of housing come back with the number (e.g., apartment [4] townhouse [0] studio [5]). The types of housing will always be there but its the numbers I am interested in updating. When ever you change the filter, new numbers are popping up. What I am doing is filtering questions based on topic, subject etc.
Is there anyway to use this in node.js? What I have working so far requires the page to refresh.
$.ajax({
type="POST",
url: "/user/calculatequestions",
data: {
filter date here... },
success: function () { },
error: function () { }
});
The '/user/calculatequestions' goes through an app.post and renders a new page with new variables.
Thanks in advance,
S

You can get the values of the filter through Java Script and send data filter through Ajax.
Example of input:
<input id="field" name="field1" type="text" >
Java Script function (together Ajax stack):
var data = {};
data.fielter_data1 = document.getElementById('field');
$.ajax({
type="POST",
url: "/user/calculatequestions",
data: data,
success: function () { },
error: function () { }
});
Then, in the function node called /user/calculatequestion you can get the parameters filter with:
var filter_data = req.body.fielter_data1;
The success callback returns the data after note proccess, then you update the components (inputs, tables, lists and etc) in the front-end.
See this question please: How to refresh table data using Ajax, Json and Node.js

Related

Ajax Parameter Being Received as {string[0[} in MVC Controller

First of all, I have never successfully built an AJAX call that worked. This is my first real try at doing this.
I am working on building a function to update existing records in a SQL database. I am using ASP.NET Core (.NET 6) MVC but I also use JavaScript and jQuery. I cannot have the page refresh, so I need to use ajax to contact the Controller and update the records.
I have an array that was converted from a NodeList. When I debug step by step, the collectionsArray looks perfectly fine and has data in it.
//Create array based on the collections list
const collectionsArray = Array.from(collectionList);
$.ajax({
method: 'POST',
url: '/Collections/UpdateCollectionSortOrder',
data: collectionsArray,
})
.done(function (msg) {
alert('Sent');
});
However, when I run the application and debug the code, the array is received in the Controller as {string[0]}.
Here is the method which is in the Controller, with my mouse hovered over the parameter:
Do not pay attention to the rest of the code in the controller method. I have not really written anything in there of importance yet. I plan to do that once the data is correctly transferred to the Controller.
I have tried dozens of ideas including what you see in the Controller with the serialize function, just to see if it processes the junk data that is getting passed, but it hasn't made a difference.
I have been Googling the issue & reading other StackOverflow posts. I've tried things like adding/changing contentType, dataType, adding 'traditional: true', using JSON.stringify, putting 'data: { collections: collectionsArray }' in a dozen different formats. I tried processing it as a GET instead of POST, I tried using params.
I am out of ideas. Things that have worked for others are not working for me. What am I doing wrong? I'm sure it's something minor.
UPDATE: Here is the code which explains what the collectionList object is:
//Re-assign SortID's via each row's ID value
var collectionList = document.querySelectorAll(".collection-row");
for (var i = 1; i <= collectionList.length; i++) {
collectionList[i - 1].setAttribute('id', i);
}
What I am doing is getting a list off the screen and then re-assigning the ID value, because the point of this screen is to change the sort order of the list. So I'm using the ID field to update the sort order, and then I plan to pass the new IDs and names to the DB, once I can get the array to pass through.
UPDATE: SOLVED!
I want to post this follow up in case anyone else runs into a similar issue.
Thanks to #freedomn-m for their guidance!
So I took the NodeList object (collectionList) and converted it to a 2-dimensional array, pulling out only the fields I need, and then I passed that array onto the controller. My previous efforts were causing me to push all sorts of junk that was not being understood by the system.
//Create a 2-dimensional array based on the collections list
const collectionArray = [];
for (var i = 0; i < collectionList.length; i++) {
collectionArray.push([collectionList[i].id, collectionList[i].children[1].innerHTML]);
}
$.ajax({
method: 'POST',
url: '/Collections/UpdateCollectionSortOrder',
data: { collections: collectionArray }
})
.done(function (msg) {
alert('Sent');
});
2-d array is coming through to the Controller successfully

What's a correct way of retrieving data?

I've posted a few questions seeking clarity in small details about the do's and don't's of javascript, ajax and html. And here's one more. I'm creating a list with javascript by the usage of an api. When making the list I get the correct values for the text. When pressing the button in the row I'm getting the alert message. But the new entry is blank.
Can I add data this way (a for loop getting info and building a string with it baked in)?
OR is it the way I retrieve and store data that is wrong?
EDIT: My data is undefined. Don't I get a string from: data.items[i].Info.drivers?
Part of javascript that talks to an api and gives drivers and cars. This segment is part of a for loop.
...+'<h5><data-title="'
+data.items[i].Info.drivers+'">'
+data.items[i].Info.drivers
+'</data></h5>'
+'<p class="subtitle"><data-title="'
+data.items[i].Info.cars+'">'
+data.items[i].Info.cars
+'</data></p>'
+ '<input class="adding"type="button" name="vehicle" value="Add book">'...
My add code (javascript in html):
$(document).on('click', '.adding',function() {
window.alert("active");
var $this = $(this);
var drivers = $(this).data('drivers');
var cars = $(this).data('cars');
alert($(this).data('drivers')); //<----gives alert, says Undefined
$.ajax({
url: 'insert.php',
type: 'POST',
data: {
'driver': drivers,
'car': cars
},
success: function(msg) {
window.alert("success triggered");
}
});
});
This is referring to the button. By putting the data attributes in the button in the same way the problem is solved.

How to pass data from Laravel View to Ajax or Javascript code without html div (id or class) - Laravel 5.3

So, currently I am passing values stored in Database MySQL to View (using Controller). I do simple querying ModelName::where()->first();.
I have my data right now in View. I want to use that data in Ajax or Javascript code that I am writing.
I can have 46 values and one way to do this is to have <div id="field1"></div> for 46 times set div style to display:none in css and in Javascript use document.getElementById('field1'); to access the values and finally, do whatever I want to do with it.
But I find this quite long and un-necessary to do as there is no point of printing all the values in html first and then accessing it. How can I directly get {{$data}} in Javascript?
myCode
public function index(Request $request){
$cattfs = Cattf::all();
$cattts = Cattt::all();
$cattos = Catto::all();
return view('/index',compact('cattfs'));
}
View
Nothing in the view. and I prefer it to be none.
Javascript and Ajax
$(document).ready(function()
{
init();
});
function init(){
my_Date = new Date();
var feedback = $.ajax({
url:url,
dataType: "JSON",
type: "GET",
}).success(function(data){
console.log(data);
//I have some data called data from url
//I want some data from controller like: cattf,cattt,catto
//I will combine url data and cattf and do simple arithmetic to it
//finally output to the view.
}).responseText;
}
One good way would be to actually make a small API to get your data. Let's say you wanted to retrieve users.
In the api.php file in your route folder:
Route::get('/posts', function () {
return Post::all();
});
and then you just need to use http://yourUrl.dev/api/posts as your URL sent in your .ajax() call to work with what you need.
I found best solution use this: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
It takes values from controller directly to Javascript.

How to serialize dynamic form data to keep maximum UI flexibility?

Due to the nature of my current project, I often find myself having to create HTML <form> elements which must support dynamic add/remove functionality of items for posting collections to the server.
My issue is that I find myself constrained by the name attribute of the form elements because I have to keep track of indices, ex.: Room[1].Tourists[0].Name. This is giving me hard times when I would like, for example, to remove an existing input element from the beginning.
I am currently building these dynamic forms with react.js which is enabling great flexibility, but I was wondering if there was some way that I could collect form data on submit event and just serialize it to match the expected model in the controller's action and post it?
Okay so you just want to solution about this i think you were stuck somewhere in your code that's why i am asking about the sample code no worry back to this try this:
<script type="text/javascript">
$(document).ready(function () {
$("#btn_submit").on('click', function () {
$.ajax({
type: "POST",
url: "Give URL here",
async: false,
data: $("#FormID").serialize(),
success: function (result) {
//Do what you want
},
error: function (response) {
//Do what you want
}
});
});
});
</script>

Using JSON to store multiple form entries

I'm trying to create a note taking web app that will simply store notes client side using HTML5 local storage. I think JSON is the way to do it but unsure how to go about it.
I have a simple form set up with a Title and textarea. Is there a way I can submit the form and store the details entered with several "notes" then list them back?
I'm new to Javascript and JSON so any help would be appreciated.
there are many ways to use json.
1> u can create a funciton on HTML page and call ajax & post data.
here you have to use $("#txtboxid").val(). get value and post it.
2> use knock out js to bind two way.and call ajax.
here is simple code to call web app. using ajax call.
var params = { "clientID": $("#txtboxid") };
$.ajax({
type: "POST",
url: "http:localhost/Services/LogisticsAppSuite.svc/Json/GetAllLevelSubClients",
contentType: 'application/json',
data: JSON.stringify(params),
dataType: 'json',
async: false,
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
}
I have written a lib that works just like entity framework. I WILL put it here later, you can follow me there or contact me to get the source code now. Then you can write js code like:
var DemoDbContext = function(){ // define your db
nova.data.DbContext.call(this);
this.notes=new nova.data.Repository(...); // define your table
}
//todo: make DemoDbContext implement nova.data.DbContext
var Notes = function(){
this.id=0; this.name="";
}
//todo: make Note implement nova.data.Entity
How to query data?
var notes = new DemoDbContext().notes.toArray(function(data){});
How to add a note to db?
var db = new DemoDbContext();
db.notes.add(new Note(...));
db.saveChanges(callback);
Depending on the complexity of the information you want to store you may not need JSON.
You can use the setItem() method of localStorage in HTML5 to save a key/value pair on the client-side. You can only store string values with this method but if your notes don't have too complicated a structure, this would probably be the easiest way. Assuming this was some HTML you were using:
<input type="text" id="title"></input>
<textarea id="notes"></textarea>
You could use this simple Javascript code to store the information:
// on trigger (e.g. clicking a save button, or pressing a key)
localStorage.setItem('title', document.getElementById('title').value);
localStorage.setItem('textarea', document.getElementById('notes').value);
You would use localStorage.getItem() to retrieve the values.
Here is a simple JSFiddle I created to show you how the methods work (though not using the exact same code as above; this one relies on a keyup event).
The only reason you might want to use JSON, that I can see, is if you needed a structure with depth to your notes. For example you might want to attach notes with information like the date they were written and put them in a structure like this:
{
'title': {
'text':
'date':
}
'notes': {
'text':
'date':
}
}
That would be JSON. But bear in mind that the localStorage.setItem() method only accepts string values, you would need to turn the object into a string to do that and then convert it back when retrieving it with localStorage.getItem(). The methods JSON.stringify will do the object-to-string transformation and JSON.parse will do the reverse. But as I say this conversion means extra code and is only really worth it if your notes need to be that complicated.

Categories