I have to append some information in my JS with form data. Something like..
var form_data = new FormData();
form_data.append('photo', photo_data );
form_data.append('customer_id', customer_id);
form_data.append('year_name', year_name);
As we can see I have used .append thrice for three information. I tried something like this and did not work as .append() expects two parameters(field name and value) and not object.
var data = {'photo': photo_data, 'customer_id': customer_id, 'year_name', year_name};
form_data.append(data);
I wish to know if there is some way to pass multiple field names and values in a single line. Thanks!
Related
What I'm trying to accomplish in php is the following:
$var->doSomething(['chris' => ['age' => 22], 'evan']);
I'm sending an array via a formData (not like the above question, obviously), and php reads the array perfectly like this:
$array = $_POST('arrayOfValues');
$var->doSomething($array);
The data on my js formdata is the following:
var array = ['chris', 'evan'];
var data = new FormData();
array.forEach(function(item){
data.append('arrayOfValues[]', item);
});
I have no idea how to accomplish it, an acquaintance told me to try an object, but it didn't work (I dunno if I have to parse it somehow in php or js).
PD: JQuery or JS are accepted, but I'd prefer the latter for learning purposes
The formData creates only a set of key/values pairs representing form fields.
If you want to send complex objects to PHP you have to use JSON.
To create JSon objects use:
var myArrayObj = { ... };
var json = JSON.stringify( myArrayObject);
More information on json: http://www.json.org/js.html
So, in PHP, use:
var_dump(json_decode($json)); //where $json is your data from JS
Ok, so I have form for creating polls. I want to use AJAX request and able user to attach image instead of question, so I use FormData for this.
I could't find any solution for working with multiple input with same name (named like this: "name[]"). I tried this option:
var fdata = new FormData();
fdata.append('answers[]', $('input[name="answer[]"]').val());
But it doesn't work. I know I could use .each(), but I don't want different name for each question, so I don't have to rebuild PHP side too much.
Thanks for any help.
You have to append each value in turn. Currently you are only appending the first one (because that is what val() returns.
$('input[name="answer[]"]').each(function (index, member) {
var value = $(member).val();
fdata.append('answers[]', value);
});
The problem is $('input[name="answer[]"]').val() isn't giving you what you need; it returns the first input element's value. Instead, you want an array of values:
var values = [];
$('input[name="answer[]"]').each(function(i, item) {
values.push(item.value);
});
fdata.append('answers[]', values);
http://jsfiddle.net/j5ezgxe9/
I am currently using the following code:
jQuery('#book-a-service').click(function(){
var selectedServices = jQuery('.selected').parent().parent().html();
console.log(selectedServices);
});
and that returns:
<td rowspan="3">Brakes</td>
<td class="service-title">BRAKES SET</td>
<td class="service-description"><p>Setting of front and rear brakes for proper functioning (excluding bleeding)</p></td>
<td class="service-price">R <span id="price-brakes-set">R75</span><div id="select-brakes-set" class="select-service selected"></div>
</td>
which is what i want, except i need an array of all the elements with '.selected' class in JSON.. i just want to know how i could almost parse it in a way that i only get the contents of the td tags and as for the "service-price" only the numeric value and then how would i insert those values into a json object?
Any Help Greatly Appreciated..
jQuery is not my most formidable frameworks, but this seems to do the trick.
jQuery('#book-a-service').click(function(){
var selected = jQuery('.selected');
selected.each( function() {
var children = jQuery(this).parent().parent().find('td');
var json = {};
console.log(children);
json.type = jQuery(children[0]).text();
json.title = jQuery(children[1]).text();
json.description = jQuery(children[2]).find('p').text();
json.price = jQuery(children[3]).find('span#price-brakes-set').text();
console.log(json);
console.log(JSON.stringify(json));
});
});
in action: http://jsfiddle.net/3n1gm4/DmYbb/
When various elements share the same class and you select them with $(".class"), you can iterate through all of them using:
$(".selected").each(function() {
var element = $(this); // This is the object with class "selected" being used in this iteration
var absoluteParent = $(this).parent().parent();
// Do whatever you want...
var title_element = $(".service-title", absoluteParent); // Get service-title class elements in the context provided by "absoluteParent", I mean, "inside" of absoluteParent
var title = title_element.html();
});
In the specific case of prices, I don't know exactly what is the price (probably R75?). Anyway, it should be inside a div and then select that div to obtain the price. If it is R75, then note that the "id" property should be unique for every DOM object in your HTML.
Also note that, when getting HTML, you're only getting a string, not the actual element, so it will probably not be useful for getting new values in an easy way (you won't be able to navigate through DOM elements with an ordinary string, even if it represents HTML from an actual object). Always get jQuery objects and work with them, unless you actually need the HTML.
For generating a JSON string, just create a global array and add the objects/values you need there. Then you can obtain a JSON string using var jsonText = JSON.stringify(your_array);
Consider not doing this in Javascript, as it's not useful in the majority of cases. Just send the values through POST value to a script (PHP, for example) and in the PHP you will get the actual value. The other way (PHP to Javascript) will be useful to return JSON (using json_encode($a_php_array)) and then, in Javascript, transform to a JS array using var my_array = JSON.parse(the_string_returned_by_php);.
I have a grid using jqgrid. I need to store the some data returned by the url:, in a local variable so that I can display it in the subgrid. For this I add that column as a hidden column in the main grid, which is of the format in json:
"Details":[{"Name":"ttt", "Quantity":"12"}] .
Then in the loadcomplete: function I save the value to a variable using
var griddata = $("#grid').getCol('Details', false);
Now when I access griddata[0], I get a object Object. I tried to parse it to get the values correctly, but to no avail. I tried:
griddata[0].Details.Name
or
griddata[0].Details.0.Name
or
griddata[0].Name,
but all failed. I guess I am missing the format if the data returned by the getcol() function.I looked up the documentation on the method and it says that it returns just the values when we specify false, but could not get any examples.
If there are any examples or if there are any pointer to the solution, it will be greatly appreciated.
If you check the type of griddata[0] (for example with typeof operator) you will see that it has type of string - this is because the value you are getting is the result of toString() on the object you have passed. The reason for that is the way in which jqGrid is treating values.
If you want to store JSON as the value, you need to stringify it entirely:
"Details": "[{\"Name\":\"ttt\", \"Quantity\":\"12\"}]"
Now you can deserialize those string values into objects like this:
var griddata = $.map($("#grid").jqGrid('getCol', 'Details', false), function(value) {
return JSON.parse(value);
});
After that you can access the objects in the way you want:
var name = griddata[0].Name;
var quantity = griddata[0].Quantity;
As an alternative you can split your object into two columns, so the values can be accessed directly with getCol.
Hi I am using a Java script variable
var parameter = $(this).find('#[id$=hfUrl]').val();
This value return to parameter now
"{'objType':'100','objID':'226','prevVoting':'" // THIS VALUE RETURN BY
$(this).find('[$id=hfurl]').val();
I want to store objType value in new:
var OBJECTTYPE = //WHAT SHOULD I WRITE so OBJECTTYPE contain 400
I am trying
OBJECTTYPE = parameter.objType; // but it's not working...
What should I do?
Try using parameter['objType'].
Just a note: your code snippet doesn't look right, but I guess you just posted it wrong.
Ok, not sure if I am correct but lets see:
You say you are storing {'objType':'100','objID':'226','prevVoting':' as string in a hidden field. The string is not a correct JSON string. It should look like this:
{"objType":100,"objID":226,"prevVoting":""}
You have to use double-quotes for strings inside a JSON object. For more information, see http://json.org/
Now, I think with $(this).find('[$id=hfurl]'); you want to retrieve that value. It looks like you are trying to find an element with ID hfurl,but $id is not a valid HTML attribute. This seems like very wrong jQuery to me. Try this instead:
var parameter = $('#hfurl').val();
parameter will contain a JSON string, so you have to parse it before you can access the values:
parameter = $.parseJSON(parameter);
Then you should be able to access the data with parameter.objType.
Update:
I would not store "broken" JSON in the field. Store the string similar to the one I shoed above and if you want to add values you can do it after parsing like so:
parameter.vote = vote;
parameter.myvote = vote;
It is less error prone.