Sending AJAX POST request to Express - javascript

I have two questions. First one is, I don't know what I'm doing wrong when sending a POST request using AJAX. I am geting results back but userSrc parameter that I send is undefined.
How to send parameter so Express can read it using req.query and use it as a parameter for searching?
Here is the code:
Jquery:
$(function() {
$("#userSrc").keyup( function () {
let dInput = $("#userSrc").val();
console.log(dInput);
$.ajax({
type: 'POST',
url: '/quicksearch',
data : {userSrc :dInput},
success: function(result) {
let html = '';
console.log(result);
result.each(element =>{
console.log(element);
html += "<h2>" + element.Title +"</h2>";
$("#result").html(html);
});
}
});
});
});
Express:
app.post("/quicksearch", (req, res) => {
let search = req.query.userSrc;
console.log(search);
Recent.findOne({
Title: search
}, (err, foundData) => {
if (err || foundData == null) {
fetch("http://www.omdbapi.com/?s=" + search + "&apikey=b322e698")
.then(response => response.json())
.then(data => {
console.log("API RESPONSE");
console.log(data.Search);
res.send({
result: data.Search
});
});
} else {
console.log("Found Local");
res.send( {
result: foundData
});
}
});
The second question which I have is, how to implement the result that I receive back since I've tried using Object.keys and ForEach. I am not sure how to get to the result.Title.
{result: Array(7)}
result: Array(7)
0: {Title: "Undefined", Year: "2006", imdbID: "tt1436480", Type: "movie", Poster: "https://m.media-amazon.com/images/M/MV5BMTgzNzkxMzk5Nl5BMl5BanBnXkFtZTgwMTQ2MzA2MDE#._V1_SX300.jpg"}
1: {Title: "The Undefined", Year: "2013", imdbID: "tt3271334", Type: "movie", Poster: "N/A"}
2: {Title: "Viet Costas - Citizenship: Undefined", Year: "2014", imdbID: "tt3838986", Type: "movie", Poster: "N/A"}
3: {Title: "A Love Undefined", Year: "2015", imdbID: "tt4955578", Type: "movie", Poster: "N/A"}
4: {Title: "Artist Undefined", Year: "2015", imdbID: "tt5190590", Type: "movie", Poster: "N/A"}
5: {Title: "Undefined", Year: "2014", imdbID: "tt5581814", Type: "movie", Poster: "N/A"}
6: {Title: "Undefined: A Muslim-American Musical", Year: "2017", imdbID: "tt7178924", Type: "movie", Poster: "https://m.media-amazon.com/images/M/MV5BODMwYTE1ZG…jk0ZmZhXkEyXkFqcGdeQXVyNzI4NTUyNjE#._V1_SX300.jpg"}
length: 7
__proto__: Array(0)
__proto__: Object
Thanks in advance!

The express handler is getting the query parameters in the URL. Those are characters after the ? in the URL, for example, /quicksearch?search=text then req.query would be { search: "text" }.
You want to read the request body. That can be done by req.body. Make sure you add the body-parser middleware in your express app. Include the middleware:
const bodyParser = require('body-parser');
const urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(urlencodedParser);
Now in your route handlers you have access to req.body.
Your forEach is good, but it seems you're doing it on the wrong variable. In your JavaScript, the result contains the whole body of your response. Your array is in result.result. Rewrite for your JavaScript:
$(function() {
$("#userSrc").keyup(function() {
let dInput = $("#userSrc").val();
console.log(dInput);
$.ajax({
type: 'POST',
url: '/quicksearch',
data: {
userSrc: dInput
},
success: function(response) { // response is the whole body
let html = '';
console.log(response.result);
response.result.each(element => {
console.log(element);
html += "<h2>" + element.Title + "</h2>";
$("#result").html(html);
});
}
});
});
});

Related

Convert PHP array from AJAX response to Javascript Object

I'm trying to create a JavaScript object based on a template I received as a test. I use Ajax to get the data from my database but i cant seem to create the object.
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'fetch.php',
dataType: 'JSON',
success: function(response) {
var test = JSON.parse(response);
var products = {};
for (var x = 0; x < test.length; x++) {
products[x] = {
productName: test[x]['name']
};
products[x] = {
category: test[x]['category']
};
products[x] = {
price: test[x]['price']
};
}
}
});
});
I'm trying to create something like this object below
products = {data: [
{
productName: "test_item_1",
category: "category1",
price: "49",
image: "test_image.jpg",
},
{
productName: "test_item_2",
category: "category3",
price: "99",
image: "test_image.jpg",
},
{
productName: "test_item_3",
category: "category3",
price: "29",
image: "test_image.jpg",
},],};
This is the how i fetch the data from my database
while($row = mysqli_fetch_assoc($run)){$datas[] = $row;}echo json_encode($datas);
Your lines with products[x] overwrite the earlier.
Change to
products[x] = {
productName: test[x]['name'],
category: test[x]['category'],
price: test[x]['price'],
};
There's a couple of problems first...
The $.ajax() config option is dataType, not datatype
Specifying dataType: "json" means jQuery will automatically parse the response as JSON. You don't need to manually parse it again
As to your mapping problem, you can map the response array to a new one with name renamed to productName using Array.prototype.map()
$.ajax("fetch.php", {
method: "POST",
dataType: "json",
// data: ¯\_(ツ)_/¯
}).done(data => {
const products = {
data: data.map(({ name: productName, category, price }) => ({
productName,
category,
price
}))
};
});

