I have got a 2d array in javascript.
var erg = new Array();
for (var i in val) {
erg[i] = new Array();
for (var j in val[i]()) {
erg[i][j] = val[i]()[j]();
}
}
but when i wanted to post it to the server only the 1d array gets passed. (erg[i])
$.ajax({
url: '/Document/UpdateTableValues',
type: 'POST',
data: {
docid: documentId,
page: self.CurrentPage(),
elementid: element.Values()[1](),
text: erg
},
success: function (data) {
self.SaveState("Dokument gesichert");
}
});
how can i send the whole array to the server?
thanks
There is just one mistake : use text: erg +"" instead of text: erg.
Related
chart.js not accept ajax post - json respose.i couldn't solve it yet.please help..
https://prnt.sc/spt4p3
https://prnt.sc/spt6j0
my json file is:
[{"DAYS":"01.05.2020","VALUES":"0"},{"DAYS":"02.05.2020","VALUES":"0"},{"DAYS":"03.05.2020","VALUES":"0"},{"DAYS":"04.05.2020","VALUES":"0"},{"DAYS":"05.05.2020","VALUES":"0"},{"DAYS":"06.05.2020","VALUES":"0"},]
javascript file is:
var days = [];
var values=[];
$.ajax({
url: 'class/report/daily_report.php',
type: 'POST',
data: {'reload': 'renew', 'type': 'rep_1'},
success: function (response) {
var jsonARR =$.parseJSON(response);
var k=0;
for ( var key in jsonARR ) {
days[k]=jsonARR[key]["DAYS"];
values[k]=parseInt(jsonARR[key]["VALUES"]);
k++;
}
}
});
var a = {
labels: days,
datasets: [{
backgroundColor: KTApp.getStateColor("danger"),
data: values
}]
};
Please remind that $.ajax() makes an asynchronous HTTP request. In you code however, you create the chart even before ans answer from that request is received.
The problem can be solved by moving the code responsible for chart creation inside the $.ajax() block as shown below.
$.ajax({
success: function(response) {
var jsonARR = $.parseJSON(response);
var k = 0;
for (var key in jsonARR) {
days[k] = jsonARR[key]["DAYS"];
values[k] = parseInt(jsonARR[key]["VALUES"]);
k++;
};
var a = {
labels: days,
datasets: [{
backgroundColor: KTApp.getStateColor("danger"),
data: values
}]
};
new Chart(...);
});
I want to create a multidimensional array from the values I retrieved on an ajax post request.
API response
[{"id":"35","name":"IAMA","code":"24"},{"id":"23","name":"IAMB","code":"08"}]
jQuery code
var mulArr = [];
$.ajax({
type: 'POST',
url: '/path/to/APIendpoint',
dataType: 'json',
data: {
codes: codes
},
success: function(data) {
$.each(data, function(key, value) {
mulArr[key]['id'] = value.code;
mulArr[key]['text'] = value.name;
});
}
});
Syntax error
TypeError: mulArr[key] is undefined
I can properly fetch the data from the endpoint, the only error I encounter is the one I stated above. In perspective, all I want to do is simply a multidimensional array/object like this:
mulArr[0]['id'] = '24';
mulArr[0]['text'] = 'IAMA';
mulArr[1]['id'] = '08';
mulArr[1]['text'] = 'IAMB';
or
[Object { id="24", text="IAMA"}, Object { id="08", text="IAMB"}]
It happens because mulArr[0] is not an object, and mulArr[0]['id'] will throw that error. Try this:
var mulArr = [];
$.ajax({
type: 'POST',
url: '/path/to/APIendpoint',
dataType: 'json',
data: {
codes: codes
},
success: function(data) {
$.each(data, function(key, value) {
mulArr.push({id: parseInt(value.code), text: value.name});
// or try this if select2 requires id to be continuous
// mulArr.push({id: key, text: value.name});
});
}
});
Alternative to using push (which is a cleaner approach) is to define the new object.
mulArr[key] = {
id: value.code,
text:value.name
};
Another way of achieving what you want would be this one:
var mulArr = [];
$.ajax({
type: 'POST',
url: '/path/to/APIendpoint',
dataType: 'json',
data: {
codes: codes
},
success: function(data) {
mulArr = data.map(value => ({ id: parseInt(value.code), text: value.name }));
}
});
This is cleaner and also uses builtin map instead of jQuery $.each. This way you also learn the benefits of using the map function (which returns a new array) and also learn useful features of ES2015.
If you cannot use ES6 (ES2015) here is another version:
mulArr = data.map(function (value) {
return {
id: parseInt(value.code),
text: value.name
};
});
I guess you can already see the advantages.
Using BackBone i send both variables and array to post call to be sent to database. I was able to obtain the variables. But when i try to access array it goes to ERROR and unable to access that array also. Is this the way of sending is correct?
AdminView.php
addQuestion: function (event) {
var question = $('#txtQuestion').val();
var correctAns = $('#txtCorrectAns').val();
var options = ["Saab", "Volvo", "BMW"];
var data = {question: question, catID: catID, correctAns: correctAns, options: options};
Backbone.ajax({
type: 'POST',
ansyc: false,
url: "http://localhost/TEST/index.php/Rest_API/RestAPI/question",
data: data,
dataType: 'json',
success: function (val) {
alert("Success");
},
error: function (erorr) {
alert("Failed");
}
});
}
RestAPI
function question_post() {
$question = $this->post('question');
$catID = $this->post('catID');
$correctAns = $this->post('correctAns');
$options = $this->post('options');
$this->load->model('QuestionModel');
$response = $this->QuestionModel->addQuestion($question,$catID,$correctAns);
$this->response($response);
}
Use a model and use Model.save()
http://backbonejs.org/#Model-save
I'm a newbie in ajax, I've created this array through a function in js from a btn table: I've tried it many ways with no success, there's nothing printed in my *.php.. even with print_r, var__dump, etc
console.log(data)
{"datos":[{"value":false,"id":"173"},{"value":false,"id":"172"},{"value":false,"id":"171"},{"value":false,"id":"170"}]}
big question is: How can I pass this array to php, because I need to update a table sql with those values
JS:
$('#update').click(function(e){
e.preventDefault();
var datos = [],
data = '',
checkStatus = document.getElementsByName('check');
for(var i=0;i<checkStatus.length;i++){
var item = {
"value": checkStatus[i].checked,
"id": checkStatus[i].getAttribute('data-id')
}
datos.push(item);
}
data = JSON.stringify({datos:datos});
$.ajax({
type: "POST",
url: "updateTable.php",
datatype: "json",
data: {data},
cache: false,
success: function(){
console.log(data);
}
});
});
PHP:
????????
On the server side ..
var_dump(json_decode($json));
or for each
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
I always use querystring to parse data posted by client. But this is the first time I am posting an array, and I'm having same issue.
client side:
$.ajax({
url: 'myurl',
type: "POST",
data: {ids: ["str1","str2","str3"]},
success: function (msg) {
location.reload();
},
error: function (msg) {
alert("ServerError");
},
cache: false,
});
server side:
var body='';
req.on('data', function(chunk) {
body += chunk.toString();
});
req.on('end', function() {
var parsedbody = querystring.parse(body);
console.log(parsedbody);// {'ids[]':["str1","str2","str3"]}
My problem? Well, first note the comment: the key is ids[] intead of simply ids. So strange and annoyng. And the big problem: if I pass an array with one string like this:
data of ajax request--> data: { ids: ["str1"] }
the console.log becomes
console.log(parsedbody);// {'ids[]':"str1"}
console.log(parsedbody['ids[]'].length);// 4 (instead of 1)
As you can see my array become a string and this is a problem.
You could just easily create your own wrapper around querystring.parse(). Example:
var qs = require('querystring');
function parseQS(str) {
var result = qs.parse(str),
keys = Object.keys(result);
for (var i = 0, len = keys.length, key, newKey; i < len; ++i) {
key = keys[i];
if (key.slice(-2) === '[]') {
newKey = key.slice(0, -2);
if (!Array.isArray(result[key]))
result[newKey] = [ result[key] ];
else
result[newKey] = result[key];
delete result[key];
}
}
return result;
}
console.dir(parseQS('foo[]=bar&baz=bla&quux[]=123&quux[]=456'));
// outputs:
// { baz: 'bla',
// foo: [ 'bar' ],
// quux: [ '123', '456' ] }