Sending hidden form field to server on a Wordpress site - javascript

I am new to working with Wordpress and I'm using a JQuery plugin called textcomplete with Algolia search to allow users to # mention other users in the comment section of my site as shown in the code below.
$input.textcomplete([
{
match: /\B#(\w*)$/,
search: function(term, callback) {
lastQuery = term;
myIndex.search(term, { hitsPerPage: 5 }, function(err, content) {
if (err) {
throw err;
}
if (content.query === lastQuery) {
callback(content.hits);
}
});
},
template: function (hit) {
console.log(hit);
return hit._highlightResult.display_name.value;
},
replace: function (hit) {
return ' #' + hit.display_name + ' ';
},
index: 1
}
]);
I want to send my hit.display_name variable to the server to use as part of a MySQL query. Normally I would do this by making it a hidden form field and posting it to the php file where it is required (in this case wp-comments-post.php) but with the way comment forms are handled with Wordpress (using a comment_form function and passing it an associative array of objects) I am not sure how to do this...
So my question is how do I access this hit.display_name variable in my wp-comments-post.php file?

Related

Show NodeJS Errors in main html file itself

I made a form using NodeJs, i made some validations of input that show errors when user enter wrong values, the problem here is that the error appear on a new blank page but i need the error to appear on the main html file itself with cool styling
here's the live site http://mido.sundays.org.uk
I tried to make post request on the same route to see if the error will appear on the same page or not but the page turned to white blank page with the text inside
app.post('/', function (req, res) {
const SchemaValidation = {
name: joi.string().min(4).required().error(() => {
return {
message: 'Name is required. (min:4 chars)',
};
}),
email: joi.string().email().error(() => {
return {
message: 'Email field can\'t be Empty',
};
}),
phone: joi.string().min(8).max(14).required().error(() => {
return {
message: 'Valid Phone number is Required (min:8 characters - max: 14 characters)',
};
}),
university: joi.string().required().error(() => {
return {
message: 'University Field is Required',
};
}),
faculty: joi.string().required().error(() => {
return {
message: 'Faculty Field is Required',
};
}),
academicyear: joi.string().required().error(() => {
return {
message: 'Academic Year Field is Required and should range from 1-6',
};
}),
workshop: joi.array()
.items(joi.string().error(() => {
return {
message: 'You Should pickup 2 Committees',
};
})),
first_choice: joi.string().required().error(() => {
return {
message: 'You should pickup first choice',
};
}),
second_choice: joi.string().required().error(() => {
return {
message: 'You should pickup second choice',
};
}),
};
joi.validate(req.body,SchemaValidation,(err, result) => {
if(err) {
res.send(`<p style='color:red; text-align:center; margin-top:20px;'>${err.details[0].message}</p>`);
return; // don't try saving to db if the schema isnt valid
}
else
res.send(`<p style='color:green; text-align:center; margin-top:20px;'>Successfully Posted Data</p>`);
})
});
All what i need is to show the error in the same page and prevent the submit..
To solve this problem, I highly racommand you to use Pug.js (Template Engine), because you can't pass parameters into a specific page. By using a template engine, you can pass data as object, and render them with res.render('index', {error: res.error.message}).
You will be able to output into the page from server side the error object displaying whatever you needed to display!
res.send('content') basically it's a document.write()
https://pugjs.org/api/getting-started.html
Is there a reason you can't do the validation on the front end before submitting the form? That is usually the preferred way. You can have some backend validation so that you don't get bad data into your db but once you send a request you need to send a response back and in your case the response is the message not the entire HTML page. You can create a validation by adding an event listener to your submit button then using Ajax once you validate to send the data to the backend or you can use Bootstrap's built in validation and not mess with Ajax just through the form action. https://getbootstrap.com/docs/4.0/components/forms/#validation

How to properly create a custom field in salesforce using jsforce?

I am trying to create a customfield in jsforce and am having a heck of a time doing it. I can create a custom object fine, but when trying to make a field so the clients users to sort their leads by it is giving me a heckof a time. This is what I did to create a object
var jsforce = require('jsforce');
var conn = new jsforce.Connection();
conn.login('myemail', 'my password and token', function(err, res) {
if (err) { return console.error(err); }
var metadata = [{
fullName: 'TestObject1__c',
label: 'Test Object 1',
pluralLabel: 'Test Object 1',
nameField: {
type: 'Text',
label: 'Test Object Name'
},
deploymentStatus: 'Deployed',
sharingModel: 'ReadWrite'
}];
conn.metadata.create('CustomObject', metadata, function(err, results) {
if (err) { console.err(err); }
for (var i=0; i < results.length; i++) {
var result = results[i];
console.log('success ? : ' + result.success);
console.log('fullName : ' + result.fullName);
}
});
{
if (err) { return console.error(err); }
console.log(res);
}
})
That works fine but it is not what I need. Any help would be greatly appreciated as the client wants this out. It is part of a larger project that we have already completed but now the fields have to be dynamically created so the end users don't have to make the fields themselves in order for us to push the data to their account. We are currently pushing stuff but its under another field whose name doesn't make sense
I have been able to accomplish this by making a package in the salesforce website. All my clients users have to do is to click a simple link click install and it makes a list view and creates the fields i need.

