I have built a form to add some dummy data to a Mongo collection for testing purposes. The function to add the data seems to be working ok in that the data is being added ok, but, for some reason, the redirect command at the end of the function is not doing its thing. The data comes from a bog standard HTML form. Here is the code for adding the data:
router.post('/addacc',function(req,res){
var sljEdate = "";
var pljEdate = "";
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/stc';
MongoClient.connect(url,function(err,db){
if(err){
console.log("Connection Error");
}else{
console.log("connected to mongo");
var collection = db.collection('account');
var query = {accountID: req.body.acc_id,companyName: req.body.acc_name,companyEmail:req.body.acc_email,companyPhone:req.body.acc_phone,companyPostCode:req.body.acc_postcode,
photographers: {phtID:"",phtName:"",phtPhone:"",phtEmail:"",phtLoc:"",preferredContact:"",lastJob:"",pljEpoch:pljEdate,phtNotes:""},
schools: {schoolID:"",schoolName:"",schoolPhone:"",schoolEmail:"",schoolPostCode:"",lastJob:"",sljEpoch:sljEdate,notes:""}};
collection.insert(query,function(err,result){
if(err){
console.log("Error inserting Account record",err);
}else{
console.log("Data Insert Success");
res.redirect("/forms");
}
db.close();
});
}
});
});
I added lines to log to the console in a few places so that I could check progress and they all fire, including the final 'Data Insert Success' one. The res.redirect which follows it, however, does nothing. In the browser the URL remains as '/addacc', though the node console shows a subsequent GET for the '/forms' URL.
I've tried a few variations for the redirect, using e.g. res.send("test") just to try and output something, also a res.render function, but none of them seem to work.
I'm pretty sure that I have missed something simple, but I've been staring at the code for too long and I can't see anything wrong with it. In fact, I've had nearly identical code working lots of times. The only thing I'm doing differently this time is that I'm inserting into a Mongo collection which includes embedded documents, but the data insert is not the problem as the data gets in fine.
Help please!
Ok, it seems that the Node problem above was a bit of a red herring. The redirect is actually working ok (MrWillihog's comment above is duly noted for future reference anyway). I thought it must be as all the response codes on the npm console checked out fine. The problem is actually to do with the rendering of the Jade template. Specifically something to do with the the file layout.jade which I use to set out the HTML head. For some reason (yet to be determined) things work fine when calling the /forms page directly in the URL. The file forms.jade starts in the standard way with
extends layout
block content
With the opening BODY tag in layout.jade the page fails to load properly when called from the redirect: the layout.jade file renders (I put an H1 in there to check), but forms.jade doesn't.
I moved the BODY down in to forms.jade (under block.content) and it started working though, interestingly, the URL in the address bar remains as '/accadd'
Again I'm a bit stumped as I have used this pattern quite a few times with no issue. I'm guessing that I've just forgotten something simple. I'll keep digging until I find the answer, but at least now I should be looking in the right place.
Related
hello first thank you for your help to my first question in stackoverflow.
my qeustion is "how to use render's second parameter 'locals' on script in pug file".
in index.js...
router.get('/', function(req, res, next) {
Movie.find({}).then((movies)=>{
res.render('index', {movies:movies});
}).catch((err)=>{
console.log(err);
});
};
in index.pug...
extends layout
block content
ul
each movie in movies
li
a(href='/edit/'+movie._id) #{movie.title}
script(type='text/javascript').
console.log(movie)
and the console.log output is "uncatched reference error: movie is not defiend".
on "a(href='/edit/'+movie._id) #{movie.title}" the movie is working but,
on "console.log(movie)" it's not.
i think scope is not matter and the declaration also no problem.
what is problem? and how can i use the locals on script in pug file?
one more time, really thank you for your help!!
Of course it's undefined. Understand what is happening :
Pug is rendering an HTML file. Meaning, it's a template, that you fill with values. Pug is going to "bake" all this and output an HTML file. Good.
This file contains a line of code, as text : console.log(movie). Very well.
Now, this HTML file is sent to the browser, where it is parsed, an the code executed.
The browser starts executing the code, sees console.log(movie) and says "What the heck is movie?" Crash : movie is undefined.
This is the difference between server-side and client-side environments. Your file is being created on the server, but executed in a browser, a totally different environment in a totally different machine. There's no way movie is defined there.
Currently attempting to build a Wikipedia viewer as per the Free Code Camp project. You can see the whole CodePen here. Now, in my console I can see that sometimes, I get a response with the data I was looking for. Other times, I get no response at all, and still other times running the search causes all of the content on my page to simply disappear. I thought initially it might be a caching issue, but there are instances where it will successfully run multiple searches in a row then either stop or disappear; and others where it will not receive any data at all.
When I have these malfunctions, the console does not display any errors, so I don't have any feedback about what's going wrong.
Here's the relevant code:
function wikiSrch(){
var srchParam = "";
var srchRes;
$("#searchB").click(function(){
srchParam = $("#inpt").val();
$.getJSON("https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + srchParam + "&format=json&callback=?", function(data){
console.log(JSON.stringify(data));
});
});
}
$(document).ready(function(){
wikiSrch();
})
So, have been trying to get a javascript to read a spreadsheet, but needed it private rather than public, so spent quite a bit of time trying to figure out how to do that. It is actually quite easy, or seems like it is, except that I still can't read the spreadsheet. Will cover private spreadsheets through the cloud console in the end.
So, I have a rather simple spreadsheet which contains about 6 columns, (including customer emails and similar, hence why private). And I have been playing about trying to get it to work for the last couple of days.
First, the string!
So to enable this I first need a string that will return a json object (is that what I am expecting back?)
https address: https://spreadsheets.google.com/feeds/list/
Sheet ID :
Additional : /od6/private/full
Command : ?alt=json-in-script&callback=importGSS
or full string : https://spreadsheets.google.com/feeds/list//od6/private/full?alt=json-in-script&callback=importGSS
This seems to work quite fine, if I remove the json part it shows me the data sheet, if I ad it, I get an empty file instead.
So now to the code.
The function that SHOULD be returning the object is the following (spLink) contains the link above.
function loadData(spLink){
$.getJSON(spLink).always(function(data) {
console.log("Object created!");
console.log(data);
}).fail(function(message) {
console.error('Something went pretty wrong!');
console.error(message);
}).done(function(){
console.log('Done!');
});
}
The only thing I can really tell about it is that data continues returning null, and I can't really figure out where else the data may end up.
Have tried both with and without callback.
The list feed only works if there are no empty cells in a row with data, among other pitfalls.
Use the cell feed instead, which requires more code because you wont get the data organized by rows.
I searched around, and couldn't find an answer to my question. I'm very new at coding, and at work, we have an application that current names that are logged in, and what they are doing.
Recently, they have changed from jquery 1.4.1 to jquery 1.8.3. Ever since then, I cannot get the results to process correctly, because of the following error;
"Unable to get value of the property 'split': Object is null or undefined"
I have the code setup to grab the results and split them;
function processAgents(xData, status) {
var avail = xData.responseText.split("|")[0];
var acw = xData.responseText.split("|")[1];
var total = xData.responseText.split("|")[2];
var breaks = xData.responseText.split("|")[3];
var pending = xData.responseText.split("|")[4];
The application is setup to open as an HTA file which opens up the PHP script.
Any help would be appreciated, please let me know if I left anything out!
Thanks!
EDIT 1
I did some more investigating, and it looks like I'm not getting data from my process request. This is how it is currently setup
function updateAgents() {
var ts1 = new Date().getTime();
$.ajax({
url: "http://SERVER/AgentSrc.php?x=" + ts1,
complete: processAgents
I'm not sure if this is processing correctly since they went to jquery 1.8.3.
EDIT 2
So after looking into it more, it doesn't appear that the script is getting the data from the server, even though I have access. If I make a local file and put the information in it, it will pull the information and split it, but if I point to the path of the file on the server, it won't get the information. But the strange thing is, if I run it using jquery 1.4.1, it pulls the data fine, but can't display it. But with 1.8.3, it doesn't allow me to pull it from the server.
thanks again!
This will give some clarity
xData.responseText.toString().split("|")[0];
(split is part of string not jQuery)
Here is a possible explanation: in earlier versions of jQuery, ajax calls returned an xmlHttpRequest (XHR) object. Recent versions return a promise (jqXHR) instead.
See this page for more details.
The Program I'm writing and the functionality I'm trying to achieve
Okay. So what I'm writing at the moment is a very simple forum, in Javascript using AJAX. Part of my task is to add a new post, using an API that my lecturer wrote for us in PHP. Just to note, the API and the SQL database are completely local.
The function I am using to add this post is:
function addPosts()
{
// Add the new thread to the SQLlite database.
var treq = new Request({
url:'guestbook/control.php?action=insertPost',
'method':'post',
onSuccess: function() {
alert('win');
},
onFailure: function() {
alert('fail');
}
}).send(Object.toQueryString({
// Had to convert it to a query string because it wouldn't work as a normal object.
// These are the required values to send, to store a "post" in the database.
'name':'This is a name',
'comment':'This is a comment!'
}));
}
I am aware this will add the same data every single time. I'm just trying to get the damn thing working!
The problem
What is happening is, when this function is called, I am getting an SQL syntax error. I was confused, because that would imply that my lecturer's code is wrong. After speaking with my lecturer, he explained that this happens when the post data isn't sent correctly to the PHP code. So I went about using Google Chrome's developer tools to see what was going on, and this is what I discovered:
Now to me, this means that the data is successfully being loaded into the request, and is being passed to the PHP files fine. Obviously I'm wrong. I've been racking my brains trying to make this work.
I know that the API works fine, because everyone else in my class isn't having any problem with it, and the code I am using is practically a rip off of the code in the notes, so I'm about 90% sure that's correct to.
One thing to note is that the code in the onSuccess key runs, so I know it's not a problem on the AJAX side.
Another thing is that this code worked in University on those computers, and it's since I've got it home that it's decided not to work.
Stack Trace
Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[HY000]: General error: 1 near ")": syntax error' in G:\Ajax
Coursework\guestbook\php\database.php:134Stack trace:#0 G:\Ajax
Coursework\guestbook\php\database.php(134): PDO->prepare('INSERT INTO
pos...')#1 G:\Ajax Coursework\guestbook\php\class.GuestBook.php(44):
DatabaseHandler->insert(Array)#2 G:\Ajax
Coursework\guestbook\control.php(8): GuestBook->insert(Array)#3
G:\Ajax Coursework\guestbook\control.php(56): insertPost()#4 {main}
thrown in G:\Ajax Coursework\guestbook\php\database.php on line 134
Object.toQueryString is used in convert an object to a query string. So if the server is requiring both $_POST['name'] and $_POST['comment'] to be set, it wont be.
Frankly because you are posting it, I dont think $_GET['name'] or $_GET['comment'] would be set either.
Request.send expects an opject. You are sending it a string. So it should be
Request.send({prop: 'value'}), not Request.send(value).
Do yourself a favor and make a PHP with the following php code, and see what it returns. It may clear this up for you right away. I have a feeling nothing is being sent except for $_GET['action']
<?php
echo '<pre>';
print_r($_GET);
print_r($_POST);
echo '</pre>';
?>
Just in-case anyone stumbles upon this thread looking for an answer:
function addPosts()
{
// Add the new thread to the SQLlite database.
var treq = new Request({
url:'guestbook/control.php?action=insertPost',
onSuccess: function() {
alert('win');
},
onFailure: function() {
alert('fail');
}
}).post('name=This is a name&comment=This is a comment!');
}
Here I'm using the .post method to POST data.