form key+value pairs jquery plugin - javascript

Is there a way I can access the array of data that the browser compiles on a form submit - before the actual GET/POST operation in js/jq?
$("form").submit(function(event){
event.preventDefault();
//give me the data array here
});
I'm finding myself increasingly using AJAX - I call event.preventDefault(), grab the name/value pairs of all the elements contained in $(this) (the form) and then push them to the server via $.post(). It's becoming a pain the neck to assemble the data array manually. It would be great if a plugin existed of sorts:
$data = $("form").gimmeData();
Does something like this exist that supports all the major HTML input elements? Am I approaching this way wrong? Thanks!

Yes, jQuery has a "serializeArray()" method that does pretty much what you ask for.
It returns an array like:
[ { name: "something", value: "whatever" }, { name: "another_one", value: 22 } ]
You can turn that into an object like this:
var arr = $('#form_id').serializeArray(), obj = {};
for (var i = 0; i < arr.length; ++i)
obj[arr[i].name] = arr[i].value;
If a name appears more than once in a form, then its "value" will be an array of values from the separate fields.

$data = $("form").serialize(); // will return query string
$data = $("form").serializeArray(); // will return array
(Details here)

You can use the $('#form').serializeArray() method in order to get the array passed to the POST request.
You can then edit the object you receive normally.

Related

How do I access this javascript object?

