Setting up a Todo List server - javascript

I'm fairly new to Javascript, Node.js and JSON. I'm supposed to build some sort of Todo list application, where the user sends his todo to a server. I've already created the HTML and Javascript to execute the basic operation without the server.
I'm using the following program/languages in order to complete my assignment:
Vagrant (various NPM modules)
VirtualBox
Javascript (jQuery)
Currently i'm trying to send the data via the following lines of code:
//Create (simplified) "task"
item["id"] = task.dataset.id;
item["taskname"] = task.dataset.taskname;
item = JSON.stringify(item);
//Send code
$.ajax({
url: '/addtodo',
type: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
},
data: item
});
Where as on the receiving side, I try to receive the data using the following lines of code:
app.post("/addtodo", function (req, res) {
var newTodo = req.body;
fs.writeFile("Somefile.json", JSON.parse(newTodo), function(err) {
if(err) {
res.json({"message":"Storing data failed"});
} else {
res.json({"message":"Data stored successfully"});
}
});
});
My objective is to get something like this in "Somefile.json"
[{
"id" : 2,
"taskname" : "Example task 2",
},
{
"id" : 2,
"taskname" : "Example task 2",
},
]
For now I get either errors or it changes the Somefile.json into [object Object].
Anyone care to explain what I did wrong and how I should fix it
Edit:
If I do not use JSON.parse i get : [object Object]
If I use JSON.stringify I get {"{\"id\":\"6\",\"taskname\":\"1234\"}":""}

Instead of the
JSON.parse(newToDo);
Use
JSON.stringify(newToDo);
This function will convert the object into a string and will give you the desired output.

Related

Associating xxxx_id with xxxx.id

I am running into a problem where when I submit a "property listing" I get this response:
{"owner_id":"Batman","address":"test","state":"test","sale_price":"test"}
The thing is "owner_id" is supposed to equal or associate with owner's id in a different table/JSON file (e.g owner_id = owner.id), not a string in this case which is why the object is not saving on the back-end.
Is anyone in vanilla JavaScript able to show me an example on how to associate owner_id and owner.id?
It'd be more like :
{
owner: {
id: "Batman"
},
address: "test",
state: "test",
sale_price: "test"
}
You should take a look at : https://www.w3schools.com/js/js_json_objects.asp
EDIT: Not sure how you're fetching this data but it seems like you want to handle the response you're getting.
Here is a simple GET request using the fetch api:
fetch('http://example.com/heroes') //this is the path to your source where you're getting your response data
.then((response) => {
return response.json();
//above you return a promise containing your response data
//you can also handle your response before declaring it in a var here
})
.then((myJson) => {
//you have stored your response data as a var myJson
console.log(myJson);
//here you can work your response data in any way you need
// to show an example (not that you would do this) I've provided a owner object that checks if it's property is equal to the incoming data
var owner = {
"id": Batman,
}
if ( myJson.owner_id === owner.id ) {
//do something here
}
});
More info here.

Uncaught TypeError: b.toLowerCase is not a function

I am fetching some records :
$companies = \App\User::where('type', 'pet-salon')->orWhere('type', 'veterinarian')->get();
return response()->json($companies);
The data coming back is an array of objects:
[{
id: 2,
type: "xxx",
deactivate: 0,
xxx: "Hello",
middle_name: "Mid",
lastname: "xxx",
//...
}]
This is the jQuery typeahead code:
$('#getCompaniesForConnection').typeahead({
source: function (query, process) {
return $.get('/all/companies', { query: query }, function (data) {
return process(data);
});
}
});
The exception its giving me :
Uncaught TypeError: b.toLowerCase is not a function
And the results drop-down is not showing too, What am i missing here ?
Yes, you need to json_encode your companies.
$companies = \App\User::where('type', 'pet-salon')->orWhere('type',
'veterinarian')->get();
$result = json_encode($companies ); // return this or echo
First, the PHP code looks like it's a laravel code, so you can just return the $companies variable like so:
$companies = \App\User::where('type', 'pet-salon')->orWhere('type', 'veterinarian')->get();
return $companies;
Since models and collections are converted to JSON when cast to a string, you can return Eloquent objects directly from your application's routes or controllers.
And also, let's see the definition of the process function to be sure that's not where the error is coming from.