Server side validation in Express compatible with a single page Angular application

I would like to perform server side validation, preferably with expressValidator. When saving a resource, I check to see if it is valid. If it's not valid what should I return?
There are examples:
http://blog.ijasoneverett.com/2013/04/form-validation-in-node-js-with-express-validator/
https://github.com/ctavan/express-validator
Unfortunately, I can't figure out my answer from that.
In Angular, I am using the $resource service. When I do a save, and there is a validation error, how should the server send this back? Note, this is a single page application.
Also, how should I handle this on the client side? Is this technically a success call?
Please, I am not looking for any instant, ajax, check per field solution. I want to submit save, if there is a problem, I would like to return the errors so that Angular can handle them. This does not need to be the perfect solution, just something to set me on the right track.
I am not handing the Angular code in an special way at the moment:
Controller:
$scope.saveTransaction = function (transaction) {
transactionData.saveTransaction(transaction);
}
Service
saveTransaction: function(transaction) {
return resource.save(transaction);
}
The server side code looks as follows:
app.post('/api/transactions', function (req, res) {
var transaction;
req.assert('amount', 'Enter an amount (numbers only with 2 decimal places, e.g. 25.50)').regex(/^\d+(\.\d{2})?$/);
var errors = req.validationErrors();
var mapped = req.validationErrors(true);
if (mapped) {console.log("MAPPED")};
//console.log(mapped);
if(!errors) {
console.log("Passed");
transaction = new TransactionModel({
date: req.body.date,
description: req.body.description,
amount: req.body.amount
});
transaction.save(function (err) {
if (!err) {
return console.log("created");
} else {
return console.log("err");
}
return res.send(transaction);
})
}
else {
console.log("Errors");
res.send(errors);
// res.render('Transaction', {
// title: 'Invalid Transaction',
// message: '',
// errors: errors
// });
}
});
You could send and handle "better" errors:
SERVER
res.json(500, errors)
CLIENT
resource.save(tran).then(function(){
//it worked
},
function(response) {
//it did not work...
//see response.data
});

How to implement Typeahead JS for Facebook Friends Search?

I have already seen this question. But that uses the old Bootstrap Typeahead and I'm now trying to use the Typeahead JS for autocomplete of Facebook friends. Well, what I'm trying to do is fetch the friends list from Facebook and use it to fill up input text fields. I'm fetching the facebook friends list using the following lines of code.
FB.login(function(response) {
if (response.authResponse) {
var uid = response.authResponse.userID;
access_token = response.authResponse.accessToken;
//alert('login success');
$.getJSON("https://graph.facebook.com/me/friends?access_token=" + access_token, function(result) {
var friends_list = result;
alert(friends_list.data[0].name);
});
} else {
//alert('not logged in');
location.reload();
}
});
This code is in the login page (/). This works perfectly and alert function displays the name correctly. After this, I want it to use with Typeahead JS for which I need to give the JSON Prefetch URL. The console shows 403 error when I try to use the same URL with Typeahead JS that is in another page /login/landing.
I tried to use it in Typeahead JS like this :
$(document).ready(function() {
$('.example-countries .typeahead').typeahead({
name: 'jsonvar_string',
prefetch: "'https://graph.facebook.com/me/friends?access_token='+access_token",
template: ['<p class="repo-language">{{data{{name}}}}</p>', '<p class="repo-name">{{data{{id}}}}</p>'].join(''),
engine: Hogan
});
});
It didn't work. So, I tried to parse the Javascript variable to get just the friends' name alone and use the JSON object as 'local' parameter in Typeahead like this:
FB.login(function(response) {
if (response.authResponse) {
//alert('Hi there');
var uid = response.authResponse.userID;
access_token = response.authResponse.accessToken;
alert('login success');
$.getJSON("https://graph.facebook.com/me/friends?access_token=" + access_token, function(result) {
var friends_list = result;
var friends_list_length = Object.keys(friends_list.data).length;
var jsonvar = [];
for (var i = 0; i < friends_list_length; i++) {
jsonvar.push(friends_list.data[i].name);
}
jsonvar_string = JSON.stringify(jsonvar);
localStorage.jsonvalue = jsonvar_string;
window.location.href = "/login/landing";
});
} else {
alert('not logged in');
location.reload();
}
});
Even that didn't work. My Facebook's API call returns JSON like this:
{
"data": [
{
"name": "ABCD",
"id": "1234455"
},
{
"name": "PQRSTV",
"id": "789456"
},
{
"name": "LKJHMN",
"id": "456789"
}
],
"paging": {
"next": "https://graph.facebook.com/12343434/friends?access_token=CAAJVBDOfUeQBAadfASDFdfdkdERdfdg8pVgJCMbSwIkWyQ0tIjNwoPPIjni7JeMyMbkeTNmxsKRiUe3q0h74Ngl3Ylue2Oz0XlepxUgZBoASpkSted2WV414ziawNZAHW68vLgCArRyxC8vNPeVmoZAueqnL1COrdSvkSItkVXbYVbueUZAhyBwZDZD&limit=5000&offset=5000&__after_id=100006343431073"
}
}
Anyway to parse the JSON that I'm receiving to use that directly in Typeahead JS or any other way to implement it?
you must convert the name key to value ou tokens. Typeahead.js just recognizes to autocomplete what is written in these keys.
i had the same problem with Twitter API. it may be helpful: how to integrate typeahead.js with twitter api