{"profit_center" :
{"branches":
[
{"branch": {"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3310","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3311","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"0","site_survey":"1","branch_number":"3312","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3313","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"0","site_survey":"1","branch_number":"3314","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3315","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}}
],
"profit_center_name":"Alabama"}}
I tried accessing it in ajax through this,
data.profit_center //data here is the ajax variable e.g. function(data)
or through this data["profit_center"]
but no luck
How do I access this javascript object properly. ?
By the way that code above is from console.log(data)
EDIT:
Result from console.log(data.profit_center) and console.log(data["profit_center"]) is undefined
You can put your datain a variable like
var json = data
and you can access profit_center like
alert(json.profit_center);
alert(json.profit_center.profit_center_name); //Alabama
for(var i =0 ;i<json.profit_center.branches.length;i++){
alert(json.profit_center.branches[i]);
}
Okay I have found out why it is undefined, It is a json object so I need to parse it before i can access it like a javascript object.
var json = JSON.parse(data);
Then that's it.
First parse your data if you've not already done so.
You can access, for example, each branch_number like so:
var branches = data.profit_center.branches;
for (var i = 0, l = branches.length; i < l; i++) {
console.log(branches[i].branch.branch_number);
}
In summary, profit_center is an object and branches is an array of objects. Each element in the array contains a branch object that contains a number of keys. Loop over the branches array and for each element access the branch object inside using the key names to get the values.
The profit center name can be found by accessing the profit_center_name key on the profit_center object:
console.log(data.profit_center.profit_center_name); // Alabama
You could even use the new functional array methods to interrogate the data and pull out only those branches you need. Here I use filter to pull those objects where the purchase_order is equal to 2. Note that the numeric values in your JSON are strings, not integers.
var purchaseOrder2 = branches.filter(function (el) {
return el.branch.purchase_order === '2';
});
DEMO for the three examples

javascript array mistake

I used to create an array in js
var data = new Array();
data['id'] = self.iframeFields.id.val();
data['name'] = self.iframeFields.name.val();
data['location'] = self.iframeFields.location.val();
data['about'] = self.iframeFields.about.val();
data['company'] = self.iframeFields.company.val();
data['website'] = self.iframeFields.website.val();
but passing var data returns null value
but data['id'] return value.
What did I do wrong?
EDIT:
After nrabinowitz's answer, i was using
if ($.isArray( data )){
ajax({
url: myurl,
data: {
method: "updateProfile",
data: data
},
normalizeJSON: true,
success: function( response ){
// Check to see if the request was successful.
if (response.success){
alert(response);
} else if (onError){
// The call was not successful - call the error function.
alert(response);
}
}
});
}
as it is an object not an array,
it was not returning nothing,
Removing
if ($.isArray( data )){
}
solves the issue.
In Javascript, you want an object, not an array:
var data = {};
data['id'] = self.iframeFields.id.val();
// etc...
You're expecting the array to work like an associative array in PHP, but Javascript arrays don't work that way. I'm assuming you're setting these values by key, and then trying to iterate through the array with something like a for loop - but while you can set values by key, because in Javascript an array is just another object, these values won't be available in standard array iteration, and the length of the array will still be 0.
EDIT: You note that you're using jQuery's .ajax() function to post the data to the server. The .ajax() method expects an object containing key/value pairs, and sends them to the server as a GET or POST parameters. So in your case, if you're using an object as I describe above, your server will receive the parameters "id", "name", etc in the $_POST array - not a "data" parameter.
I suspect, though I haven't tested this, that using var data = new Array(); wouldn't work at all, because of the way jQuery serializes the data passed to .ajax() - even though an array is also an object, jQuery checks if it's an array and treats it differently:
If the object passed is in an Array, it must be an array of objects in the format returned by .serializeArray()
[{name:"first",value:"Rick"},
{name:"last",value:"Astley"},
{name:"job",value:"Rock Star"}]
So it wouldn't use the key/value pairs you set at all - you would be passing an empty array and no parameters would be passed to the server.
So the right approach here:
Use var data = {};
On the server, look for $_POST['id'], $_POST['name'], etc.
You're using the array like a regular object. You're augmenting the array with additional properties, but the array itself is still empty (you should have an array.length === 0, hence the null). Try changing
var data = new Array();
to
var data = {};
and see what you get.

json jquery filter javascript array

I have a json object array. I want to search the array and for each object, create a list of 'services' that is a comma-seperated list of all the keys which have a value of "yes".
The list of json objects with the services list is then displayed in html using jquery's each.
Its a large json file so I want to do it as efficiently as possible.
I already have the object's properties being accessed through jQuery's each (ie, obj.name)
-- so I think it should be possible to filter the services listed for each object using
jQuery's filter, and then display the key if the value is yes.
But it seems like a more efficient option would probably be to create a new javascript array, join the services with a value of yes and then add that variable to the html being
appended.
Im not sure which would be faster and so far havent been very successful at either... so any advice and examples would be very helpful.
Here's what the json array looks like:
[
{"name":"name1",
"service1":"y",
"service2":"y",
"service3":"n",
},
{"name":"name2",
"service1":"n",
"service2":"y",
"service3":"n",
},
];
If you just want to filter the array then use grep.
grep - Finds the elements of an array which satisfy a filter function. The original array is not affected.
http://api.jquery.com/jQuery.grep/
First off, delete trailing commas. Internet Explorer gets really, really confused by them. Anyway, I assume you don't want to "search" the array when you say "for each value"; you want to iterate through the array and parse it into a more usable list. The first method I'd suggest is just passing what you want as the array you desire, but if that's not an option, what you're looking for is some variant of this, which should be fairly efficient (jsFiddle example):
var json = [
{"name":"name1", "service1":"y", "service2":"y", "service3":"n"},
{"name":"name2", "service1":"n", "service2":"y", "service3":"n"}
];
var parsed = {};
for (var i = 0, iLen = json.length; i < iLen; i++) {
// Assuming all we need are the name and a list
var name;
var list = [];
for (var key in json[i]) {
var value = json[i][key];
// We need to hold on to the name or any services with value "y"
if (key === "name") {
name = value;
} else if (value === "y") {
list.push(key);
}
}
// Add them to the parsed array however you'd like
// I'm assuming you want to just list them in plain text
parsed[name] = list.join(", ");
}
// List them on the web page
for (var key in parsed) {
document.write(key + ": " + parsed[key] + "<br>");
}
That way you wind up with a display to the visitor of the services available and still keep an array around for further use if necessary.
jQuery.inArray() Search for a specified value within an array and return its index (or -1 if not found).
http://api.jquery.com/jQuery.inArray/
Or
http://api.jquery.com/jQuery.each/

jQuery .getJSON return into array variable & json array manipulation

is there any way I can get the return of $.getJSON into a variable array?
I know its async and out of scope, but I will use it inside ajax callback, I just need to get all the values first and check them against another array.
Something like:
$.getJSON('itemManager.php?a=getItems', function(data){
// itemArray = new Array(data);
// idsArray = new Array(data.id);
for (var i in someOtherArray){
if($.inArray(i, idsArray) == -1){
// do something...
// get jason variable by id?
// itemArray[i].someVariable
}
}
}
EDIT: JSON structure
[{"id":"786","user_id":"1","seller_id":"2","address_id":"1","time":1299852115,"publicComment":null,"personalComment":null},
{"id":"787","user_id":"1","seller_id":"2","address_id":"1","time":1299852115,"publicComment":null,"personalComment":null},
{"id":"785","user_id":"1","seller_id":"2","address_id":"1","time":1299852114,"publicComment":null,"personalComment":null},
{"id":"784","user_id":"1","seller_id":"2","address_id":"1","time":1299852113,"publicComment":null,"personalComment":null},
{"id":"783","user_id":"1","seller_id":"2","address_id":"1","time":1299852111,"publicComment":null,"personalComment":null}]
This is basically the idea.
Get all the values
Isolate the id values of JSON objects
Loop another array
Check if json id is inside the other array
Access other json variables by id value
There are various solutions here I guess, but I'm looking for something with minimal code.
With the given information, there is not shortcut to test the existence of IDs. You really have to loop over everything. However you can improve a bit by creating an id => object mapping:
$.getJSON('itemManager.php?a=getItems', function(data){
var items = {};
for(var i = data.length; i--; ) {
items[data[i].id] = data[i];
}
for (var j = someOtherArray.length; j--; ){
var item = items[someOtherArray[j]];
if(item){
// do something with `item`
}
}
}
It woud be even better if you create this structure on the server already, then it would be:
$.getJSON('itemManager.php?a=getItems', function(data){
for (var j = someOtherArray.length; j--; ){
var item = data[someOtherArray[j]];
if(item){
// do something with `item`
}
}
}
You should also consider which arrays will contain more elements, data or someOtherArray and adjust your data structures such that you loop over the smaller array only.
Update:
To create the appropriate structure on the server with PHP, you have to create an associate array.
So at the point where you add an object to the array, you should not do
$items[] = $obj;
but
$items[$obj->id] = $obj; // or $obj['id'] if you have an array
If you get an array as your JSON response then your data variable in your callback is an array, no need to do anything with it.
If you get an object as your JSON response as the data.id in you example might suggest, and some of it's values is an array, then just use data.id as an array, or use var array = data.id; if that is more convenient for you.
Remember that data in your callback is just whatever you got as JSON. It can be an object (which is an associative array), an array, a string, a number, or a true, false or null value. If it is an object you access it using data.key, if it is an array you access it using data[index]. I say it because I suspect that you might be confusing arrays with objects here.

How to store temporary data at the client-side and then send it to the server

I need to store data temporarily at the client-side to allow users to add, edit or delete items without having to query the server for each of these actions; just when the user finishes adding items and clicks on the Add button, the list is sent to the server to be saved permanently.
This image describes what I want to achieve.
I know I have to use arrays in JavaScript, but I don't know how to create one to store objects (in this case Detail which contains :id, price and description).
I hope you can help me out.
Thanks in advance.
PS: I'm using JSP and... sorry for my English
Sure, since it's a table it makes sense to have an array of objects. Note that an object is surrounded by curly braces and an array is surrounded by brackets:
var myArray = []; // Initialize empty array
var myObject = {}; // Initialize empty object
This should accomplish what you need:
// Initialize variables
var newEntry, table = [];
// Create a new object
newEntry = {
id: '',
price: '',
description: ''
};
// Add the object to the end of the array
table.push(newEntry);
Which is the same as this:
// Initialize array
var table = [];
// Create object and add the object to the end of the array
table.push({
id: '22',
price: '$222',
description: 'Foo'
});
You can now access properties like this:
table[0].id; // '22'
On modern browsers, if you want the data to persist across sessions (like cookies) you could use the sessionStorage or localStorage objects.
When you want to send the data to the server, you'll send a JSON version of the table across the wire:
var data = JSON.stringify(table);
You can create an Array of your custom Detail objects pretty easily with object literals:
var details = [];
details.push({id:'abc1234', price:999.99, description:'Tesla Roadster'});
details.push({id:'xyz5678', price:129.99, description:'Land Rover'});
Then you can post your data to the server when the user clicks "Add."
Sounds like a good job for JSON.

Categories

Resources