Processing variables send with nodejs inside jade - javascript

I have a script sending a matrix, something like [[1,2,3,4], [7,6,5,4], [2,3,4,5]]. When I send it using res.send(JSON.stringify(dataArray)); and display it in jade using h1#results I do indeed see the format is correct.
However I would like to use this data inside the google charts. My intuition would say to present the data like this: data.addRows = results;. This is however not the case because jade doesn't understand that I mean the variable send.
I suspect I do not understand some basic principle behind jade. I understand that most of jade/html is fixed and that only code within "script" tags get executed but as far as I can see all code inside google's function drawChart() {) is within a script tag.
EDIT
My new ajax script:
$(function() {
$('#search').on('keyup', function(e){
if(e.keyCode === 13) {
var parameters = { search: $(this).val()};
$.get('/seraching', parameters, function(data) {
$('#results').html(data);
console.log('parsing json');
var chartData = (data);
console.log(chartData[0])
drawChart(chartData, parameters.search);
});
}
});
});

So, there several issues at play here. First, using Express and Jade to deliver a processed template, using AJAX with a search parameter to get some data, and using an Express route to send some data based on the search parameter you send it.
Initially you want Express and Jade to set up the main page:
main.jade
html
head
script(src='googlechart.js')
script(src='myJS.js')
body
title Title
h1 Heading
input("type='text', id='search'")
button("id='submit'")
So here we ensure that Google chart is loaded as well as the JS that will contain your AJAX call. I've also included the text box for the search parameter.
In your Express app you would render the page like this:
app.get('/', function (req, res) {
res.render("main.jade");
});
myJS.js
First set up the chart object. Then, when the submit button is clicked, use the value of the search field in the ajax data property. Once the promise is resolved, display the results.
var chart = new google.visualization.DataTable();
$('#submit').click(function () {
var param = $('#search').val();
$.ajax({
url: '/getdata',
dataType: 'JSON',
data: { search: param }
}).done(function (data) {
// note that jQuery automatically parses JSON for you
chart.addRows(data);
});
});
But! In order to do this you need to set up a route in Express to handle the AJAX call which would look like:
app.get('/getdata', function (req, res) {
var param = req.param('search');
// filter data by search param
res.send(JSON.stringify(data));
});
So, you only need Jade once to set up the main template. It's the Express routes that you need to deliver the JSON data when you submit an AJAX request.
Hope that's a better answer :) Oh, there might be a couple of typos in here because I've not used Express for a while, but I'm pretty sure it's correct.

Related

jQuery on click not working with express to load a handlebars page

jQuery on click function not working to work with express to route to a handlebars page to display passed information.
I've tried changing the get to post. Not using handlebars and just having in html file and using path.sendFile or chaning res.render to be res.send
Heres the on click function
$("#song").on("click", function(){
var songArtist = $(this).text();
$.get("/results/:" + songArtist);
});
Heres the express route
app.get("/results/:songArtist", function(req, res) {
res.render("songResult");
//res.sendFile(path.join(__dirname + "./../views/result.html"));
});
I expect that when the divs with the song id is clicked to load to a new page.
Get rid of the : in the $.get() in the front-end JS. The : is only used on the back-end to represent variable URL parameters.
So on the back-end, when you listen for get requests at "/results/:songArtist", whatever comes after "/results/" will now be referred to in the function as req.params.songArtist.
For example, if I send a get request to "/results/pinkfloyd", inside the listener function you provided above, req.params.songArtist === pinkfloyd.

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.

Add a HTML Page To WordPress Site Using Javascript

I'm creating a plugin that will add a custom page to the website (with no template).
I'm struggling to work out how talk to WordPress from inside the Jquery part of my plugin.
At present, there is a variable called res that contains all the HTML for the page.
$.post( templateUrl + "templates/template2.html", function( data ) {
tinyMCE.triggerSave();
var res = data.replace("[([PREHEADER])]", $("#peg-newsletter-preheader").val())
res = res.replace("[([HEADING])]", $("#peg-newsletter-heading").val());
});
Any help is appreciated.
Thanks.
You are using post incorrectly.
This section of the function
function( data ) {
tinyMCE.triggerSave();
var res = data.replace("[([PREHEADER])]", $("#peg-newsletter-preheader").val())
res = res.replace("[([HEADING])]", $("#peg-newsletter-heading").val());
})
is a call back (meaning this is a response you get from WP after you make a successful post). Changing values here only changes the values that you receive rather than wp.
To 'talk' to wp you need to post the data in the body: http://api.jquery.com/jquery.post/
So your jquery post will look like this:
$.post( templateUrl + "templates/template2.html",
{ preHeader: "something", Header: "something" },
function( data ) {
alert("Post successful");
});
However this would assume that your end point allow for a post request to do what you want.
I am not sure what you are trying to achieve though. It looks like you want to change the HTML template of WP? If so I don't know of any rest api that would allow you to do that, as these api's are primarily for pulling WP Posts/Blog data from WP. HTH

