Submit form with Ajax in array format, not serialized? - javascript

I want to submit a form using Ajax but I want it to be in an array, not serialized.
var form = $(this);
data: {data:form.serialize()};
gives me this in my PHP:
firstname=John&lastname=Doe&phone=123123412345
and I have to run this code in PHP to get it into the format I want:
parse_str($_POST['data'], $data);
Just seems super unnecessary and I would like to remove that step. How can I just pass the form in an array format? Thanks

// var form = $(this);
var form = this;
data: {data: Object.fromEntries(new FormData(form))}
then you will get the $_POST variable like this:
Array
(
[data] => Array
(
[firstname] => John
[lastname] => Doe
[phone] => 123123412345
)
)

You're over-engineering your Javascript.
In this line:
data: {data:form.serialize()};
you're creating an object with data as a key and your serialized data as its value. When you pass that to jQuery for an AJAX call it passes that in that form. Hence you're finding your serialize string in $_POST['data'] and you have to unpack it.
You should send your serialised data to jQuery without packing it in an object:
data: form.serialize()};
jQuery will recognise that and send the daya with the correct keys so that you can read it directly in $_POST['firstname'], $_POST['lastname'], etc.

Related

Add JavaScript object to form data while submit the form

The user has the option to perform several actions in the form, after action when he submits the form, needs to add a JavaScript object to form. I tried multiple ways, in server data reached as [Object object]
JavaScript Object
var damageitems = {'5b3b43285d57025915000002':
{action: "accept",damage_location_name:"Front Bumper", estimated_total_repair_cost: "993.72", estimated_total_repair_cost_currency:"USD"}
}
Script I tried
$( "form" ).submit(function( event ) {
event.preventDefault();
url = $(this).attr( "action" );
var postData = $(this).serializeArray();
postData.push({name: 'damage_items', value: damage_items});
$.post(url, postData, function(){});
});
Value reached in server
{"utf8"=>"✓", "_method"=>"put", "authenticity_token"=>"uztc+G0fyTb8wH7D6HZAslTfxuJvFLP3UunjiRjWylk=", "damage_items"=>"[object Object]", "action"=>"batch_update", "controller"=>"damage_items", "claim_id"=>"5b3b41415d57026665000001"}
My aims submit the value as normal submit not ajax,
the value in js variable reaches in the server as a hash with key damage_items.
Not prefer the way add it in form control value then submit
Updating your script to the following will do the trick
$( "form" ).submit(function( event ) {
event.preventDefault();
url = $(this).attr( "action" );
var postData = $(this).serializeArray();
postData.push({name: 'damage_items', value: JSON.stringify(damage_items)});
$.post(url, postData, function(){});
});
When you try to store the data in the form, it is converted into a string using toString method if it is not a string already. toString method of Object returns [object Object] and that is why you are getting it.
Converting it into a JSON string will prevent that.
The best way is to turn a JavaScript Object Literal into a JSON (see the differences here). Because It is easy for machines to parse and generate and most of server side languages have methods to parse it. Also in http requests, like ajax, we must send strings.
Fortunately we have a method in js to do that, and is using JSON.stringify() and a method to turn a JSON into JavaScript Object Literal using JSON.parse()
Then, in your code:
//JavaScript Object Literal
var damageitems = {'5b3b43285d57025915000002':
{action: "accept",damage_location_name:"Front Bumper", estimated_total_repair_cost: "993.72", estimated_total_repair_cost_currency:"USD"}
}
damageitems = JSON.stringify(damageitems);
//JSON - It is easy for machines to parse and generate
// we could put this in a request because it's a string,
console.log(damageitems);

Ajax post multiple objects and Retrieve in PHP

