Pass array with data values using POST payload with BackBone - javascript

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

Related

javascript to filter json and return another value

I have some javascript:
datasetID is set from the url value.
I get the json data.
const datasetID = urlParams.get('datasetID')
var data;
$.getJSON("json/data.json", function(json){
data = json;
});
Next I want to filter the json data based on the datasetID, then retrieve the value assigned to another attribute vernacularName and assign it to a const.
const record = data.filter(d => d.datasetID === datasetID);
const vernacularName =
How far away am I? Suggestions welcome.
sample code
[
{
"datasetID":"A1"
"language":"en",
"accessRights":"CC BY 4.0",
"vernacularName":"goat"
}
]
Filter in front-end is not a good option (let say your data.json is large) so if you could filter it in back-end before retrieving. For example, I send an ajax request with parameter ID: datasetID :
const datasetID = urlParams.get('datasetID')
var data;
$.ajax({
type: "POST",
url: "/getjson",
dataType: "json",
success: function (json) {
record = json
if (record.length === 1)
vernacularName = record[0]["vernacularName"]
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log('error');
},
data: {
ID: datasetID
},
cache: false
})
If you can't tweak in back-end and datasetID is unique then this should be enough:
if (record.length === 1)
vernacularName = record[0]["vernacularName"]

Parsing array multidimension from ajax to controller in codeigniter?

I have a dynamic table and i want to send in controller by ajax. I have code ajax like this :
$(".save").click(function(e){
var items = new Array();
$("#list-item tr.item").each(function () {
$this = $(this)
var ref_item_id = $this.find("#ref_item_id").val();
var ref_pic_id = $this.find("#ref_pic_id").val();
var price= $this.find("#price").val();
var qty= $this.find("#qty").val();
items.push({ ref_item_id : ref_item_id, ref_pic_id : ref_pic_id, price: price, qty : qty});
});
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '<?php echo base_url("transac/save")?>',
dataType: "json",
data: JSON.stringify({'items': items }),
success: function (data) {
var obj = $.parseJSON(data);
alert(obj.lenth);
},
error: function (result) { alert(result); }
});
})
now, how get data in controller and save in table database. My Controller like this :
public function penjualan_save(){
$items = $this->input->post("items");
// next code ???
}
I hope you can help me. Thanks
first thing, your don't need JSON.stringify({'items': items }), just use:
data: {'items': items },
and in your controller, just create a model and pass your post data into it, for example:
public function penjualan_save(){
$items = $this->input->post("items");
$this->load->model('model_name');
$this->model_name->insert($items);
}
then you need to define a function for your model, like this:
public function insert($data)
{
// if you didn't call database library in autoload.php
$this->load->database();
$this->db->insert_batch('mytable', $data);
}

How to use element name when initializing object in javascript?

I'm trying to get data using ajax function, but my code returns :
Uncaught SyntaxError: unexpected string..
Javascript :
var myParams = {
$('#csrf').attr('name') : $('#csrf').val(),
'module' : 'culinary',
'id' : '12',
}
$.ajax({
url: '/uploader/get_list',
type: 'GET',
data: myParams,
success: function(response) {
reponse = $.parseJSON(response);
console.log(response);
}
});
One of my friends suggested to use this:
var myParams = [];
myParams[$('#csrf').attr('name')] = $('#csrf').val();
myParams['module'] = 'culinary';
myParams['id'] = '12';
But if I use the second method, the PHP function can't recognize the parameters.
What's the correct way to send parameters to an ajax function?
The issue is in your creation of the myParams object. To create a key using a variable you need to use bracket notation. Try this:
var myParams = {
'module': 'culinary',
'id': '12',
}
myParams[$('#csrf').attr('name')] = $('#csrf').val();
The second example you have doesn't work because you create an array, ie. [], not an object, {}.
Also note that if you set the dataType property of the request then you don't need to manually parse the response as jQuery will do it for you:
$.ajax({
url: '/uploader/get_list',
type: 'GET',
data: myParams,
dataType: 'json',
success: function(response) {
console.log(response);
}
});
You should define new object {} and not new array [] :
var myParams = [];
Should be :
var myParams = {};
Hope this helps.

Creating multidimensional array inside each

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.

Passing an array from Ajax to PHP

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

Categories

Resources