I have written a nodejs plugin in C++ and I am trying to call it from within a locally hosted webpage with jQuery. I have read that I can't make a direct call to nodejs because of the same origin policy so I should use jsonp. Note: I am pretty new to jquery, nodejs and json(p), but I am feeling adventurous. I am now using the following code:
node_test.js:
var mylib = require("./mylibrary");
var http = require("http");
http.createServer(function(req, res) {
console.log("Received request: " + JSON.stringify(req.url));
res.writeHead(200, {"Content-type": "text/plain"});
res.end('_testcb(\'{"message": "' + mylib.my_awesome_function() + '"}\')');
}).listen(1337);
index.html:
index.html:
<DOCTYPE HTML>
<html>
<head>
<title>
NodeJS test
</title>
<link rel='stylesheet' type='text/css' href='style.css'/>
<script type='text/javascript' src='jquery.js'></script>
</head>
<body>
<div id="test"></div>
<script>
$(document).ready(function() {
$.ajax({
url: "http://127.0.0.1:1337/",
dataType: "jsonp",
jsonpCallback: "_testcb",
cache: false,
data: "test_data",
timeout: 5000,
success: function(data) {
$("#test").append(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error ' + textStatus + " " + errorThrown);
}
});
});
</script>
</body>
</html>
If I run node node_test.js and view index.html in my browser my function gets called. However, I would like to be able to execute multiple functions from my own nodejs library. I thought of somehow parsing the data I send to my nodejs app, and run it through a big switch case, a bit like this:
var reply = "";
switch (data) {
case 1:
reply = mylib.my_awesome_function();
break;
case 2:
reply = mylib.my_cool_function();
break;
// repeat for every function I have
}
// send reply
But I am not sure if this is the intended way to do this. Is there a better/smarter way to make multiple calls to nodejs from within jQuery/javascript on a webpage?
Related
I have an ajax get request that has a data of an input. I want to pass this data into a variable and use it in my query.
index.handlebars
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input type="hidden" class="test" name="test" value="sample"/>
<script type="text/javascript">
$( document ).ready(function() {
var username = $('.test').val();
$.ajax({
type : 'GET',
url: '/users//welcome',
data : {
wew: username
}
});
alert(username); //correct output
});
</script>
</body>
</html>
and in my users/welcome
router.get('/welcome', ensureAuthenticated, function(req, res){
var test = req.query.wew; //data from ajax request
Item.find({username: test},function(err, docs, test){
//where username is the data
console.log(test);
res.render('welcome', {docs:docs});
});
});
This code is not working. Please help :/
You could use socket.io. I use it for bi-directional communication between the browser and node.js server.
On the client side you would do:
function movePlayer () {
socket.emit ('doSomethingServerSide', {numVal: 4, usrName: 'KaiserSolze'});
}
And server side you would have:
// A FUNCTION THAT LISTENS FOR A CALL FROM BROWSERS CONNECTED VIA SOCKET
socket.on ('doSomethingServerSide', function (msg) {
// THEN YOU COULD REPORT TO ALL BROWSERS / CLIENTS THAT SOMETHING WAS DONE
io.sockets.emit ('reportToClients', msg);
});
If you decide to go this route there are lots of posts here to help you get started with socket.io.
Try giving your website full URL with http and replace double (//) with one
$.ajax({
type : 'GET',
url: 'http://<your application full url>/users/welcome',
data : {
wew: username
}
});
Or you can try below
$.ajax({
url: "/users/welcome?wew="+username,
type: "GET",
contentType: "application/json",
dataType: "json",
});
var test = req.query.wew; //data from ajax request
Just change to this one with this one:
var test = req.body.wew
Also you need to import body parser to your project for getting req.body.keynames
I'm trying to get json data from the Bing Search API.
What I have done is this
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script language="JavaScript" type="text/javascript" src="jquery-1.12.3.js"></script>
<script>
$(document).ready(function() {
var appId = ':mykey';
function getNews() {
//console.log("DF");
var azureKey = btoa(appId);
var myUrl = 'https://api.datamarket.azure.com/Bing/Search/v1/News?Query=%27britain%27&$format=json';
$.ajax({
method: 'post',
url: myUrl,
dataType:"jsonp"
//Set headers to authorize search with Bing
headers:{'Authorization':'Basic ' + azureKey }
}
success: function(data) {
console.log("DF");
//console.log(data);
var json = data.d.results[1].Url;
document.getElementById("demo").innerHTML = json;
},
error: function(jqXHR, error, textStatus) { console.error(jqXHR, error, textStatus); }
});
};
getNews();
});
</script>
</body>
</html>
When I try to run this, the following error comes in the console:
Uncaught SyntaxError: Unexpected identifier
for the line
headers:{'Authorization':'Basic ' + azureKey }
I have the following doubts:
Whether I am doing the jsonp thing right?
Whether I am correct in including two scripts:
language="JavaScript" type="text/javascript" src="jquery-1.12.3.js"> and the main script.
And of course, why the error.
The syntax error is a missing comma
dataType:"jsonp",
// ^
You also have an extra } after the headers object, which will be another syntax error, change that to a comma.
headers:{'Authorization':'Basic ' + azureKey }
,
// ^ comma not a }
You won't be able to use the authorization header with JSONP, it is not possible. If the service supports CORS (which it looks like it does) then you can use a normal XHR by setting the dataType to json.
This question is a followup on this question and this one. I am unable to send form field values through jquery's ajax api. The code is as follows:
index.html
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<link rel="stylesheet" type="text/css" href="index.css">
<script src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script type="text/javascript" src="index.js"></script>
</head>
<body onload="welcome()">
<div class id="main"></div>
</body>
</html>
The welcome function is implemented in index.js:
index.js
function welcome()
{
view_account();
}
function get_form_data_with_token($form){
var unindexed_array = $form.serializeArray();
var indexed_array = {};
$.map(unindexed_array, function(n, i){
indexed_array[n['name']] = n['value'];
});
indexed_array['token'] = 'adafdafdgfdag';
return indexed_array;
}
$(document).ready(function(){
$("#changepassword_form_id").submit(function(e){
var uri, method, formId, $form, form_data;
// Prevent default jquery submit
e.preventDefault();
e.stopImmediatePropagation();
uri = location.protocol + '//' + location.host + "/change_password";
method = "POST";
formId = "#changepassword_form_id";
$form = $(formId);
form_data = get_form_data_with_token($form);
alert("form_data: token = " + form_data['token'] + " password3 = " + form_data['l_password3'] + " password4 = " + form_data['l_password4']);
// Set-up ajax call
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
cache: false,
// Setting async to false to give enough time to initialize the local storage with the "token" key
async: false,
dataType: "json",
data: form_data
};
// Make the request
$.ajax(request).done(function(data) { // Handle the response
// Attributes are retrieved as object.attribute_name
console.log("Data from change password from server: " + data);
alert(data.message);
}).fail(function(jqXHR, textStatus, errorThrown) { // Handle failure
console.log(JSON.stringify(jqXHR));
console.log("AJAX error on changing password: " + textStatus + ' : ' + errorThrown);
}
);
});
});
function view_account()
{
var changePassword;
changePassword = "<form action=\"/change_password\" id=\"changepassword_form_id\" method=\"post\">";
changePassword = changePassword + "<br><label>Old Password: </label><input id=\"password3\" type=\"password\" name=\"l_password3\" required><br>";
changePassword = changePassword + "<br><label>New Password: </label><input id=\"password4\" type=\"password\" name=\"l_password4\" required><br><br>";
changePassword = changePassword + "<input type=\"submit\" value=\"Change Password\">";
changePassword = changePassword + "</form>";
// Replace the original html
document.getElementById("main").innerHTML = changePassword;
}
The onsubmit handler is not executed even though the dom ready event is used as mentioned in this question.
How can I submit the fields only once using the ajax api from jquery?
Edit:
jsfiddle example from a previous question. Even though the code runs on jsfiddle it fails when run in fire fox.
Use the on event handler like this:
$(document).on("submit","#changepassword_form_id",function(e){
...code here...
});
This delegates it, since #changepassword_form_id isn't yet defined on document.ready.
Since, you are using required property on inputs and need to check for filled forms, you can use submit event.
You are clearly appending the html dom before the div has even loaded..
Heres a step by step breakup of the flow...
You are loading the .js file inside the <head>.
You are calling the function inside the file which has the following line, document.getElementById("main").innerHTML = changePassword; But, but there is nothing with the id "main" yet!!!
Then the <body> is being loaded, inside which the div with the id "main" is present.
You see the logic?? right??
Not to be nosy, but this problem is the outcome of the wrong design of your code, fixing it with any workaround is only going to cause you further headaches, so I strongly recommend that you update the code design, unless you have really little control over the code, in which case the patch work is your only option.
And if you are going by the patchwork, you can always use the .off.on event delegation which removes the possibilities of event duplication on code rerun.
I've been trying to create a small page and all it does is update some values from a source document. The page loads fine, but I don't get the results from the requested source. The .fail function runs, but the textStatus and errorThrown values don't appear in the alert() window that pops up.
I'm very new to javascript and jquery. I'm trying to bash this together with pieces found from the web to figure it out but nothing seems to be working. Mainly, it's the response I think I'm falling down on...
Anyway, here's the code:
<html>
<head>
<title></title>
<script type="text/javascript" src="~/Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript">
function update() {
$.ajax({
type: "GET",
url: "http://192.168.2.86:15890/linearlist.xml",
dataType: "xml"
}).done(function (res) {
//alert(res);
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("AJAX call failed: " + textStatus + ", " + errorThrown);
});
}
function GetData() {
update();
setTimeout(function () {
GetData();
}, 50);
}
});
</script>
</head>
<body>
<script type="text/javascript">
GetData();
</script>
<div class="result"> result div</div>
</body>
</html>
UPDATE:
I've update my code re: #Ian's answer. It's still not working, sadly. I'm not getting the textStatus or errorThrown results either. I've tried debugging with Internet Explorer through VS2012 but it's not getting me far. If I put the URL into a webpage, I can view the XML document.
$.get does not accept one parameter as an object literal; it accepts several: http://api.jquery.com/jQuery.get/#jQuery-get1
You might be thinking of the $.ajax syntax: http://api.jquery.com/jQuery.ajax/
Anyways, call it like:
$.get("http://192.168.2.86:15890//onair.status.xml", {}, function (res) {
var xml;
var tmp;
if (typeof res == "string") {
tmp = "<root>" + res + "</root>";
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(res);
} else {
xml = res;
}
alert("Success!");
}, "text");
Or use $.ajax:
$.ajax({
type: "GET",
url: "http://192.168.2.86:15890//onair.status.xml",
dataType: "text"
}).done(function (res) {
// Your `success` code
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("AJAX call failed: " + textStatus + ", " + errorThrown);
});
Using the fail method, you can see that an error occurred and some details why.
Depending on what/where http://192.168.2.86:15890 is, you may not be able to make AJAX calls due to the same origin policy - https://developer.mozilla.org/en-US/docs/JavaScript/Same_origin_policy_for_JavaScript
I know you have some logic in your success callback, but I'm pretty sure if you specify the dataType as "text", the res variable will always be a string. So your if/else shouldn't really do much - the else should never execute. Either way, if you're expecting XML, it's probably easier to just specify the dataType as "xml".
We have a website that is protected by Basic Authentication and has a particular javascript file underneath it.
I want to load that javascript file from a different MVC3 site by putting details on the authentication header when loading the file and here's what I'm trying that doesn't seem to work - it's always popping up the basic authentication login dialog:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<title>Auth test</title>
</head>
<body>
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/Base64.js"></script>
<h2>Index</h2>
<script type="text/javascript">
$(document).ready(function () {
var auth = make_base_auth('domain\user', 'password');
$.ajaxSetup({
headers: {
'Authorization': auth
}
});
$.ajax({
url: 'https://localhost/WebClient/scripts/bob.js',
dataType: 'script',
//username: 'domain\user',
//password: 'password',
//withCredentials: true,
//crossDomain: true,
//headers: { 'Authorization': auth },
success: function (data) {
alert("Got the script!");
callFunctionInTheOtherJSFile();
},
async: false
});
});
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
</script>
</body>
</html>
Any ideas what I should do to get the the code to work?
As you'll see from the various commented out parts - I've tried a few different ways (newer and older jQuery methods etc)!
For reference, the Base64 JS is taken from here - http://www.webtoolkit.info/javascript-base64.html as described here - http://coderseye.com/2007/how-to-do-http-basic-auth-in-ajax.html
Have you tried the standard http://user:pass#hostname/ syntax ?