Object property name changes when parsing it to node js - ajax

I have an object:
{"description":"Κλείσε τις βάνες","closeValves":["13/21","12/31","13/12","12/32"]}
and when i am sending it to node js with ajax the moment it gets into the router.post it transforms into this
{"description":"Κλείσε τις βάνες","closeValves[]":["13/21","12/31","13/12","12/32"]} ..
Any ideas why this is happening? in the node script where i have the router.post i am requiring this
let express = require('express');
let router = express.Router();
Update at comment:
the call the function:
formEvent(json,'events/entry',valvescallback);
and the function AJAX:
function formEvent(data,module,next,e){//the request function
e=e||false;
console.log("form:",data)
if( e ){e.preventDefault();}
var url = './'+module; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: data,
dataType:'json',
success: function (data) {
next(data);
},
error:function (data) {
next(data)
}
});
}
Update at comment 2:
No the data come from postgress SQL in a text type column like this
{"description":"Κλείσε τις βάνες","closeValves":["13/21","12/31","13/12","12/32"]}
and i am using this to transform it into json and parse it:
var json = jQuery.parseJSON(data.task);
json.action = 'getValves';
json.test = json.closeValves;//test to see if it also changes name
I can see that it transformes any property that is an array like this
name:[1,2,3] --> name[]:[1,2,3]
the odd is that when I am console.log the data inside the AJAX function the are in the right form but inside the post they change..

I found it!! the answer is at the definition of the body-parser npm usage:
app.use(bodyParser.urlencoded({ extended: false}));
you just need to make the extended property true and the array name will not change.. so the answer is
app.use(bodyParser.urlencoded({ extended: true}));

Related

Binding Ajax Response Issue "You cannot apply bindings multiple times to the same element." in knockoutJs Magento2.4.3

I am calling ajax inside knockoutJs and want to binding data inside html file on checkout page.
How could i achieve this. Please help me.
define(
[
'jquery',
'ko',
'uiComponent'
],
function($, ko, Component) {
'use strict';
$(document).on('input', 'input[name="postcode"]', function () {
var ViewModel = function () {
var self = this;
self.data = ko.observableArray();
};
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
var postcode = $("input[name='postcode']").val();
var url = ;
$.ajax({
showLoader: true,
url: url,
data: {postcode: postcode},
type: "POST",
dataType: 'json'
}).done(function (content) {
viewModel.data(content);
});
});
});
After that i am getting this error.
Please correct my code. Thanks in advance.
By calling ko.applyBindings(viewModel); you are enabling knockout and binding to the root element the viewModel, right?
You can not apply bindings multiple times on the same element, so if this line gets called a 2nd time on the same root element, it will faiil.
You either want to set explicit html node, like ko.applyBindings(vm, elem) or you might want to check out ko.cleanNode(elem); so that you make sure that previous bindings are cleaned first and then you re-bind to the same element normally

Ajax call results in 500 {internal server error}

I am trying to send json data through ajax call.
Following is the code I used. I'm using node.js as the backend. a_filters,b_filters,etc. are arrays. I googled the error but couldn't get the code to work.
var filters =
{
"a" : a_filters,
"b" : b_filters,
"c" : c_filters,
"d" : d_filters
};
$.ajax({
url : "query/get-filtered-data",
dataType : 'json',
async: "true",
data:JSON.stringify(filters),
contentType: 'application/json; charset=utf-8',
success : function(data){
},
failure: function(data){
alert('got an error');
}
});
EDIT : This is my server-side code.
var express = require('express');
var router = express.Router();
//the URL below is correct since it redirects from 'query/'
router.get('/get-filtered-data', function (req, res, next) {
console.log(req);
var filters = JSON.parse(req.body);
console.log("foo");
var a_filters = filters["a"];
var b_filters = filters["b"];
var c_filters = filters["c"];
var d_filters = filters["d"];
res.send(query);
});
conosle.log('foo') doesn't print anything.
console.log(req) has req.body empty.
Thanks a lot in advance.
Because you are referencing req.body, you need to use a router method that includes a body - post or put.
You may also need to include type: "POST" in your jQuery Ajax method.
There is a more general semantic question about whether you should use get with a query string to communicate parameters when retrieving data rather than using a request body, but that is an API design question rather than a cause of errors.