Using Facebook request dialog with Meteor

I'm trying to send an "app" invite to user friends using the Facebook JavaScript SDK.
Here is a template event when click the Facebook button:
"click #fb": function (e, tmp) {
Meteor.loginWithFacebook({
requestPermissions: ['user_likes',
'friends_about_me',
'user_birthday',
'email',
'user_location',
'user_work_history',
'read_friendlists',
'friends_groups',
'user_groups']
}, function (err) {
if (err) {
console.log("error when login with facebook " + err);
} else {
FB.api('/' + Meteor.user().services.facebook.id + '/friends', { fields: 'name,picture' }, function (response) {
if (response && response.data) {
friends = response.data;
friends_dep.changed();
}
});
}
});
}
after that i want the user to invite people to my app, my code looks like this (another template event):
FB.ui({method: 'apprequests',
message: 'My Great Request'
}, function(response) {
if (response && response.post_id) {
alert('Post was published.');
} else {
alert('Post was not published.');
}
}
);
And it's working. There is a Facebook dialog with all the user friends, but when trying to send the message, I get the response error = 'Post was not published.'
What am I doing wrong here?
Basically the user can build a group - and I want the user to be able to invite his facebook friends into that group. Is there anyway that when sending the request the reciver will just press "yes" and will be automatically added to the sender group?
note I'm using my local machine aka localhost:3000
Can you try removing the && response.post_id portion from the if statement?
According to the Facebook API docs for the Requests Dialog: https://developers.facebook.com/docs/reference/dialogs/requests/ the response will just have 'request' and 'to' data. It looks like you've copy and pasted your callback from an example they give for the Posts Dialog. If you still get an error after removing this then you aren't getting a response, I am unsure how the JS SDK handles responses. If you can get other API calls to work using js sdk then I'm really not sure.
I recently worked with the Facebook API and opted not to use the JS SDK because it seemed to be at odds with using the accounts-facebook package. I'm curious if you're using that too.
Some Facebook API calls like creating a Post (and possibly this one) do require a dialog box, I'll outline how I got around this without using the JS SDK in case it helps you or anyone else. I would just form the URL client side and open a popup window e.g. here's how I handled sending a post:
'click .send-message': function() {
var recipient = this.facebook_id;
var config = Accounts.loginServiceConfiguration.findOne({service: 'facebook'});
var url = "http://www.facebook.com/dialog/feed?app_id=" + config.appId +
"&display=popup&to=" + recipient + "&redirect_uri=" + Meteor.absoluteUrl('_fb?close');
window.open(url, "Create Post", "height=240,width=450,left=100,top=100");
}
Then to get the response server side:
WebApp.connectHandlers
.use(connect.query())
.use(function(req, res, next) {
if(typeof(Fiber)=="undefined") Fiber = Npm.require('fibers');
Fiber(function() {
try {
var barePath = req.url.substring(0, req.url.indexOf('?'));
var splitPath = barePath.split('/');
if (splitPath[1] !== '_fb') {
return next();
}
if (req.query.post_id) {
//process it here
}
res.writeHead(200, {'Content-Type': 'text/html'});
var content = '<html><head><script>window.close()</script></head></html>';
res.end(content, 'utf-8');
} catch (err) {
}
}).run();
});
This code is very similar to the code used in the oauth packages when opening the login popup and listening out for responses.

Categories

Resources