Formatting the text response from an AWS Lambda function - javascript

I've been working to build my first serverless web application, using AWS Lambda, API Gateway, and S3. The good news is, I've gotten it to work, and everything is talking to each other like I want it to. The bad news is, the text response I get back is ugly, and I'm having trouble figuring out how to fix it.
Website: http://wmcleanzodiac.s3-website-us-east-1.amazonaws.com
If you click the button to trigger the function, you'll see the response is written like:
{"Your Zodiac sign is :" "result"}
I'm trying to remove the quotes and brackets. I tried JSON.parse, but that just yielded object Object. Any hints on where I can look to find a solution?
To get the response, I'm using the following javascript function:
<script>
function Lambda(){
var month = document.getElementById("inmonth").value;
var day = document.getElementById("inday").value;
var date = {month : month, day : day};
const xhttp = new XMLHttpRequest();
const url= 'https://c50vvxrko9.execute-api.us-east-1.amazonaws.com/Zodiac'
xhttp.open("POST", url, true);
xhttp.send(JSON.stringify(date));
xhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) {
var resultElement = $("#sign-result");
resultElement.text(this.responseText);
}
}
}

You put the whole response into the HTML Element.
To fix this, one way is to modify your lambda to return JSON in Format like: {"result": "<the_result>"}.
Then display it using: resultElement.text(this.responseText.result); in your javascript code.

Related

Is there a way to send params inside params in ajax call (vanillaJS) [duplicate]

This question already has answers here:
How to prepare encoded POST data on javascript?
(5 answers)
Closed 1 year ago.
The context
I'm building a save/load system for an email template builder based on grapesjs-mjml. I'm saving my MJML code in a BDD (MySQL).
My current code
I'm sending my template name and my template MJML code through an ajax call which look like that
let params = "name="+template_name + "&html="+template_mjml;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "save.php", true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// doing stuffs when it's saved
}
};
xhttp.send(params);
and on the server side, I'm catching the html value with a standard $_POST['html']
My issue
Sometimes, there is urls inside my html param (it could be links for example). And inside those urls, there is some & which means my $_POST['html'] is not reading the whole param: it's stopping right before the first & of my html code
My dirty solution
On my client side, I added a html = html.replaceAll('&','//amp;') and I'm doing the reverse function on the server side. Which that, I'm getting rid of all & in my 'html' param, but it's not very nice...
I would like to know if one of you know a better/nicer solution to do that ?
You should use encodeURIComponent(). This will properly encode special characters.
let params = "name=" + encodeURIComponent(template_name) + "&html=" + encodeURIComponent(template_mjml);

PHP not detecting POST JSON data from JavaScript request

I am in need of a little help with a small bit of my code that is essential to my application. I am making a small clicker game, and I want users to be able to save and load data via PHP to my server. I do not want to use Local Storage to make it harder for anyone to edit their economy and "cheat". When the user clicks on a save button I have, it fires my vue method which initializes the saving. I have had no problem getting the data into a JSON format, however I cannot get PHP to read this data via POST. I have checked for network headers, and it shows that stuff is being sent, it seems that PHP just isn't catching it. I'll include the code for the JS part and PHP part below. The PHP is only set to echo if the array_key_exists right now, as after getting this sorted out I will easily be able to handle the rest. Any help would be greatly appreciated!
I have tried to follow this, which has not worked so far Send JSON data from Javascript to PHP?
JS
saloOut: function() {
var saveData = {
saveMoney: this.money,
saveCrystals: this.crystals,
};
saveData = "saveData=" + (JSON.stringify(saveData));
var sendData = new XMLHttpRequest();
sendData.open("POST", "salo.php", true);
sendData.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
sendData.send(saveData);
console.log(saveData);
}
PHP
<?php
if (array_key_exists("saveData", $_POST)) {
echo "<p>SALO Ready!</p>";
}
?>
Decode the JSON string at the PHP end before accessing values, like this:
<?php
if(isset($_POST['saveData'])){
$result = json_decode($_POST['saveData'], true);
// use $result['saveMoney'] and $result['saveCrystals'] accordingly
}
?>
Update# 1:
As OP commented below, I expect that it will print "SALO Ready" but it is instead doing nothing
That's because you are not using responseText property of XMLHttpRequest object to see the text received from the server. Use below snippet to see the response text.
saloOut: function() {
var saveData = {
saveMoney: this.money,
saveCrystals: this.crystals,
};
saveData = "saveData=" + (JSON.stringify(saveData));
var sendData = new XMLHttpRequest();
sendData.open("POST", "salo.php", true);
sendData.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
sendData.send(saveData);
sendData.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
}
Reference: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText

