form name array not working - javascript

What could be causing my array from not forming correctly? I get the following result.
array(1) {
["element[119"]=>
array(1) {
["data"]=>
string(1) "0"
}
}
When it the result should look like this.
array(1) {
["element"]=>
array(1) {
["119"]=>
array(1) {
["data"]=>
string(1) "0"
}
}
}
Simplified front end:
<input class="custom-control-input data is-valid" data-parent="0" data-qid="119" name="element[119][data]" id="119-Yes" type="radio" onchange="showTextBox(this)" value="1" checked="">
<script type="text/javascript">
var formData = {};
$(form).find(":input.data:visible, input[type=hidden].data").each(function (index, node) {
formData[node.name] = node.value;
});
console.log(formData);
$.ajax({
url: "index.php?route=form/form/saveSection",
data: { form_id: $("#formRequest").data("formsaveid"), section_id: $("#formRequest").data("currentsectionid"), path: $("#formRequest").data("formpath"), action: "saveSection", data: formData},
dataType: "json",
method: "POST",
beforeSend: function() {
console.log("Saving Section...");
console.log("Section ID: "+$("#formRequest").data("currentsectionid"));
console.log(postData);
},
success: function(data) {
}
});
</script>
Simplified back end:
var_dump($data);exit;

The issue is happening with the way you manipulate the data with
$(form).find(":input.data:visible, input[type=hidden].data").each(function (index, node) {
formData[node.name] = node.value;
});
really you need to serialize the entire form and convert it to json, so replace the above with this:
var formData = JSON.parse($(form).serializeArray());
Then you can:
<?php
var_dump($_POST['data']);

name="[element][119][data]"
Try to encapsulate everything inside array brackets in your name tag in HTML.

Related

Cannot rewrite some html content with ajax

I wanna rewrite my HTML content with ajax. A part can be rewritten, but not for others. This is my js :
$.ajax({
url: 'http://localhost/ThePrpuz/public/mahasiswa/getDetail',
data: {
nim: nim
},
method: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
if ((data.gender) == 'Wanita') {
$('#foto').attr('src', 'http://localhost/theprpuz/public/img/cewek.jpg');
$('#foto').attr('alt', 'Cewek');
} else {
$('#foto').attr('src', 'http://localhost/theprpuz/public/img/cowok.jpg');
$('#foto').attr('alt', 'Cowok');
}
$('#nama').html(data.nama);
$('#nim').html(data.nim);
$('#univ').html(data.univ);
$('#fakultas').html(data.fakultas);
$('#jurusan').html(data.jurusan);
$('#penjurusan').html(data.penjurusan);
$('#ttl').html(data.tempat.concat(', ', data.tanggal));
}
});
The problem is, content with ** ID: ttl** can be rewritten. But did not for others. The result like this :
Nama :
Nim :
TTl : Somewhere, sometime
Univ :
Fakultas :
Jurusan :
Penjurusan :
Ih this case, I use console.log(data) to see that my ajax works or not. and in console, these are shown :
{
"nama": "Muhammad Fachri Saragih",
"tanggal": "2001-09-11",
"tempat": "Sibolga",
"gender": "Pria",
"univ": "Sriwijaya",
"fakultas": "Ilmu Komputer",
"jurusan": "Sistem Komputer",
"penjurusan": "Jaringan",
"nim": "9011281924069"
}
The method concat() is used to join two or more arrays, not strings!
Replace
$('#ttl').html(data.tempat.concat(', ', data.tanggal));
with
$('#ttl').html(data.tempat + ', ' + data.tanggal);
First, try to check the data type of the "data". I think it can't be accessed because the data type is still string, not JSON.
try to parse data to JSON.
$.ajax({
url: 'http://localhost/ThePrpuz/public/mahasiswa/getDetail',
data: {
nim: nim
},
method: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
console.log(typeof data);
var obj = JSON.parse(data);
if ((obj.gender) == 'Wanita') {
$('#foto').attr('src', 'http://localhost/theprpuz/public/img/cewek.jpg');
$('#foto').attr('alt', 'Cewek');
} else {
$('#foto').attr('src', 'http://localhost/theprpuz/public/img/cowok.jpg');
$('#foto').attr('alt', 'Cowok');
}
$('#nama').html(obj.nama);
$('#nim').html(obj.nim);
$('#univ').html(obj.univ);
$('#fakultas').html(obj.fakultas);
$('#jurusan').html(obj.jurusan);
$('#penjurusan').html(obj.penjurusan);
$('#ttl').html(obj.tempat.concat(', ', obj.tanggal));
}
});

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.

how to pass dynamically created options in multi select box to MVC controller

