creating a associative array/hash in javascript - javascript

I have a form with different groups of checks boxes and trying to pass all the selected values into an array then pass that data into a ajax request.
$('#accessoriesOptions input').each(function(index, value){
if($(this).attr('checked') ){
var newItem =[];
var obj = {};
obj[$(this).attr('value')] = $(this).attr('name'); //I have an hash table with the key-value
wizard.searchArray.push(obj);
}
})
$.ajax({
data : wizard.searchArray
})
I get a wizard.searchArray like :
[0] = {'acc_1' : 'vase'},
[1] = {'acc_3' : 'ceramic'}
I need to create a key-value as I use the key to work out which part of the filtering to use.
The problem
When I do the ajax request, from firebug I see the request as :
/wizard-demo/?undefined=undefined&undefined=undefined

In this case just push add the properties to the obj and use it directly, that's the pair that'll get serialized property when used as the data property, like this:
var obj = {};
$('#accessoriesOptions input').each(function(index, value){
if(this.checked){
obj[this.value] = this.name;
}
})
$.ajax({
data : obj
});
Though this is backwards from a normal <form> submission, if that's what you want it's this instead:
obj[this.name] = this.value;
If you wanted to send the entire form, there's a much shorter/built-in .serialize() method for this:
$.ajax({
data : $("#accessoriesForm").serialize()
});

Related

javascript and jquery weird array object

i have stuck on this weird thing for 03 day and don't understand why it created that object "id[]" when jquery sending data to server. i tried to push the element to new array so i can get the normal {id: 'value01'} but it does not work, the server response is still showing the weird array in object: {'id[]': 'value01}. i am stuck on this because if i do var id = masoid[0] it work as the server show normal {id: 'value01'} but i need to filter the array before sending it. Thank you for your time
here is jquery code
function onlyUnique(value, index, self) {
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
if(isNumeric(value)){
return self.indexOf(value) === index;
}
};
// var id = {masoid.filter(onlyUnique)};
// var idDaFilter = new Array;
// id.forEach(element => {
// idDaFilter.push(element);
// });
var id = masoid.filter(onlyUnique);
console.log(id);
$.ajax({
url: deleteUrl,
type: 'POST',
data: {id:id},
});
the server response:
server code
let id = JSON.parse(JSON.stringify(req.body));
console.log(req.body);
You're using the method filter in the variable id. This method return a new array (shallow of original), so this is why you're getting 'id[ ]' on response. Use find instead.
var id = masoid.find(onlyUnique);
See an example here.
When you set var id = masoid[0] you're getting the first element of that array, than it works.
See more details on documentation find method and filter method

How can I assign dictionary values to javascript variables (jQuery / AJAX API call returned in JSON)

