Getting an AJAX GET request to work with Express.js - javascript

I am using node.js and Express.js on the back end, and am trying to make a server call from the client via AJAX.
So I have this POST request that works fine with AJAX:
node.js/Express.js:
app.post('/createNewThing', function(req, res) {
var userInput = req.body.userInput;
if (userInput) {
res.send('It worked!');
}
});
Client Side/AJAX request:
var userInputForm = $('#userInputForm.val()')
$.ajax({
url: "/createNewThing",
type: "POST",
data: "userInput=" + userInputForm,
dataType: "text",
success: function(response, status, http) {
if (response) {
console.log('AJAX worked!);
}
}
});
The userInputForm comes from an HTML form.
This POST request works fine. But I want to change this to a GET request. If I change app.post to app.get, and change type in the AJAX call to GET, I get this 500 error:
GET /createNewThing?userInput= 500

When you make a GET request, the data appears in the query string (of the URL in the request headers). It doesn't appear in the request body. There is no request body.
When you try to read from the request body, you are trying to access a property of an undefined object, which triggers an exception and cause an internal server error.
This answer explains how to read a query string:
var id = req.query.id; // $_GET["id"]
So
var userInput = req.query.userInput;

I think var userInputForm = $('#userInputForm.val()') will get error or get wrong data..This may be the reason for the error. Due to userInputForm may not be a string and concatenate with userInput=
Actually it is bad data.
And for the data in ajax, you should modify data from data: "userInput=" + userInputForm,
to:
data: {
userInput: userInputForm
},
dataType: "json"
And var userInputForm = $('#userInputForm.val()')
to var userInputForm = $('#userInputForm').val();
At last, you could modify as bellow, I believe it works:
var userInputForm = $('#userInputForm').val();
$.ajax({
url: "/createNewThing?userInput=" + userInputForm,
type: "GET",
success: function(response, status, http) {
if (response) {
console.log('AJAX worked!);
}
}
});

Related

Update a p element from a nodejs function

I need to send a value from a input form to a nodejs server, which triggers a calculation with this value and needs to update an p element with the result of the calculation on the client side.
How can this be done?
This is what i have:
//Server side:
app.post('/calculate/:id', function(req, res){
var title = 'Tax Calculation';
var tax= taxcalculation(req.params.id);
res.render('index', {
title: title,
tax: tax,
});
});
//Client side:
var income= document.getElementById("income");
var tax = document.getElementById("tax")
$(income).on('change', function() {
console.log("changed");
$.ajax({
type: 'POST',
url: '/calculate/'+income.value,
success: function() {
$('#tax').html('<%= tax %>');
},
error: function() { // if error occured
alert("Error occured, please try again");
},
});
});
Okay, so you don't give a lot of data, but this sounds as simple as sending a response with the results to the client side in your Node web service that does the calculations and append the result to the P element
Your server code to handle the ajax call should output a json response which will contain the content for the <p>. It should not re-render the whole index page. I don't do a lot of node.js so I'll leave that for you to figure out.
The ajax success function should accept a response as a parameter, and then operate on that response.
Assuming the server response to this ajax request is of the format {"tax": 15.99}:
$.ajax({
type: 'POST',
url: '/calculate/'+income.value,
success: function(response) {
if (response.tax || response.tax === 0) {
$('#tax').html(response.tax);
}
},
error: function() { // if error occured
alert("Error occured, please try again");
},
});

how do I send a GET request with Jquery?

Currently I am using Flask and Jquery and getting a 500 Internal Server Error response in my console. When I post with Ajax to the url on flask, shouldn't it be able to be received? I don't understand why I am getting this error.
Jquery
$('.movie').click(function(){
console.log(this);
$(this).toggleClass('green blue').promise().done(function(){
if ($(this).html() == "Add Movie"){
$(this).html("Added");
}
});
id = $(this).val();
//get information from API
$.ajax({
url: "/profile",
dataType: 'json',
async: true,
data: {id: id},
success: function(data) {
}
});
Python/Flask
#app.route("/profile", methods = ["GET"])
def profile(id):
print("mydata is: ", request.args['id'])
if request.args.get:
print("this API is reached")
id = request.args.get['id']
url_movie = 'https://api.themoviedb.org/3/movie/{}?api_key=78cb6b67a99ce26e6d6619c617d9c907&language=en-US'.format(id)
r = requests.get(url_movie)
code = r.json();
return jsonify(code)
500 is a server error. There is something wrong with the request execution at server side only.

How to get CSRF token Value at javaScript

I have requirement like that, when I send request, CSRF-token should be send with it. I Explore some SO questions, But I can't find Solution.
I have written Code like bellow to add token when request being sent,
var send = XMLHttpRequest.prototype.send,
token = $('meta[name=csrf-token]').attr('content');
XMLHttpRequest.prototype.send = function(data) {
this.setRequestHeader('X-CSRF-Token', "xyz12345");
//this.setRequestHeader('X-CSRF-Token',getCSRFTokenValue());
return send.apply(this, arguments);
}
This is Working Fine, But now i need to add CSRF-Token in function in place of xyz12345.
I have tried ajax function as below .
`
$.ajax({
type: "POST",
url: "/test/"
//data: { CSRF: getCSRFTokenValue()}
}).done(function (data) {
var csrfToken = jqXHR.getResponseHeader('X-CSRF-TOKEN');
if (csrfToken) {
var cookie = JSON.parse($.cookie('helloween'));
cookie.csrf = csrfToken;
$.cookie('helloween', JSON.stringify(cookie));
}
$('#helloweenMessage').html(data.message);
});
But it is not Yet Worked.
So my question is:
How to get js side CSRF-Token Value?
you need to do this in new Laravel
var csrf = document.querySelector('meta[name="csrf-token"]').content;
$.ajax({
url: 'url',
type: "POST",
data: { 'value': value, '_token': csrf },
success: function (response) {
console.log('value set');
}
});
I get my CSRF Token by this way,
By adding function :
$.get('CSRFTokenManager.do', function(data) {
var send = XMLHttpRequest.prototype.send,
token =data;
document.cookie='X-CSRF-Token='+token;
XMLHttpRequest.prototype.send = function(data) {
this.setRequestHeader('X-CSRF-Token',token);
//dojo.cookie("X-CSRF-Token", "");
return send.apply(this, arguments);
};
});
Where CSRFTokenManager.do will be called from CSRFTokenManager Class.
Now It is adding token in header and cookie in every request.

Ajax post not received by php

I have written a simple code. In order to avoid flooding a JSON server, i want to break up the JSON response in pieces. So my jquery code should be parsing one variable ("page") to the php page that handles the JSON Oauth Request. On success, it should append the DIV with the latest responses.
My code should be working, except for the fact that my ajax post is not being received by my php file.
Here goes
archief.html
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: page,
success: function() {
console.log(page);
$.get("trytocombinenewageandgettagsendates.php", function(archief) {
$('#archief').append(archief);
});
},
error: function(err) {
alert(err.responseText);
}
});
return false;
});
The php file doesn't receive anything.
var_dump($_POST);
gives me array(0) { }.
Very strange, i'd really appreciate the help!
You are sending a string instead of key-value pairs. If you want to use $_POST you need to send key-value pairs:
...
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function() {
...
If you send a single value or string, you would need to read the raw input.
Also, you are sending 2 GET requests and 1 POST request to the same file. Is that intentional? Note that only the POST request will have the $_POST variable set.
Thank you for your help and not letting me post "this still doens't work" posts :)
I made the mistake of loading the "unConsulted" php file [$.get("trytocombinenewageandgettagsendates.php"] upon success. Instead, i append the response of the PHP.
The working code below:
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
//$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function(response){
$("#archief").append(response);
},
error: function(err) {
alert(err.responseText);
}
});
return false;

ajax request not sending any data ASP.NET MVC project with jQuery

I'm fairly new to asp.net MVC but am baffled as to why my request isn't working.
I'm trying to send an ajax request with jquery as per:
jQuery(function ($) {
var total = 0,
share = $('div.share'),
googlePlusUrl = "https://plusone.google.com/_/+1/fastbutton?url=http://bookboon.com" + $(location).attr('pathname');
setTimeout(function() {
$.ajax({
type: 'GET',
data: "smelly",
traditional: true,
url: share.data('proxy'),
success: function(junk) {
//var $junk = junk.match(regex);
console.log(junk);
},
error: function (xhr, errorText) {
console.log('Error ' + xhr.responseType);
},
});
}, 4000);
And set a line in my RouteConfig as:
routes.MapRoute(null, "services/{site}/proxy", new { controller = "Recommendations", action = "Proxy" });
The markup has a data-attribute value as:
<div class="share" data-proxy="#Url.Action("Proxy", "Recommendations")">
And my Proxy action method starts with:
public ActionResult Proxy(string junk)
The problem is that the junk parameter is always null. I can see in the debug output that the route seems to correctly redirect to this method when the page loads (as per jQuery's document ready function), but I cannot seem to send any data.
I tried sending simple data ("smelly") but I don't receive that neither.
Any suggestions appreciated!
The model binder will be looking for a parameter in the request called junk, however you're sending only a plain string. Try this:
$.ajax({
type: 'GET',
data: { junk: "smelly" }, // <- note the object here
traditional: true,
url: share.data('proxy'),
success: function(junk) {
//var $junk = junk.match(regex);
console.log(junk);
},
error: function (xhr, errorText) {
console.log('Error ' + xhr.responseType);
},
});

Categories

Resources