Updating page through ajax and url without reloading the page (node.js)

What would be the correct way to make the inventory update without refreshing the page and accessible through both the button event and url. So that when url param id is based to the route it will update it to the specific page. Like a products page on a shopping site. Below works through the ajax request but not through the url (inventory/2) it just takes me to the posted data and not with the rendered view. I require it to be able to go to a specific page by the url so I can link to it. It also needs to be able to fall back to just standard page loading when javascript is not enabled.
View (inventory)
extends layout
block content
div.row
div.col-md-offset-2.col-md-8#inventory
a(class='btn', href='#') Get More!
script.
$(function(){
$("a.btn").on("click", function(e) {
e.preventDefault();
$.get( '/inventory/2', function(data) {
$('#inventory').html(data);
});
});
});
Routes
router.get('/inventory/:id?', function (req, res) {
if(req.params.id){
var id = req.params.id;
var data = "Updated and now on page " + id
res.send(data);
}else{
res.render('inventory');
}
});
Would recommend to have two separate sets of paths: one for the human users and one for the scripts (API). In your routes file above, you mix the two - res.send(data) is intended for the AJAX script, and res.render('inventory') for direct display in the browser in response to the user's request - that is, basically, why you don't get the result you expected.
Please see a below a simple example how the app files can be structured (extend it as you see reasonable):
View:
extends layout
block content
div.row
div.col-md-offset-2.col-md-8#inventory
= content
a(class='btn', href='#') Get More!
script.
$(function(){
$("a.btn").on("click", function(e) {
e.preventDefault();
$.get( '/api/inventory/2', function(data) {
$('#inventory').html(data);
});
});
});
Routes:
var getData = function(id) {
return "Updated and now on page " + id;
}
router.get('/api/inventory/:id', function (req, res) {
res.send(getData(req.params.id);
}
router.get('/inventory/:id?', function (req, res) {
var data;
if (req.params.id) {
data = getData(req.params.id);
} else {
data = null;
}
res.render('inventory', {content: data});
});
(note: you may have to use != content instead of = content in the Jade template if your data contains HTML.)
Now, the user can access different states of the page via urls /inventory and /inventory/2, while the AJAX call will be done using a third url, /api/inventory/2.
On top of that, you can dynamically update the url field in the user's browser as may be needed - see the answers to this question for more details.

How to get data returned from Ajax appended to a div? -- JQuery + Rails 3.1

I'm trying to get data returned from a controller and append it to a div. Here is the code I have:
$(this).parent().find('list').append(__WHAT_GOES_HERE?__);
How should I get data to append using ajax in JQuery? I know this is a very basic question -- I'm new to JS :(
PS. Lets assume the controller's path is /ajax_get_items
I assume you want to load it into a class, so list would be .list
Something like:
$.ajax({
url: "/ajax_get_items",
type : "POST",
data : { // If you need data to be posted
id : 12,
num : "test"
},
success : function(result){
$(this).parent().find('.list').append(result);
// If a JSON object is returned, use the following line:
// $(this).parent().find('.list').append(result.html);
}
})
Or if you want to just load data without params (GET method):
$(this).parent().find('.list').load("/ajax_get_items");
If you want more information about ruby rails and jQuery: http://brandonaaron.net/blog/2009/02/24/jquery-rails-and-ajax
This is what you need:
$.ajax({
url: '/ajax_get_items',
success: function(data) {
$('#selector').parent().find('list').append(data)
}
});
Note that you can't use 'this' in this context depending on where this call is made, or you might end up with unexpected results
$('somelink').click(function(e) {
e.preventDefault();
$.ajax(url, data, success:function(resData) {
resultSet = resData.extract(resData);
}
}
Basically this part handles the response from the ajax call and extract is supposed to build up your required html from the returned data.
After this you can simply say
$(this).parent().find('list').append(resultSet);
But this assumes the major work is done in the function extract with the returned data.
There you build up your list (or whatever) html is needed.

Categories