I have a well running AJAX request that queries data from a third party API that returns the data in JSON. I now want to assign the values from the returned JSON data to javascript variables to make further manipulation to the data itself in my AJAX success function before updating the frontend.
In the below example I would like to assign the value of key name to my Javascript team variable.
What would be the best way to accomplish this?
This is the returned structure:
{
"api":{
"results":1,
"teams":[
{
"team_id":66,
"name":"Barcelona",
"code":null,
"logo":"Not available in Demo",
"country":"Spain",
"founded":1899,
"venue_name":"Camp Nou",
"venue_surface":"grass",
"venue_address":"Carrer d&apos;Ar\u00edstides Maillol",
"venue_city":"Barcelona",
"venue_capacity":99787
}
],
This is my AJAX request:
$('ul.subbar li a').on('click', function(e) {
e.preventDefault();
var team_id = $(this).attr("id");
console.log(team_id);
$.ajax({
method: "GET",
dataType: "json",
url: "https://cors-anywhere.herokuapp.com/http://www.api-football.com/demo/api/v2/teams/team/" + team_id,
success: function(response) {
var team_data = response
console.log(team_data)
team = // how to assign team name from API callback to variable
console.log(team)
$("#selectedClub").html(response);
}
});
});
You can use dot notation to navigate through objects
team_data.api.teams[0].name //output: "barcelona"
In you example there is only one item inside teams array, so the above example should works fine, but let's suppose that in your response there is more than 1 team on teams then you could do something like this:
var teamList = [];
$.each(team_data.api.teams, function(index, team){
teamList.push(team.name);
})
and it will give an array with all team names from your ajax response
put JSON in js obj variable
var obj = JSON.parse('{ <key:value>,<key:value>...}');
Make sure the text is written in JSON format, or else you will get a syntax error.
Use the JavaScript object in your page:
Example
<p id="demo"></p>
<script>
document.getElementById("name").innerHTML = obj.name + ", " + obj.country;
</script>

PHP POST: Setting data variables dynamically from an array

Hi all I'm pretty new to PHP and AJAX and all that good stuff and I'm a little stumped on how to proceed from here in my code.
I have a form that is getting sent and I have an array (subcategories) which contains the form labels to retrieve the values of the fields. The fields and values are getting created dynamically based on a textfile that the user uploads so I don't have any way of knowing what they are.
var arrayLength = subcategories.length;
for (var i = 0; i < arrayLength; i++) {
var eachfield = subcategories[i];
//Do something
//#C: selector is working fine, cleaning input
var eachfield = $('#' + eachfield).val().trim();
//push the appropriate values with the fixed stuff to a new array
values.push(eachfield);
}
What I'm trying to do is now to set these variables to some name and send them through $data using AJAX and POST.
Something like the following if I was setting everything statically.
var data = {
dimitypedata: dimitype,
densitydata: density,
velocitydata: velocity,
temperaturedata: temperature,
submitbtnclicked: "submitted"
};
//using the data and sending it through a post with promise handling
$.ajax({
type: 'POST',
url: "controller.php",
data: data,
success: function(response) {
//alert("worked");
//console.log(response);
alert(response);
},
error: function() {
alert("There was an error submitting the information");
}
});
I'm not quite sure how to mix these two and it may be partially because of getting a confused and not yet being that great with POST and AJAX calls.
EDIT: It looks like my question was a bit unclear (sorry first post lol) I'm trying to dynamically push values that I take out of an HTML form field. The problem is that the form is generated depending on what the user chooses to upload to the site (so both the fields and the forms. My ultimate goal is to enable the user to edit the dynamically generated form based on a text file that they upload and be able to generate a new text file after editing it on the GUI after clicking on the submit button. I can do this if its static but I'm having trouble figuring out how to do the same if I don't know what the form will contain.
I'm trying to to my data object so I can use it in my AJAX call. Here's a little bit of the PHP code that I would use in the next step if the variables were static:
if(isset($_POST['submitbtnclicked']) && $_POST['submitbtnclicked'] == 'submitted') {
//new instance of model for use
$model = new model();
$dimitypedata = $_POST['dimitypedata'];
$densitydata = $_POST['densitydata'];
$velocitydata = $_POST['velocitydata'];
$temperaturedata = $_POST['temperaturedata'];
For an exact answer, we need to see what the "subcategories" array look like.
If I understood correctly, you would like to put the values in an object instead of an array (values). So the first part would look like:
var data = {};
var arrayLength = subcategories.length;
for (var i = 0; i < arrayLength; i++) {
//notice that now field name and field value go in separate variables
var fieldName = subcategories[i];
//#C: selector is working fine, cleaning input
var fieldValue = $('#'+eachfield).val().trim();
//push the appropriate values with the fixed stuff to a data object
data[fieldName] = fieldValue;
}
//and then you send your gathered data
//using the data and sending it through a post with promise handling
$.ajax({
type: 'POST',
url: "controller.php",
data: data,
success: function(response) {
//alert("worked");
//console.log(response);
alert(response);
},
error: function() {
alert("There was an error submitting the information");
}
});
If you want to generate your 'data' object using 'values' variable, you can do the next:
values = []; // here your values collected previously
var data = {};
for (var key in values){
data[key] = values[key];
}
//now you can use your data in AJAX

Accessing items in array

I have an object returned from a $.ajax request. This is an example:
[{"id":"14","branchName":"Catcliffe","address1":"26 Main Street","address2":"","address3":null,"city":"Catcliffe","county":"South Yorkshire","postcode":"S60 5SR","country":"UK"}]
I am having a brain freeze on how to access items in the array, for example how would I set a variable to the 'branchName'...
This is the code I used to get the data:
$("#branchID").change(function(){
var id = $(this).val();
$.ajax({
url: "/admin/getBranchInfo.php?branchID=" + id,
success: function(branch){
$("div#results").html(branch);
}
});
});
You need to get the first element in the returned array using it's index, [0], then you can grab the property you want from that, .branchName.
$("div#results").html(branch[0].branchName);
Example fiddle
I just assumed that you are holding that object in a variable called xObj.
Try,
console.log(xObj[0].branchName)
But you should parse it before accessing the values since you have not mentioned the type,
var xObj = JSON.parse(branch);
console.log(xObj[0].branchName)
You have to use indexer, to access the element of array. As array contains object you go to use dot . operator to access object properties like branchName
Live Demo
$("div#results").html(branch[0].branchName);
Your code would be
$("#branchID").change(function () {
var id = $(this).val();
$.ajax({
url: "/admin/getBranchInfo.php?branchID=" + id,
success: function (branch) {
$("div#results").html(branch[0].branchName);
}
});
});
You would get the branchName property from the first (and only) item in the array:
$("div#results").html(branch[0].branchName);
use object and using its property we can access it branch[0].branchname
$("#branchID").change(function()
{
var id = $(this).val();
$.ajax(
{
url: "/admin/getBranchInfo.php?branchID=" + id,
success: function(branch)
{
var branchname= branch[0].branchname;
$("div#results").html(branch);
}
});
});
To handle multiple objects you can loop the result using a for loop like the one given below:
for(var i in branch)
{
var id = branch[i].id;
var branchName = branch[i].branchName;
//....
//Iterate other objects as well
}

Convert javascript object or array to json for ajax data

So I'm creating an array with element information. I loop through all elements and save the index. For some reason I cannot convert this array to a json object!
This is my array loop:
var display = Array();
$('.thread_child').each(function(index, value){
display[index]="none";
if($(this).is(":visible")){
display[index]="block";
}
});
I try to turn it into a JSON object by:
data = JSON.stringify(display);
It doesn't seem to send the proper JSON format!
If I hand code it like this, it works and sends information:
data = {"0":"none","1":"block","2":"none","3":"block","4":"block","5":"block","6":"block","7":"block","8":"block","9":"block","10":"block","11":"block","12":"block","13":"block","14":"block","15":"block","16":"block","17":"block","18":"block","19":"block"};
When I do an alert on the JSON.stringify object it looks the same as the hand coded one. But it doesn't work.
I'm going crazy trying to solve this! What am I missing here? What's the best way to send this information to get the hand coded format?
I am using this ajax method to send data:
$.ajax({
dataType: "json",
data:data,
url: "myfile.php",
cache: false,
method: 'GET',
success: function(rsp) {
alert(JSON.stringify(rsp));
var Content = rsp;
var Template = render('tsk_lst');
var HTML = Template({ Content : Content });
$( "#task_lists" ).html( HTML );
}
});
Using GET method because I'm displaying information (not updating or inserting). Only sending display info to my php file.
END SOLUTION
var display = {};
$('.thread_child').each(function(index, value){
display[index]="none";
if($(this).is(":visible")){
display[index]="block";
}
});
$.ajax({
dataType: "json",
data: display,
url: "myfile.php",
cache: false,
method: 'GET',
success: function(rsp) {
alert(JSON.stringify(rsp));
var Content = rsp;
var Template = render('tsk_lst');
var HTML = Template({ Content : Content });
$( "#task_lists" ).html( HTML );
}
});
I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:
var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";
console.log( JSON.stringify(display) );
This will print:
["none","block","none"]
This is how JSON actually serializes array. However what you want to see is something like:
{"0":"none","1":"block","2":"none"}
To get this format you want to serialize object, not array. So let's rewrite above code like this:
var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";
console.log( JSON.stringify(display2) );
This will print in the format you want.
You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console
You can use JSON.stringify(object) with an object and I just wrote a function that'll recursively convert an array to an object, like this JSON.stringify(convArrToObj(array)), which is the following code (more detail can be found on this answer):
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
}
To make it more generic, you can override the JSON.stringify function and you won't have to worry about it again, to do this, just paste this at the top of your page:
// Modify JSON.stringify to allow recursive and single-level arrays
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
return oldJSONStringify(convArrToObj(input));
};
})();
And now JSON.stringify will accept arrays or objects! (link to jsFiddle with example)
Edit:
Here's another version that's a tad bit more efficient, although it may or may not be less reliable (not sure -- it depends on if JSON.stringify(array) always returns [], which I don't see much reason why it wouldn't, so this function should be better as it does a little less work when you use JSON.stringify with an object):
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
jsFiddle with example here
js Performance test here, via jsPerf

Categories

Resources