Please help. I'm using MVC, razor 3, jquery.
I dynamically create a multi select box when a dropdown selection changes. I bind the multiple selection to a List in my model. And it works, except it passes me the list of selected indice, instead of a list of the selected text. I want selected text, not index of the list. I set the value as text, but I have no luck.
if I manually create the list, everything works. How do I pass a list of selected options back to the controller?
I have this div in my view:
<div class="row-fluid" id="divAvailableAssemblies" hidden ="hidden">
<label class="span4">Available Assemblies:</label>
<select multiple="multiple" class="span8 ui-corner-all" id="Request_SelectingAssemblies" name="Request.SelectingAssemblies">
#*<option value="test">test</option>
<option value="test2">test2</option>*#
</select>
</div>
Here my jquery:
<script type="text/javascript">
$(function () {
$('#ddPartsToCreate').live('change',function () {
var selectedPart = this.value;
if (selectedPart < 6 || $("#txtOrderNumber").val()=="")
{
$("#divAvailableAssemblies").attr("hidden", "hidden");
return;
}
$("#divAvailableAssemblies").removeAttr("hidden");
$.ajax({
type: 'POST',
url: '#Url.Action("GetSelectingAssembliesFromOrder", "Home")',
data: JSON.stringify({ orderNumber: $("#txtOrderNumber").val() }),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
cache: false,
async: false,
success: function (response) {
var returnedData = JSON.parse(response);
var selectingAssemblies = $("#Request_SelectingAssemblies");
selectingAssemblies.empty();
for (var assembly in returnedData)
{
//selectingAssemblies.append($('<option >', { value: assembly }).text(returnedData[assembly].Text)).hide().show();
//selectingAssemblies.append($('<option value=' + assembly + '>' + returnedData[assembly].Text + '</option>'));
//selectingAssemblies.append($('<option >', { value: assembly, text: returnedData[assembly].Text }));
//selectingAssemblies.append($('<option></option>').val(assembly).html(returnedData[assembly].Text));
//$("#Request_SelectingAssemblies").append($('<option>', { value: assembly }).text(returnedData[assembly].Text));
//$("#Request_SelectingAssemblies").append($('<option>', { value: assembly }).text(returnedData[assembly].Text));
//$('<option />', { value: assembly, text: returnedData[assembly].Text }).appendTo(selectingAssemblies);
selectingAssemblies.append($('<option></option>').val(assembly).html(returnedData[assembly].Text));
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
in the backend, I generate JSON:
foreach (var assembly in pr.ShipParts)
{
sb.Append(String.Format(",{{\"Text\":\"{0}\", \"Value\":\"{1}\"}}", assembly.Mark.ToString(), assembly.Mark.ToString()));
availableAssemblies.Add(assembly.Mark.ToString());
}
I bind the multiple selection(Request_SelectingAssemblies) with this property in my model:
public List<String> SelectingAssemblies
{
get
{
return _SelectingAssemblies;
}
set
{
_SelectingAssemblies = value;
}
}
private List<String> _SelectingAssemblies = new List<string>();
When it gets to my action in the controller, SelectingAssemblies has index instead of the actual text. But I set the value of each option as text. If I set the option manually, they will show in source page and return the text. But since I dynamically create the options, they don't show in source page. I don't know how I can make MVC understand dynamic data.
In the picture, the list of CX001, RBX001, RBX002 is dynamically created. if I hit F12 in IE, I will see them created correctly in the DOM. If I choose CX001 and RBX002, SelectionAssembies will have 0 and 2.
Thanks
This is the latest and working code, thanks to #StephenMuecke:
<script type="text/javascript">
$(function () {
$('#ddPartsToCreate').live('change',function () {
var selectedPart = this.value;
if (selectedPart < 6 || $("#txtOrderNumber").val()=="")
{
$("#divAvailableAssemblies").attr("hidden", "hidden");
return;
}
$("#divAvailableAssemblies").removeAttr("hidden");
$.ajax({
type: 'POST',
url: '#Url.Action("GetSelectingAssembliesFromOrder", "Home")',
data: JSON.stringify({ orderNumber: $("#txtOrderNumber").val() }),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
cache: false,
async: false,
success: function (response) {
var returnedData = JSON.parse(response);
var selectingAssemblies = $("#Request_SelectingAssemblies");
$.each(returnedData, function (index, item) {
selectingAssemblies.append($('<option></option>').val(item.Value).html(item.Text));
});
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
public ActionResult GetSelectingAssembliesFromOrder(String orderNumber)
{
return Json(model.GetSelectingAssembliesFromOrder(orderNumber), JsonRequestBehavior.AllowGet);
}
public String GetSelectingAssembliesFromOrder(String orderNumber)
{
//...
StringBuilder sb = new StringBuilder();
sb.Append("[");
foreach (var assembly in pr.ShipParts)
{
string assemblyName = assembly.Mark.Trim();
sb.Append(String.Format(",{{\"Text\":\"{0}\", \"Value\":\"{1}\"}}", assemblyName, assemblyName));//JSON to build the list
//...
}
sb.Append("]");
sb.Remove(1, 1);//remove extra comma
_db.SaveChanges();
return sb.ToString();
}

jQuery: Mixing Strings and List of Javascript Objects in JSON

What I'm trying to do is possibly quite simple, however beeing not very familiar with jQuery I can't figure out how to do it.
I want to send some Data as JSON to an ASP.NET Controller. The Data contains some Strings and a list of Objects.
The Code would look somewhat like this:
View:
$(document).ready(function () {
var stuff = [
{ id: 1, option: 'someOption' },
{ id: 2, option: 'someOther' },
{ id: 3, option: 'anotherOne' }
];
things = JSON.stringify({ 'things': things });
var dataRow = {
'String1': 'A String',
'String2': 'AnotherOne'
}
dataRow = JSON.stringify(dataRow);
var sendData = dataRow + things;
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/Backend/DoStuffWithStuff',
data: sendData,
success: function () {
alert('Success!');
},
failure: function (response) {
alert('Fail! :(');
}
});
});
Controller:
public class Stuff
{
public int id { get; set; }
public string option{ get; set; }
}
public void DoStuffWithStuff(string String1, String2, List<Thing> things)
{
//Do my Stuff
}
Any Ideas would be great! :)
You do not need to stringify the json data.
You just create an object you van to send and than
var jsonObject = {
'string' : 'string',
'object' : {
'stirng': 'string'
}
};
$.ajax({type: "POST", url: DotNetScript, data: jsonObject})
.done(function(dataBack){
//what to do with data back
});
It actually doesn't look too bad so far! Just a few things...
[HttpPost]
public void DoStuffWithStuff(string String1, String2, List<Stuff> things)
{
//Do my Stuff
}
In here, you don't actually give a type to string2. I'm going to assume this is a typo, but that's the minor part here.
Also, in that method, notice it has the HttpPost on the top. In your javascript here:
$.ajax({
...
type: 'POST',
...
});
You specify POST, so you must make the method support post (You could also get away with GET in this case by changing type to GET, then removing the attribute, but i'm not sure what your "stuff" entails...)
var stuff = [
{ id: 1, option: 'someOption' },
{ id: 2, option: 'someOther' },
{ id: 3, option: 'anotherOne' }
];
things = JSON.stringify({ 'things': things });
var dataRow = {
'String1': 'A String',
'String2': 'AnotherOne'
}
dataRow = JSON.stringify(dataRow);
var sendData = dataRow + things;
You didn't actually pass stuff into your method, which may be helpful...
Here is the ajax method re-written with the proper JSON pass (for what you're trying to do here).
$(document).ready(function () {
var stuff = [
{ id: 1, option: 'someOption' },
{ id: 2, option: 'someOther' },
{ id: 3, option: 'anotherOne' }
];
var dataRow = {
String1: 'A String',
String2: 'AnotherOne'
things: stuff
}
$.ajax({
dataType: 'json',
type: 'POST',
url: '/Backend/DoStuffWithStuff',
data: sendData,
success: function () {
alert('Success!');
},
failure: function (response) {
alert('Fail! :(');
}
});
});

How can I convert a json object to an array in javascript

Here is a snippet of javascript from my C# web MVC application:
$.ajax({
url: 'myurl'
}).done(function(response) {
$scope.Vdata = JSON.parse(response);
return $scope.$apply();
});
The JSON response form this call looks like this
"{
\"renditions\": {
\"live\": \"true\",
\" type\": \"default\",
\"rendition\": {
\"name\": \"Live \",
\"url\": \"http: //mysite\"
}
}
}"
I would like to wrap the json response rendition object into an array to look like this-(note the added square brackets for the array)
"{
\"renditions\": {
\"live\": \"true\",
\" type\": \"default\",
\"rendition\": [{
\"name\": \"Live \",
\"url\": \"http: //mysite\"
}]
}
}"
I tried something like this which didn’t work:
$.ajax({
url: 'myurl'
}).done(function(response) {
var tmp;
if (!respose.renditons.rendition.isArray) {
tmp = respose.renditions.renditon;
respose.renditon = [];
respose.renditon.push(tmp);
}
$scope.Vdata = JSON.parse(response);
return $scope.$apply();
});
The response will sometimes include the rendition object as an array so I only need to convert to an array in cases where its not.
Can someone please help me with the correct javascript to convert the json object into an array. Preferably modifying my existing code
Try this:
$.ajax({
url: 'myurl'
}).done(function(response) {
var json = JSON.parse(response);
if(!Array.isArray(json.renditions.rendition)) {
json.renditions.rendition = [json.renditions.rendition];
}
return json;
});
Fiddle demo (kind of...)
You can check if the object is an array using this:
Object.prototype.toString.call( response.renditions.rendition ) === '[object Array]'
And you can simplify the conversion to an array -- just wrap it as an array using x = [x]:
if (Object.prototype.toString.call( response.renditions.rendition ) !== '[object Array]') {
response.renditions.rendition = [response.renditions.rendition];
}
Fiddle demo.
add data type JSON to your ajax post. example
$.ajax({type: "POST",
url: URL,
data: PARAMS,
success: function(data){
//json is changed to array because of datatype JSON
alert(data.renditions);
},
beforeSend: function (XMLHttpRequest) {
/* do something or leave empty */
},
complete: function (XMLHttpRequest, textStatus) { /*do something or leave empty */ },
dataType: "json"}
);

Categories

Resources