Submit form with a multidimensional array from Javascript to PHP - javascript

i have a big form with lot of inputs.
Also i have a javascript multidimensional array. It's an array of custom objects, that they are adding and removing as a shopping cart .
The array is defined as a local JS variable.
When i submit the form, i need to pass the array too, and i don't know how to do it.
Here I leave an example, it's illustrative only , as my form and my classes are much more complex .
<SCRIPT LANGUAGE="JavaScript">
var itemList = [];
var CustomClass = function (id, description) {
this.id = id;
this.description = description;
};
function addItem(id, description)
{
var item = new CustomClass( id,description);
itemList.push(item);
}
</script>
<form method="post" action="formSave.php">
<input type="text" name="someInput1">
<input type="text" name="someInput2">
<input type="submit" value="Submit">
</form>
Thank you very much.

If you were set on using a form to submit your data, id make a hidden text input and use JSON.stringify(data) in your js and decode it on server with json_decode server side.
<input id = 'jsValueHolder' style = 'display:none'>
<script>
function loadJSDataBeforeSend(dataToSend){
document.getElementById("jsValueHolder").value = JSON.stringify(dataToSend);
}
loadJSDataBeforeSend(itemList);
</script>
And on server side:
<?php
/* other code */
$jsonDataString = ... // get your data from the input
$dataObject = json_decode($jsonDataString);
$dataKeyValueArray = json_decode($jsonDataString, true);
?>
Note how adding true to the json_decode function returns a key value array rather than a php object.

Related

Which API I need to use instead of serializeArray to get the custom attributes of fields?

I'm using serializeArray() to retrive the form attributes. When I try to get the attributes, I'm receiving name and value for all the fields.
I have checked the documentation https://api.jquery.com/serializeArray/. I understood it will return the name and value of all the fields.
Now I have few custom attributes for some fields. I want to retrieve them using those custom attributes.
How can i achieve this?
Here is my logic.
var data = $('form').serializeArray();
var newData = {};
var queue = {};
data.forEach(function(field) {
if( field.customField != undefined && field.customField.indexOf("true")>=0 ) {
queue[field.name] = frm.value
} else {
newData[frm.name] = frm.value;
}
});
I need to get that customField attribute, I'm adding that to the HTML field attribute.
May not be the best, but you can do like this.
Let's say you have set of text boxes, text areas and so on with custom data attributes in it. What I am doing here is adding a class to those fields that you need to get value / data attributes in it.
Let's take the following HTML as an example.
HTML
<form id="frm">
<input class="serialize" type="text" name="title1" value="Test title 1" data-test1="test AAA" data-test2="test BBB" /><br/>
<input class="serialize" type="text" name="title2" value="Test title 2" data-test1="test CCC" data-test2="test DDD" /><br/>
<textarea class="serialize" data-test1="textarea test 1">TEST 22 TEST 11</textarea>
<button id="btn" type="button">Serialize</button>
</form>
What I am doing here is iterating through fields which has class .serialize and putting value, name, data attributes and so on to an array.
jQuery
$(document).ready(function(){
$('#btn').on('click', function(e) {
var dtarr = new Array();
$(".serialize").each(function(){
var sub = new Array();
sub['name'] = $(this).attr('name');
sub['value'] = $(this).val();
//data attribute example
sub['data-test1'] = $(this).data('test1');
sub['data-test2'] = $(this).data('test2');
dtarr.push(sub);
});
// This will give you the data array of input fields
console.log(dtarr);
});
});
Hope this helps.

How to get the json object from an form exception some especial name?

I have some input in my form,now I want to get the json object from the form without some input named point,What's wrong with my code?I have to remove them.It seems not work for not() function.How to fix my code?
<form id="myform">
<input name='student' value='a'/>
<input name='student' value='b'/> '
...
<input name='point' value='90'/>
<input name='point' value='95'/>
</form>
Now I only want to submit the student data to the server.So I write the code:
var data = $('#myform').not("input[name='point']").serializeArray();
var objParam = {};
$.each(data, function(i, v) {
objParam[v.name] = v.value;
});
but the result still have point data.What's wrong with not() function?
breaking down your code $('#myform') selects your form, in this case, only one object, then you filter that object with .not("input[name='point']") but there is only one object which is the form itself.
You want to filter the form's children instead, so just add .children() like this:
var data = $('#myform').children().not("input[name='point']").serializeArray();
var objParam = {};
$.each(data, function(i, v) {
objParam[v.name] = v.value;
});
Hope this will help you.
$('#myform input[name!=point]').serializeArray()
Your selector is faulty.
$('#myform').not("input[name='point']").serializeArray()
...says, "Serialise the form with ID 'myForm' which is not also an input and has the name 'point'.
Rather, you mean: "Serialise the form with ID 'myForm' but omit its child inputs with name 'point'.
Here's a non-jQuery way, using native FormData.
//get the form as form data
var fd = new FormData(document.querySelector('#myform'));
//delete any elements pertaining to [name=point]
fd.delete('point');
//et voila; this shows we retain only the student fields
for (var key of fd.keys()) alert(key);

JS filter/autocomplete