Get value in Json with ajax [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have an API that returns JSON like this:
[{
"Code": "001",
"Name": "xyz",
"Members": [{
"FullName": "User1"
}]
}, {
"Code": "002",
"Name": "asd",
"Members": [{
"FullName": "User2"
}]
}]
I want to replace Name and member in my label matching with "Code" and i want to do that with ajax. How can achieve the matching with Code?
This is my implementation:
$('#btnFind').on('click', function () {
var Code = $("#input_edit_code").val();
$.ajax({
type: "get",
url: "/mvc/ComplaintHandlerSquadGetListPage",
success: function () {
alert();
},
error: function (ex) {
alert(ex.title);
}
});
})
You can use javascript's filter and map Array's functions.
Let's pretend you store the code typed by the user inside this codeNumber var
var codeNumber = '002';
Your array of members:
var members = [{"Code":"001","Name":"xyz","Members":[{"FullName":"User1"}]},{"Code":"002","Name":"asd","Members":[{"FullName":"User2"}]}];
A function to filter your array by Code :
var byCode = function(member) {
return member.Code === codeNumber;
};
A function to get the name of the filtered member :
var getName = function(member) {
return member.Name;
};
You get the member's name
var memberName = members.filter(byCode).map(getName).toString();
console.log(memberName);
I don't believe AJAX and simple JSON alone can do what you want.
JSON is a way to structure objects - JavaScript Object Notation. It only structures data.
AJAX is an Asynchronous means of making an HttpRequest. It asks a server for something.
If you use AJAX to ask for a JSON file. You will get the JSON data.
I believe you have two options:
Use AJAX to request the data from the server. The server will then have to load the JSON file, find the correct data and return the correct data to AJAX.
Use AJAX to get the JSON data. Find the correct data with JavaScript.
Inside the success handler, you can compare something like this:
success: function(response) {
// yourObject that matches the code
var yourObject = response.filter(function(item) {
return item.Code === Code
});
// wherever you want to show this name
$("body").text(yourObject.Name);
}
$.ajax({
type: "get",
url: "/mvc/ComplaintHandlerSquadGetListPage",
success: function (result) {
jQuery(result).each(function(i, item){
if(item.Code == Code)
{
$('#myid').text(item.Name);
}
},
error: function (ex) {
alert(ex.title);
}
});

Incorrect returns from $.getJSON and node-async - server side node/express jsonp

I'm getting an odd error when using $.getJSON with node-async to a server running node/express with jsonp response.
I make two calls to the server using node-async iterating over an array but when all is done the second result has some properties which contain the values from the first.
The odd thing is that the server side response IS coming back - as one of the properties that came back is correct - but another property looks like it is overwritten on the second call by the property from the first.
On the server side, I've debugged it and checked the res.jsonp line which is returning the correct results, I've also checked it with some console logging server side.
Code below - TLDR results are as follows:
//Expecting results to be:
[
{"series":1, options:{serverSays:"Here is series 1"},data: [a:1,b:2,c:3]},
{"series":2, options:{serverSays:"Here is series 2"}, data: [x:9, y:8, z:7]}
]
//Actual Results are
[
{"series":1, options:{serverSays:"Here is series 1"}, data: [a:1,b:2,c:3]},
{"series":2, options:{serverSays:"Here is series 2"}, data: [a:1,b:2,c:3]}
]
Here's a simplified version of the code (with much junk taken out but logic remaining intact):
var series = [
{id: 1},
{id: 2}
]
var results = [];
//A function to get data from the server and return it
function getData(id, cb)
{
var url = serverUrl + "/GetSomeData/" + id;
$.getJSON(url)
.done(function (serverResponse)
{
console.log("Response from server: ", serverResponse)
cb({"series": id, options: serverResponse.options, data: serverResponse.data});
}
}
//A function to iterate through the series using async.forEach
function iterator(s, callback)
{
getData(s.id, function(data)
{
//Use the data
results.push(data);
//Tell async we are done with this iteration
callback()
});
}
function done(err)
{
console.log("Finished");
//Expecting results to be
//[
// {"series":1, options:{serverSays:"You Requested Series 1"},data: [a:1,b:2,c:3]},
// {"series":2, options:{serverSays:"You Requested Series 2"}, data: [x:9, y:8, z:7]}
//]
//Actual Results are
//[
// {"series":1, options:{serverSays:"You Requested Series 1"}, data: [a:1,b:2,c:3]},
// {"series":2, options:{serverSays:"You Requested Series 2"}, data: [a:1,b:2,c:3]}
//]
}
async.eachSeries(series, iterator, done);
I've tried it with async series, async parallel and with the promise style getJSON and the callback style getJSON - all show the same error.
Could be my client side code or else maybe I'm doing something silly with the server side jsonp.
Server side, I build the data then go
return res.jsonp(output);
Any thoughts?
I have to admit, I can't find any problem with your code. For the sake of exhausting all options, maybe you can try async.map?
var series = [
{id: 1},
{id: 2}
]
//A function to get data from the server and return it
function getData(id, cb)
{
var url = serverUrl + "/GetSomeData/" + id;
$.getJSON(url)
.done(function (serverResponse)
{
console.log("Response from server: ", serverResponse);
cb({"series": id, options: serverResponse.options, data: serverResponse.data});
});
}
//A function to iterate through the series using async.forEach
function iterator(s, callback)
{
getData(s.id, function(data)
{
//Tell async to add data to the result list
// and continue with the next iteration.
callback(null, data); // err = null
});
}
function done(err, result)
{
console.log("Finished");
}
// Note that map doesn't perform the iterator in order, but the result list is in order.
async.map(series, iterator, done);
Have you tried checking the network tab of the developer tools to see the response from the server the browser received?
If the response is the same as the expected output, there is probably something missing from the picture here.
Doh. Looks like I was being caught out by an external function call breaking the chrome inspector horribly!!
I finally realised that the chrome console was not displaying valid data in the inspector, but if i JSON.stringify'd the object it displayed correctly.
E.g.
console.log("Server response is: ", serverResponse) //In the getJSON callback
Would give the tree view for the incorrect object which would look like this:
{"series":2, options:{serverSays:"Here is series 2"}, data: [a:1,b:2,c:3]} //Incorrect data property
But doing
console.log("Server response is: ", JSON.stringify(serverResponse))
Showed the correct JSON:
{"series":2, options:{serverSays:"Here is series 2"}, data: [x:9, y:8, z:7]} //Correct data property
--
The cause? What I was doing with the data. One of the "junk taken out" lines that i removed from the example was a call to a highcharts chart to set the series data - along the lines of
getData(s.id, function(data)
{
//THE OMITTED LINE
chart.series[someSeries].setData(data.data);
//Tell async to add data to the result list
// and continue with the next iteration.
callback(null, data); // err = null
});
This was tripping over a bug I had in the chart definition, but instead of failing gracefully it somehow broke the chrome inspector...!
I'm guessing with the scope hell of node-async + $.getJSON + multiple functions + callbacks, this was the final straw. Go Figure!

Adding keys to objects in a parse object

Im working with the parse javascript sdk and i want to add a key to an object in a Parse 'object' when saving it.
For ex:
var saveGif = new SaveGifTags();
saveGif.save({
type: req.body.type,
tag: req.body.tags[i],
gifObjects: newGif
}, {
success: function(data) {
console.log(data);
res.json(data);
},
error: function(data) {
console.log(data);
}
});
gifObjects is my object in the Parse Class. I tried to do something like this
gifObjects: gifOjects[gifObj.id] = newGif;
newGif of course is the object i want to save. This gave me an error of gifObjects is not defined. So i tried something like this
gifObjects[gifObj.id] : newGif;
that didnt work either. i want to create something like this:
{
hgs32: {
url: '',
image: ''
},
64522 : {
url: '',
image: ''
}
}
any suggestions?
Figured it out. Not sure what the downvote is for, but i had to create the object before i saved it.
var gifObjects = {};
gifObjects[gifObj.id] = newGif;
and then the save
saveGif.save({
type: req.body.type,
tag: req.body.tags[i],
gifObjects: gifObjects
},

Categories