Building a gateway with nodeJs

I have to build a layer for an API using nodeJs and create some endpoints for the frontend.
I'm new to nodeJS and I've builded some small servers creating models and making some CRUD with Mongo.
This is the first time I have to make an intermediate layer to an existing API to filter the results.
I did it, and in the expected format, but I'm getting an error from node and I can't figure out how to resolve it.
The original API is kind like this:
{
id:'some id',
pagination: {...},
results: [...],
other_results: [...],
additional_info: [
{
id:'someid',
info:'someinfo',
values:[
{
id: 'someid',
name: 'some category name',
count: 999
},
{...},
{...}
],
},
{...},
{...}
]
}
and I have to "extract" the data from "results" and the first array of "additional_info".
My endpoint has to return data in this format:
{
brand: {name: "Any brand", country: "Germany"},
categories: ["category one", "category two", "category three"],
items: [
0: {id: "olmk23238777", name: "item one", imgUrl: 'img/34341.jpg', price: {total:424, currency: "USD"}, shipping: 'fast'},
1: {id: "olmk23239348", name: "item two", imgUrl: 'img/34764.jpg', price: {total:47, currency: "USD"}, shipping: 'slow'},
…]
}
I could achieved with this:
const axios = require('axios');
exports.products = async query => {
const url = `${process.env.BASE_URL}${query}`;
let productsData = {
brand: {
name: 'Any Brand',
country: 'Germany',
},
};
try {
const result = await axios({
method: 'GET',
url,
});
const data = result.data;
productsData.categories = data.additional_info[0].values.map(
({ categoryName }) => categoryName
);
productsData.items = data.results.map(item => ({
id: item.id,
name: item.name,
imgUrl: item.imgSrc,
price: {
total: parseInt(item.price),
currency: item.currency,
},
shipping: item.shipping_method,
}));
return productsData;
} catch (error) {
console.log(error);
}
};
This is the controller:
const { products } = require('../utils/products');
exports.searchItem = async (req, res) => {
const { search } = req.query;
try {
const response = await products(search);
res.send(response).json();
} catch (error) {
console.log(error);
}
};
and the endpoint look like this:
http://localhost:4000/api/products?search=shirt
This is the error
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
I tried different things but I can't fixe it
First of all, your error has an explanation here:
Error: Can't set headers after they are sent to the client
And for your code:
look this:
res.send(response).json();
it should be one of these:
res.send(response);
// or
res.json(response);
For the parameter type/structure, please refer to documentation of your selected library.

How can I delete a key from my JSON if its empty

