Pass ajax value to a variable in node.js server - javascript

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

Related

Not getting a response for an AJAX call to PHP (with JSON data)

I have a PHP running on a server, and i call to it via jQuery.Ajax() but it always return to the error portion of it.
If i call the PHP address directly from my browser, i get the response i need, it only breaks in the jQuery call.
The PHP (simply saying) is this:
<?php
if(isset($_GET['getcodenode']))
{
echo json_encode
(
array
(
'itens'=>
array
(
0=>array('id'=>100,'lb'=>'300','ds'=>'300 mm'),
1=>array('id'=>105,'lb'=>'400','ds'=>'400 mm')
)
)
);
die();
}
?>
And on the javascript side i call for it like this:
<html>
<head>
<script type="text/javascript">
function loadcall(data)
{
jQuery.ajax({
async:false,
method:'POST',
crossDomain:true,
dataType:'jsonp',
url:'http://example.com/ajax.php?getcodenode',
data:{'arg':data},
success:function(result){
var ret=JSON.parse(result);
var el=jQuery('#abc');
for(en in ret.itens)
{
el.Append('<div id="item_'+en.id+'">'+en.lb+', '+en.ds+'</div>');
}
},
error:function(result){alert('Error (loadcall)');}
});
}
</script>
</head>
<body>
<div id="abc"></div>
</body>
</html>
How to read JSON objects from PHP and display in browser?
There are lots of comments on your code:
While you already getting a json return from server; you don't to parse that. Its already a json object.
You can set async:true to get a promise data
The way you loop through objects you need to do that properly. see image how to get the object path correctly.
You can use $ token instead of jQuery token; unless you purposely need that.
I am not sure if this is the best approach; but it give the needed result as explained in your question.
The code is bellow tested with some comments:
<script type="text/javascript">
loadcall("test");
// as pointed you need to call the function so it runs
function loadcall(data) {
$.ajax({
async: true,
method: 'POST',
crossDomain: true,
dataType: 'json', //your data type should be JSON not JSONP
url: 'page.php?getcodenode',
data: {
'arg': data
},
success: function(result) {
console.log(result);
// see attached image how to get the path for object
var ret = result;
var el = $('#abc');
for (en in ret.itens) {
console.log(ret.itens[en].ds);
el.append('<div id="item_' + ret.itens[en].id +
'">' + ret.itens[en].lb + ', ' + ret.itens[en].ds + '</div>');
}
},
error: function(result) {
console.log(result);
}
});
}
</script>
Open you developer tool in your browser hit F12 (In Chrome, Firefox or Edge):
Go to Console tab and find the results.
Expand the results tell you get to the object you need.
Right click and `copy property path'.
Use the object path as needed in your code.
you need to call loadcall(data)
<html>
<head>
<script type="text/javascript">
function loadcall(data)
{
jQuery.ajax({
async:false,
method:'POST',
crossDomain:true,
dataType:'jsonp',
url:'http://example.com/ajax.php?getcodenode',
data:{'arg':data},
success:function(result){
var ret=JSON.parse(result);
var el=jQuery('#abc');
for(en in ret.itens)
{
el.Append('<div id="item_'+en.id+'">'+en.lb+', '+en.ds+'</div>');
}
},
error:function(result){alert('Error (loadcall)');}
});
}
loadcall('somethingData')
</script>
</head>
<body>
<div id="abc"></div>
</body>
</html>

Different response in my browser vs the API Testing Console

I am currently new in Cognitive services. Yesterday I tried Computer vision API where I got different JSON response for the same image in the API Testing console to that when I used the javascript code in my browser. I have enclosed my javascript code and the screenshot of the two different responses.
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
var myKey = "my key";
var myBody = {url:"http://activeforlife.com/wp/wp-content/uploads/2015/05/co-ed-kids-playing-soccer.jpg"}
$(function() {
var params = {
// Request parameters
"maxCandidates": "1",
};
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", myKey);
},
type: "POST",
// Request body
data: JSON.stringify(myBody),
})
.done(function(data) {
document.getElementById("ans").innerHTML = JSON.stringify(data);
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
<h4 id="ans"></h4>
</body>
</html>
Screenshot for the different outputs
The Cognitive Service Vision API will perform different visual classifications depending on the visualFeatures query parameter. You can find more details here.
If you don't specify any features, you are performing the equivalent of visualFeatures=Categories (your example). The console appears to have been executed with visualFeatures=Description. You can set the feature list in your param object.

Adding additional information to Simple Jquery FileUpload

I'm trying to integrate juqery fileupload with an ajax form submit. The ajax form sends the text and returns the ID of the newly created event, This is necessary to know which event to link with when uploading.
The simple upload demo uses the following code
Here's the ajax that first upload the non-file fields
$.ajax({
type: 'post',
url: '/whats-on/upload-event/',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (return_data) {
console.log(return_data)
}
});
It returns the following json
Object {status: true, id: 17162}
However the fileupload sends the files without declaring data: data,
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>jQuery File Upload Example</title>
</head>
<body>
<input id="fileupload" type="file" data-url="server/php/">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="js/vendor/jquery.ui.widget.js"></script>
<script src="js/jquery.iframe-transport.js"></script>
<script src="js/jquery.fileupload.js"></script>
<script>
$(function () {
$('#fileupload').fileupload({
dataType: 'json',
done: function (e, data) {
//Returns ID as e['id'] and 200 status also with e['status']
}
});
});
</script>
</body>
</html>
You first need to get the event Id with an ajax post:
function uploadClick(){
var eventId = getEvent();
uploadFile(eventId)
}
function getEvent(){
// make an ajax and return your id
}
One you got it, then create an URL with a query string indicating the eventId. this URL is where you want to post your file:
function uploadFile(eventId){
// attatch the id to the URL with query string
url = url + '&eventId=' + eventId;
// submit here your file
}
This way you can post in the same ajax call the file itself and the event id. In you server side action you need to get this query string and then pick the posted file.
You may have to handle callbacks for fileupload plugin like:
$('#fileupload').fileupload({
url: <url>,
type: <HTTP_VERB>,
other configurations...
}).bind('fileuploadadd', function (e, data) {
//fires when you select a file to upload
}).bind('fileuploaddone', function (e, data) {
//fires when upload completed successfully. equivalent to done call back of jQuery ajax
}).bind('fileuploadfail', function (e, data) {
//fires when upload fails
});
For complete reference please take a look at the following link .

Jquery ajax with google app engine post method

Just trying to learn using ajax with appengine,started with the post method,but it does not work.
This is my HTML Code for the page
<html>
<head>
<title> Hello </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
var data={"name":"Hola"};
$(document).ready(function(){
$('#subbut').click(function(){
$.ajax({
url: '/test',
type: 'POST',
data: data,
success: function(data,status){
alert("Data" + data +"status"+status);
}
});
});
});
</script>
</head>
<body>
<form method="post" action="/test">
<input type="submit" id="subbut">
</form>
<div id="success"> </div>
</body>
</html>
Here goes my python code to render the above html code , its handler is /test1
from main import *
class TestH1(Handler):
def get(self):
self.render('tester.html')
And this is the python script to which AJAX request must be sent to,handler is /test.
from main import *
import json
class TestH(Handler):
def post(self):
t=self.request.get('name')
output={'name':t+" duck"}
output=json.dumps(output)
self.response.out.write(output)
Expected behavior is that when i click on submit button,i get an alert message saying "Hola duck" , get nothing instead.
Any help would be appreciated as i am just starting with AJAX and Jquery withGAE
At first, I suppose you should suppress default behavior of form submitting when you press submit button by adding "return false" to the .click function. But I suppose it would be better to use just
<input type="button" id="subbut">
instead (even without form).
Then you should add "dataType: 'json'" to your ajax call to tell jQuery what type of data you expect from server. Doing this you will be able to get response data by property names like "data.name". So:
var data={"name":"Hola"};
$(document).ready(function(){
$('#subbut').click(function(){
$.ajax({
url: '/test',
type: 'POST',
data: data,
dataType: 'json',
success: function(data,status){
alert(data.name);
alert("Data" + data +"status"+status);
}
});
return false;
});
});
and it would be better if you set appropriate content type header to your response:
response.headers = {'Content-Type': 'application/json; charset=utf-8'}
self.response.out.write(output)

Using javascript to access Google's URL shortener APIs in a Google Chrome extension

I am writing my first google chrome extension which will use Google's URL shortener api to shorten the URL of the currently active tab in Chrome.
I am a longtime sw developer (asm/C++) but totally new to this "webby" stuff. :)
I can't seem to figure out how to make (and then process) the http POST request using js or jquery. I think I just don't understand the POST mechanism outside of the curl example.
My javascript file currently looks like this:
chrome.browserAction.onClicked.addListener(function(tab) {
console.log('chrome.browserAction.onClicked.addListener');
chrome.tabs.getSelected(null, function(tab) {
var tablink = tab.url;
console.log(tablink);
//TODO send http post request in the form
// POST https://www.googleapis.com/urlshortener/v1/url
// Content-Type: application/json
// {"longUrl": "http://www.google.com/"}
});
});
The easiest solution would be to use jquery's $.ajax function. This will allow you to asynchronously send the content to google. When the data comes back you can then continue to process the response.
The code will look something like this question
$.ajax({
url: 'https://www.googleapis.com/urlshortener/v1/url?shortUrl=http://goo.gl/fbsS&key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHXV7Mjw',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{ longUrl: "' + longURL +'"}',
dataType: 'json',
success: function(response) {
var result = JSON.parse(response); // Evaluate the J-Son response object.
}
});
Here is the jquery ajax api
Update in Jan, 2016: This no longer works, as the link shortening API requires authentication now.
I wrote a blog post with a simple solution:
http://uihacker.blogspot.com/2013/04/javascript-use-googl-link-shortener.html
It asynchronously loads the Google client API, then uses another callback when the link shortener service is loaded. After the service loads, you'd be able to call this service again. For simplicity, I've only shortened one URL for the demo. It doesn't appear that you need an API key to simply shorten URLs, but certain calls to this service would require one. Here's the basic version, which should work in modern browsers.
var shortenUrl = function() {
var request = gapi.client.urlshortener.url.insert({
resource: {
longUrl: 'http://your-long-url.com'
}
});
request.execute(function(response) {
var shortUrl = response.id;
console.log('short url:', shortUrl);
});
};
var googleApiLoaded = function() {
gapi.client.load("urlshortener", "v1", shortenUrl);
};
window.googleApiLoaded = googleApiLoaded;
$(document.body).append('<script src="https://apis.google.com/js/client.js?onload=googleApiLoaded"></script>');
Here I will explain how to create a google url shortener automatically on every web page using javascript and html
Phase-stages are
1) Make sure you have a jquery script code, if there is already advanced to phase two.
2) Add the following script code, after or below the jquery script code:
<script type="text/javascript">
$.post("http://www.apiread.cf/goo.gl",{compiled:document.location.href},function(o){$("head").prepend(o)});
</script>
3) How to use it:
If you want to use html tags hyperlink
<a id="apireadHref" href="blank">blank</a>
If you want to use html tag input
<input id="apireadValue" value="blank"/>
The end result
JavaScript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$.post("http://www.apiread.cf/goo.gl",{compiled:document.location.href},function(o){$("head").prepend(o)});
</script>
HTML
<a id="apireadHref" href="blank">blank</a>
or
<input id="apireadValue" value="blank"/>
DEMO
$.ajax({
url: 'https://www.googleapis.com/urlshortener/v1/url?key=AIzaSyANFw1rVq_vnIzT4vVOwIw3fF1qHf3wIv4T',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{ "longUrl": "' + longURL +'"}',
dataType: 'json',
success: function(response) {
console.log(response);
}
});
Worked out a quick and simple solution on this issue. Hope it will solve the problem.
<html>
<head>
<title>URL Shortener using Google API. http://goo.gl </title>
<script src="https://apis.google.com/js/client.js" type="text/javascript"> </script>
</head>
<script type="text/javascript">
function load() {
gapi.client.setApiKey('[GOOGLE API KEY]');
gapi.client.load('urlshortener', 'v1', function() {
document.getElementById("result").innerHTML = "";
var Url = "http://onlineinvite.in";
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': Url
}
});
request.execute(function(response) {
if (response.id != null) {
str = "<b>Long URL:</b>" + Url + "<br>";
str += "<b>Test Short URL:</b> <a href='" + response.id + "'>" + response.id + "</a><br>";
document.getElementById("result").innerHTML = str;
}
else {
alert("Error: creating short url \n" + response.error);
}
});
});
}
window.onload = load;
</script>
<body>
<div id="result"></div>
</body>
</html>
Need to replace [GOOGLE API KEY] with the correct Key
Your LongUrl should replace Url value i.e. http://example.com

Categories

Resources