Ajax unable to pass other variables with serialize()

What I am trying to achieve is making an Ajax call to the server to return some data whilst also taking into consideration what filters have been selected in my form ".searchfilters form". I am trying to pass variables along with a form serialize and am getting a syntax error unepected token . on page load. Have I merged the normal variables I want to pass along with the form.serialize in the wrong way? Also if there is a better method to applying filters to an ajax request im open to it but this is the main method I have found from online examples.
$(".sidebar-list-parent li a, .sidebar-list-child li a").click(function(){
var soundid = $(this).attr("soundid");
var soundidparent = $(this).attr("class");
var filters = $(".search-filters form");
$.ajax ({
type: 'GET',
data: {filters.serialize(), soundid:soundid, soundidparent:soundidparent, }
url: "audio-module.php",
success: function(data) {
$('.audio-modules-container').html(data);
}
});
Change
data: {filters.serialize(), soundid:soundid, soundidparent:soundidparent, }
to
data: {filters.serialize(), soundid:soundid, soundidparent:soundidparent },

ajax request in jquery, data sent to the server not working

var p = JSON.stringify(parameter);
console.log(p);
$.ajax({
type: 'POST',
url: 'http://abc.com/ajax.php',
data: p,
success: function(status) {
console.log(status);
}
});
console.log(p) shows {"o_fname":"hh","o_lname":"jkhk","o_email":"uifh#bjvh.com","o_phone":"","b_name":"bmnbmbm,b","b_address":"","b_city":"","b_postal":"","b_phone":""}
but in my http://abc.com/ajax.php page print_r($_POST) is giving me an empty array Array()
var p = JSON.stringify(parameter);
That is your problem.
When you pass string data to .ajax, it sends it “as-is” – but PHP only popuplates $_POST if it receives data encoded as application/x-www-form-urlencoded.
So don’t make your data into a string, but pass your parameter object directly as value for data – then jQuery will take care of sending it the right way, so that PHP understands what it is supposed to do with it.
I think park of the problem may be that in data: you're passing the parameter details, but to the function on the other side of the jQuery you're passing a parameter name and nothing else.
Try:
$.ajax({
type: 'POST',
url: 'http://abc.com/ajax.php',
data: {parametername:p},
success: function(status) {
console.log(status);
}
});
With parametername replaced with the parameter name ajax.php is expecting.

Can't get $.ajax or $.get to work

I have this $.ajax (using jquery) code, it originally was the $.get that is now commented but for some reason I'm always getting the error and I can't find anything wrong with it =/, am I overlooking something?
$.fn.randomContent = function(options){
var contentArray = new Array();
var dType = "html";
var defaults = {
xmlPath: "../xml/client-quotes.xml",
nodeName: "quote"
};
var options = $.extend(defaults, options);
alert(options);
$.ajax({
type: "GET",
url: "../xml/client-quotes.xml",
dataType: "html",
success: function(){
$(defaults.nodeName).each(function(i){
contentArray.push($(this).text());
});
$(this).each(function(){
$(this).append(getRandom());
});
},
error: function(){
alert("Something Went wrong");
}
});
/*$.get(defaults.xmlPath, function(){
alert("get");
$(defaults.nodeName).each(function(i){
contentArray.push($(this).text());
});
$(this).each(function(){
$(this).append(getRandom());
});
}, type);//$.get*/
};
Here's the getRandom() function:
function getRandom() {
var num = contentArray.length
var randNum = Math.floor(Math.random()*num)
var content = "";
for(x in contentArray){
if(x==randNum){
content = contentArray[x];
}
};
alert(content);
return content;
}
It could be that the browser is caching your GET requests. In this case, either:
ensure the server is controlling your cache options (using cache-control settings of private or no-cache)
change the method of your AJAX call to POST instead of GET
differentiate your GET request by adding querystring parameters that change with each request
I prefer option #1, specifically because POST operations are intended to change something on the server, and so we should use that method when our actions do in fact modify server state. GET requests on the other hand, are requests that do nothing more than read data.
I feel a GET request is more appropriate for this task, and so in my own code I would prevent the caching of the response.
Does that url have to be absolute? I've never tried doing ajax requests with a "../" in it. Do you have FireBug installed? You could examine the response header from the sever.

Resources