POST data with ajax

I'm trying to save a few lines of text in a textarea with ajax targeting a classic asp file.
I'm not sure how to use ajax when when it comes to sending data with POST method and NOT using jQuery, didn't find any questions concerning this here either, no duplicate intended.
Ajax function:
function saveDoc() {//disabled
var xhttp = new XMLHttpRequest();
var note = document.getElementById("note");
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("0").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "saveNote.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(note);
ASP Classic:
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.OpenTextFile("c:\inetasp\1.txt",8,true)
dim note
note = RequestForm("note")
f.Write(note)
f.Close
Response.Write("Works.");
set f=nothing
set fs=nothing
I'm aware there might be a lot wrong with the .asp since i couldn't find any specific info about how to handle ajax requests with Classic ASP correctly.
Any suggestions on how to make this work without jQuery are welcome.
I cannot test your code as I don't have a backend running on my machine right now. But I can already tell you a few things:
you are calling xhttp.send(note); but your note is a DOM element. It should be a string with a querystring format.
in your server side code you call RequestForm is it a custom function you have previously defined ? The usual syntax is Request.Form
Hope it can help

Including OpenWeatherMap API using Javascript

I'm a very beginner in JavaScript, I recently learned it at school indeed. I have to include and get responses from the OpenWeatherMap API on a web page. For now, all I want to do is getting the temperature in the city specified in the API's URL.
I struggled a long time before asking for your assistance but I couldn't figure my problem out.
Here is my code :
var btn = document.getElementById("btn");
var p = document.getElementById("paragraphe");
var txtf = document.getElementById("txtf");
btn.addEventListener('click', fun, false);
function fun(){
var xhr = new XMLHttpRequest();
xhr.open('GET','http://api.openweathermap.org/data/2.5/weatherq=London&appid=2de143494c0b295cca9337e1e96b00e0&units=metric', true)
xhr.addEventListener('readystatechanged', function(){
if(xhr.readyState == 4 && xhr.status == 200){
var obj = JSON.parse(xhr.responseText)
p.innerHTML = obj.main.temp;
}
}, false)
xhr.send();
}
Thank you for your help !
At first glance, check your spelling. I can't see your HTML, but possible issues could be: #paragraphe and #txtf.
Also, change the event name readystatechanged to readystatechange.
One tip, add console.log("insert check data here"); throughout your code. That way to can see in the console log where it is breaking. This really helps with trouble shooting!

How can I open a JSON file in JavaScript without jQuery?

I am writing some code in JavaScript. In this code i want to read a json file. This file will be loaded from an URL.
How can I get the contains of this JSON file in an object in JavaScript?
This is for example my JSON file located at ../json/main.json:
{"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]}
and i want to use it in my table.js file like this:
for (var i in mainStore)
{
document.write('<tr class="columnHeaders">');
document.write('<td >'+ mainStore[i]['vehicle'] + '</td>');
document.write('<td >'+ mainStore[i]['description'] + '</td>');
document.write('</tr>');
}
Here's an example that doesn't require jQuery:
function loadJSON(path, success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
if (success)
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path, true);
xhr.send();
}
Call it as:
loadJSON('my-file.json',
function(data) { console.log(data); },
function(xhr) { console.error(xhr); }
);
XHR can be used to open files, but then you're basically making it hard on yourself because jQuery makes this a lot easier for you. $.getJSON() makes this so easy to do. I'd rather want to call a single line than trying to get a whole code block working, but that's up to you...
Why i dont want to use jQuery is because the person i am working for doesn't want it because he is afraid of the speed of the script.
If he can't properly profile native VS jQuery, he shouldn't even be programming native code.
Being afraid means he doesn't know what he is doing. If you plan to go for performance, you actually need to know how to see how to make certain pieces of code faster. If you are only just thinking that jQuery is slow, then you are walking into the wrong roads...
JSON has nothing to do with jQuery.
There is nothing wrong with the code you have now.
To store the variable mainStore, it is a variable in that json.
You should store that json to a variable:
var myJSON = {"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]};
var mainStore = myJSON.mainStore;
//.. rest of your code.
I understand that by "reading a json file" you mean making the request to the url that returns json content. If so, then can you explain why you don't want to use jQuery for this purpose? It has $.ajax function that is perfectly suitable for this and covers the browsers' differences.
If you want to read the file then you have to do it server-side, e.g. php and provide it somehow to the dom (there are different methods) so js can use it. Reading file from disk with js is not possible.
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(xhttp.responseText)
}
};
xhttp.open("GET", "./user.json");
xhttp.send();
}
Naming using the linux filename structure
You can store the responseText to a variable or whatever you want to do with it

Categories