I am trying to delete the key from js object if key doesn't have value inside of it.
I have tried using delete foundBrief.Contents.url but not worked. I am doing this for alexa flash briefing skill. It throws error if the redirection url is blank I have to remove that attribute url in that case if its empty.
ContentSchema:
var contentSchema = new mongoose.Schema({
_id : { type: String, default: uuid.v1},
date: Date,
titleText: String,
mainText: String,
Url: String,
author:{
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
}
},{
versionKey: false
});
To display json object on the url using routes:
router.get("/:id/abcd.json", function(req, res) {
Brief.findById(req.params.id)
.populate("contents")
.exec(function(err, foundBrief) {
if (err) {
console.log(err);
} else {
console.log(foundBrief.contents);
//[{"uid":"00a3b980-4ccc-11e9-ab44-dd6a45baec41","date":"2019-03-22T02:30:00.000Z","title":"title test","main":"content text","Url":""}]
foundBrief.contents.forEach(function(element) {
if(element.Url === ""){
delete element.Url;
}
});
}
});
});
Have this
[
{
uid: "00a3b980-4ccc-11e9-ab44-dd6a45baec41",
date: "2019-03-22T02:30:00.000Z",
title: "title test",
main: "content text",
Url: ""
}
];
want this
[
{
uid: "00a3b980-4ccc-11e9-ab44-dd6a45baec41",
date: "2019-03-22T02:30:00.000Z",
title: "title test",
main: "content text"
}
];
for(let obj of foundBrief.contents){
Object.keys(obj).forEach(function(key){
if(obj[key] === ''){
delete obj[key];
}
})
}

form Data set values from web service response

I am trying to set table values from webservice response.
Iam getting my web service response like this.but if he response is like this means it is not getting set there.This response can be dynamic.
0:{name: "image.png", base64: "iVBORw"}
1:{name: "download.png", base64: "iVBO"}
2:{name: "test-animation.gif", base64: "R0lGODlhLAEs"}
How can i change it to??
[["image.png", "iVBORw"],["download.png", "iVBO"],[test-animation.gif", "R0lGODlhLAEs"]]
here it is what iam trying
$.cordys.ajax({
method: "somewebservice",
namespace: "Package",
parameters: {
emailid:mailidvalue
},
dataType: '* json',
success: function (result) {
output=result;
bodycontent=output["data"]["body"];
var attachvalue=result.data.tuple;
$('#attachmenttable').DataTable( {
"data": attachvalue,
columns: [
{ title: "File Name" },
{ title: "Base64" }
]
} );
},
error: function(err){
console.log(err);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
I see a 1-1 mapping between what you are given and what you desire, therefore use Array.prototype.map() or $.map.
var given = {
0: {
name: "image.png",
base64: "iVBORw"
},
1: {
name: "download.png",
base64: "iVBO"
},
2: {
name: "test-animation.gif",
base64: "R0lGODlhLAEs"
}
};
var desired = Object.keys(given).map(function(key) {
return [ given[key].name, given[key].base64 ];
});
console.log(desired);
var given = {
0: {
name: "image.png",
base64: "iVBORw"
},
1: {
name: "download.png",
base64: "iVBO"
},
2: {
name: "test-animation.gif",
base64: "R0lGODlhLAEs"
}
};
var desired = $.map(given, function (value, key) {
return [[ given[key].name, given[key].base64 ]];
});
console.log(desired);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Ionic V1 $http post json data params

I have 2 objects generated by sqlite execution:
var info_update = {
id: 270,
cancelados: 2,
concluidos: 2,
total: 914
}
var participantes = [
{id: "10",
nome: "Antonio",
idade: "4",
ativo: 1,
msg: "Backorder"
},
{id: "11",
nome: "Carlos",
idade: "1",
ativo: 1,
msg: "Flagged"
}
]
For send the object I use this method on service:
var headers = {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
};
return $http({
method: "POST",
url: "remote_url.com/action",
data: {info_update: info_update, participantes: participantes},
headers : headers
})
What's the problem?
The parameter info_update it's sent to server, but the parameter participantes it's send empty, as appears in the attached image
I need send ALL data for serve.
How i do it?
Your participantes is not object its array try changing it to object using .map function

Categories