I'm trying to get a search field on my site to have an autocomplete/filter function based off of strings in a JSON object. I want to treat the search box as a way to filter out anything that could be in the JSON object.
Here's the search bar in html:
<form id="searchProducts">
<input type="text" class="md-input label-fixed" name="srch-term" id="srch-term" autofocus placeholder="Search Products"/>
<span class="md-input-bar"></span>
</form>
And here's the JS for the JSON object, created from a php array:
<script type = "text/javascript">
var orderFormData = <?php Json_encode ($tempdata);?>;
</script>
I'm not sure the best function to use or how to use it on the JSON object, but I've heard JS autocomplete may be a good solution.
Is there a pretty straightforward way to tie these together and have a nice autocomplete/filter function on my search?
This is just given as a proof-of-concept:
<form id="searchProducts">
<input type="text" class="md-input label-fixed" name="srch-term" id="srch-term" autofocus placeholder="Search Products"/>
<span class="md-input-bar"></span>
</form>
<script>
var orderFormData = <?php Json_encode ($tempdata);?>;
</script>
<script>
var orderData = orderFormData // default value
var search = function (e) {
var term = e.currentTarget.value
orderData = Object.entries(orderFormData).reduce(function (data, entry) {
if (entry[0].match(term) || entry[1].match(term)) {
data[entry[0]] = entry[1]
}
return data
}, {})
console.log(orderData)
}
document.querySelector('#srch-term').addEventListener('keyup', search)
</script>
This handles the filter part, based on the a match from key/value to the term given in the input.
If you want the autocomplete, then you will have to code much more :)
You forgot to add echo:
<?php echo json_encode($tempdata);?>;
When you are using json_encode, you need to echo or print(). Also make sure you use the right case (optional).

javascript + flask - Proper way passing an json array to server via post request?

I have to pass an json array to the server use post request:
<form action="../../../submit/" method='post' style="margin-top:-10px" id="submitBox">
<input class="attr" type="text" name="task_url" value= "annotate/{{task_name}}/{{taskid}}/{{frame_idx+1}}" hidden>
<input class="attr" type="text" name="frame_id" value= "{{frame.id}}" hidden>
<input class="attr" type="text" name="boxes_info" value = "" hidden id="boxes_info">
<button class="btn btn-default" id="submit" class="attr_sub">
<span class="glyphicon glyphicon-ok-circle"></span>
Submit
</button>
</form>
and here is how I create an json array and pass it to input value
d3.select('#submit').on('click', function(){
var boxes = [];
var box = {};
d3.selectAll('rect').each(function(){
var rect = d3.select(this)
box['xmin'] = rect.attr('x');
box['ymin'] = rect.attr('y');
box['width'] = rect.attr('width');
box['height'] = rect.attr('height');
box['label'] = rect.attr('class');
boxes.push(JSON.stringify(box));
})
boxes = JSON.stringify(boxes);
d3.select('#boxes_info').attr('value',boxes);
})
on the server side I get the the form data:
bboxes = request.form["boxes_info"]
bboxes = json.loads(bboxes)
print bboxes[0]['xmin'] // error: string indices must be integers
print bboxes[0][0] // return '{'
print bboxes
//[u'{"xmin":"433.9936102236422","ymin":"4.8","width":"404.2108626198083","height":"461.96","label":"person"}', u'{"xmin":"433.9936102236422","ymin":"-18.2","width":"404.2108626198083","height":"20","label":"person"}', u'{"xmin":"490.73482428115017","ymin":"291.84","width":"286.517571884984","height":"197.44","label":"handbag"}', u'{"xmin":"490.73482428115017","ymin":"268.84","width":"286.517571884984","height":"20","label":"handbag"}']
It seems like I have to json.loads('bboxes[0]') again. I think I make something wrong in my code. Can anyone tell me what is the proper way to do so?
It looks like you do JSON.stringify twice on client, that's why you need to do json.loads on the server twice.
Your code (simplified):
d3.select('#submit').on('click', function(){
d3.selectAll('rect').each(function(){
...
boxes.push(JSON.stringify(box)); // stringify each box
})
boxes = JSON.stringify(boxes); // stringify array with stringified boxes
})
Instead, try to use stringify once, on the resulting array:
d3.select('#submit').on('click', function(){
d3.selectAll('rect').each(function(){
...
boxes.push(box); // don't stringify heare
})
boxes = JSON.stringify(boxes); // stringify the array
})

Edit form and get all values (like array) from javascript to php

I need to edit books values (quantity) on a form, and finally use Ajax to load it into db. But I don't know how to use an associative array to pass url from ajax, like this:
xmlhttp.open("GET", "send.php?q=" + arrayassosiative, true);
Form (after php load):
<input type="text" class="bookclass" name="bookid[1]" />
<input type="text" class="bookclass" name="bookid[2]" />
<input type="text" class="bookclass" name="bookid[3]" />
JavaScript:
var arr = new Array();
var elems = document.querySelectorAll('.bookclass'); // class
for ( var i=0; i<elems.length; i++ ) {
arr.push(elems[i].value)
}
But isn't associative array, so what can I do?
Create a form around your fileds and use form_selector.serialize()

Categories