I have a form and an array containing some data. I am trying to post both these objects to my php script. The code I am using to post the form and array is shown below:
var json_data = JSON.stringify(data_vendor); //array to be posted
$.ajax({
url: '/crm/inventory/add_purchase_order.php',
type: 'POST',
data: {data_vendor:json_data,form_data:$("#purchase_orderform").serialize()},
dataType: 'json',
In the PHP script I am able to decode the array using the following :
$vendor_codes = json_decode($_POST["data_vendor"],true);
The form contains several fields/inputs one of which is called "order_quantity" . I am trying to retrieve this value using:
$order_quantity = $_POST["order_quantity"];
The data read shows up as NULL.
(i) Is the method used correct for posting multiple objects/strings correct?
(ii) Is the method used to retrieve the form inputs correct?
Usually when you use serialize() that is all you send because it is a urlencoded string. Then the form control names are available as keys in $_POST
But you currently only have 2 keys available to $_POST ... $_POST["data_vendor"] and $_POST["form_data"]
$_POST["form_data"] is a urlencoded string which you did with serialize() so it also needs to be decoded now manually
Try
$formData = urldecode($_POST["form_data"]);
$order_quantity = $formData ['order_quantity'];
To validate this just do a dump of $_POST["form_data"] and you will see that it is a string...not array

How to send an Array via URL and extract it in PHP?

Here is a script.
It provides some select inputs which allow picking from various types of options. When the submit button is pressed it records the data in mats and pushes the mats array into an array called materialsUsed. Everytime the submit button is clicked a new array is added in materialsUsed.
I want to know how to send the materialsUsed array through a URL to php to extract the data there and insert it into an array created in PHP.
var mats = [name= "", thick= "", size= "", quantity= 0, price= 0];
mats.name = document.getElementById("mat").options[document.getElementById("mat").selectedIndex].value;
mats.thick = document.getElementById("thick").options[document.getElementById("thick").selectedIndex].value;
mats.size = document.getElementById("size").options[document.getElementById("size").selectedIndex].value;
mats.price = parseFloat($('#priceto').val()).toFixed(2);
mats.quantity = parseInt($('#quant').val());
materialsUsed.push(mats);
If you would like to simply load them as GET values into the URL just set them directly in the URL using location.href. Then simply use $__GET (IE: $__GET['mat']) in PHP to grab values.
var baseURL = "http://yourdomain.com";
window.location.href = baseURL + "?mat=" + mats.name + "&thick=" + mats.thick etc...
First you have to properly prepare your mats array and convert materialsUsed array into JSON format. Then you can call an ajax function like below, to send it to the php script.
var jsonString = JSON.stringify(materialsUsed);
$.ajax({
type: "GET",
url: "your_script.php",
data: {data : jsonString},
success: function(){
alert("Successfully sent the data!");
}
});
From the your_script.php file, you can perform this to extract the array.
$data = json_decode(stripslashes($_GET['data']));
Important
When using GET method, the amount of the data (length of url) is
limited. So, if your materialUsed array is too huge, you should use
POST method instead.
I think what you're looking for is making an ajax call to your php script providing your js array as its data.
You should listen for the form submission event in your javascript and launch an AJAX call to your PHP script providing your array. You may send your array via the URL (query string) using a GET or in the request body using a POST (that's an option you specify in your AJAX call). Then you would just retrieve your array in your php script an do whatever you want with it.
I suggest you read more on form submission events and AJAX calls in javaScript.
Quick hint : if you have the possibility to do so, try using jQuery as AJAX is way easier to use with jQuery.
You are trying to use associative array, but it's not possible in Javascript as far as I know.
I'd say the best way to do that is creating a object, parsing to json and sending to php. Does't look that hard.

Is there a way to get the form data that is submitted to the server, before on the client-side javascript?

I have an HTML form
form(method="post)
input(name="field")
button submit
upon submitting it on the server I receive the form data as an object
app.post('/', function(req){
console.log(req.body);
// => {field: 'value'}
});
Is there a way to access this object on the client-side javascript before submitting the form?
form(method="post submit="submit(this)")
function submit(){
this.data? //
// =?> Something that gives the same object
// {field:value}
}
I've searched and found various ways but they only deal with finding the particular fields and elements and extracting the values from them.
document.getElementById("...").value - not what I want.
oText = oForm.elements["text_element_name"]; - not what I want
What I want is the "composed" object that gets sent to the server via POST request.
If you're using jQuery you can use the serializeArray method.
$('#myForm').serializeArray();
Will give you an array like this:
[
{
name: 'inputField1',
value: 'my value'
},
...
]
http://api.jquery.com/serializeArray/

is there any $_REQUEST equivalent in jquery?

as we use $_REQUEST in PHP to receive post/get values, I'm looking for a similar function/key to receive values sent through $.ajax.. in java script/j query
example:
<script>
function do_something(){
// here i want the value sent using ajax
return term;
}
$('#input').keyup(function(){
var term=$(this).val();
$.ajax({
url:do_something(),// << is this possible?? or should i try
//url:do_something(term) //<< this???
dataType:'json',
data:{term:term},
results:function(data){
alert(JSON.stringify(data));
}
});
</script>
document.location.search can get GET values of the current URL.
When used like this:
document.location.search.substr(1).split("&");
you can get an array containing all GET keys and values like key=value. Then by simply splitting them on = you get the value.

Categories