Ionic V1 $http post json data params - javascript

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

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
}))
};
});

Sending AJAX POST request to Express

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);
});
}
});
});
});

Cannot put "body' in fetch post request

I have a problem with posting data throw REST API and fetch request. The request status is 200, and object goes to data base, but without body:( Since i use Insomnia, object only have an id and some "__v" key. Here`s result in data base
{
"_id": "5aa7c133610f563a089d9ccf",
"__v": 0
},
{
"_id": "5aa7c134610f563a089d9cd0",
"__v": 0
},
and my API function
function api(endpoint) {
endpoint = `http://localhost:3030/api/${endpoint}`;
return {
get() {
return fetch(endpoint)
},
post(body) {
return fetch(endpoint, {
method: 'POST',
headers: {'Content-Type':'application/x-www-form-urlencoded'},
body: JSON.stringify(body)
});
},
delete() {
return fetch(endpoint, {
method: 'DELETE'
})
}
}
}
let obj = {
name: "Apple",
nutritional_value: 100,
proteins: 200,
fats: 120,
carbohydrates: 3215,
description: "some delicious apple",
image: "apple.png",
type: "fruit"
};
api('food').post(obj);
So, what`s the problem? Help, please:)

mongodb search query - returns all results (non matching ones too)

This is a sample from MEAN stack website,
I require the query to return parameters that match ' exactly ' with the input.
Please view the image attached to understand the issue better.
Search Query Function
Any hint on this issue ? (I'm a beginner so please elaborate a little)
-TIA :)
Input for the search from the browser
{ body: { hp: 1, length: 1, diameter: 1, voltage: 1 } }
// mongo schema
var CableSchema = new schema({
body : {
"hp": {
type: Number
},
"length": {
type: Number
},
"diameter": {
type: Number
},
"voltage": {
type: Number
},
"cost": {
type: Number
},
"type": {
type: String,
default: "Cable"
}
}
});
-----------------------------------------------------------
// Result from Search Query obtained in console
[ { body:
{ type: 'Cable',
cost: 1,
voltage: 1,
diameter: 1,
length: 1,
hp: 1 },
__v: 0,
_id: 5820246086d42a3c269ad9f2 },
{ body:
{ type: 'Cable',
cost: 2,
voltage: 2,
diameter: 2,
length: 2,
hp: 2 },
__v: 0,
_id: 5820249086d42a3c269ad9f3 } ]`
The keys 'hp','length' etc are inside the body object of cable schema. So to refer 'hp' use 'body.hp' in query
Change your query to
var query = Cable.find({'body.hp' : parseInt(reqHp) , 'body.length' : parseInt(reqLen),
'body.diameter' : parseInt(reqDia) ,'body.voltage' : parseInt(reqVol)})
The confusion was with assignment - 1body was from req body and the other one was from '2body' schema
I needed to use 1body.2body to reach inside for the data.
var reqHP = req.body.body.hp;
var reqLen = req.body.body.length;
var reqDia = req.body.body.diameter;
var reqVol = req.body.body.voltage;
var reqCost = req.body.body.cost;

get array with in JSON array in web method? How to?

i have a working ajax function with web method without getting string[] address or any other array string [] abc , in parameter , My arrays within array is
MDate: "04-08-2015"
MPurpose: 1
MTime: "1010"
RowNumber: 2
address: Array[1]
cell: Array[1]
company: Array[1]
designation: Array[1]
id: "0"
masterID: 0
name: Array[1]
nic: Array[1]
after JSON.STRINGIFY it becomes
"{"name":["nouman","nouman"],"nic":["9089898","9089898"],"designation": ["jkkhjk","jkkhjk"],"company":["uk","uk"],"cell":["+923012324265","+923012324265"],"address":["hkjhjk","hkjhjk"],"id":"0","MDate":"04-08-2015","MTime":"1010","MPurpose":1,"masterID":0,"RowNumber":3}"
their are 2 adresses , cell etc as array[]
my ajax method correct
$.ajax({
type: "POST",
url: "AddNewMeeting.aspx/SetFileName",
contentType: "application/json;charset=utf-8",
data: JSON.stringify(Meeting),
dataType: "json",
success: function (data) {
alert(data);
},
error: function (result) {
//alert("Error login");
}
});
}
my web method works only when i use parameters other then arrays like adress , cell etc
[WebMethod]
public static string SetFileName(string MDate, int MPurpose, string MTime, int RowNumber)
{
string c = "d";
return c;
}
i want to recieve
//string[] address, string[] cell, string[] company, string[] designation, int id, int masterID, string[] name, string[] nic)
also in parameter but how it would not work
We can send arrays as parameter like this
companyArray = ['Value1', 'Value2']
result = { MDate: "04-08-2015", companies: companyArray }
return JSON.stringify(result)
Where web service will be
public string webService(string MDate, string[] companies)
It works for me
You need to add the traditional property to your AJAX request, set it to true and remove the JSON.stringify:
var meetingData = {
MDate: "04-08-2015",
MPurpose: 1,
MTime: "1010",
RowNumber: 2,
address: [ 'string1', 'string2' ],
cell: [ 'string1', 'string2' ],
company: [ 'string1', 'string2' ],
designation: [ 'string1', 'string2' ],
id: "0",
masterID: 0,
name: [ 'string1', 'string2' ],
nic: [ 'string1', 'string2' ],
};
$.ajax({
type: "POST",
url: "AddNewMeeting.aspx/SetFileName",
contentType: "application/json;charset=utf-8",
data: meetingData,
dataType: "json",
traditional: true,
success: function (data) {
alert(data);
},
error: function (result) {
alert("Error login");
}
});

Categories