Add JavaScript object to form data while submit the form - javascript

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);

Related

Submit form with Ajax in array format, not serialized?

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.

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.

Append string to the end of a JSON request in javascript

I am trying to append data data from a form to a request so that the complete URL is sent as the request. I know I can do this in PHP but want to know if I can also do it in the javascript
For example the json request is sent to
"http://api.wunderground.com/api/myapi/conditions/q/ZIP.json"
Where ZIP will be replaced by the user submission
$(function() {
$("#getzip").submit(function() {
var zip_data =$(this).serialize();
$.getJSON("get_weather.php",null , function(data); {
Is it possible to pass it in stead of the null? And how would I go about appending it to the request strictly in the javascript?
$.getJSON("get_weather.php",{
whatever: "value",
somemore: "another value"
}.function(){
//
};
then in your PHP:
$whatever=filter_input(INPUT_GET,"whatever",FILTER_SANITIZE_STRING);
$somemore=filter_input(INPUT_GET,"somemore",FILTER_SANITIZE_STRING);
Seems like you would need to append it to the URL string itself:
$.getJSON("http://api.wunderground.com/api/myapi/conditions/q/"
+ zip_data, function(data){ return data });

Manipulate form data before it's sent with jQuery

I want to encrypt some data in a form using jQuery before it's sent to the server, it can be a MD5 hash. It is a small project, so I don't really need to use SSL.
I have the following JavaScript code where I use $.md5 in the password confirmation info:
$(document).ready(function() {
var dataToSend = {};
dataToSend['action'] = 'signup';
dataToSend['name'] = name.val();
dataToSend['email'] = email.val();
dataToSend['confsenha'] = $.md5(pass2.val());
var options = {
target: '#error',
url: 'insert.php',
beforeSubmit: validate,
data: dataToSend,
success: function(resposta) {
$('#message').html(resposta);
}
};
$('#customForm').ajaxForm(options);
});
The problem is that the data is being duplicated. I tought that overwriting the data being sent by using the var dataToSend would make ajaxForm send only data in that map. But besides sending data from dataToSend, it also sends data from the form, so what I wanted to encrypt using MD5 appears both encrypted and clean. This is an example of what goes in the request:
usuario=user&email=user%40email.com&senha=12345&confsenha=12345&send=&action=signup&name=user&email=user%40email.com&confsenha=d41d8cd98f00b204e9800998ecf8427e
I know I have to define the a function beforeSerialize, but I don't know how to manipulate form data. Can anyone tell me how to do that?
As per the documentation on the plugin site:
data
An object containing extra data that should be submitted
along with the form.
The word along is the crux.
So when you pass data as a part of the options object that data is serialized and is sent along with any data/input elements values that are part of a form.
A better approach would be to hash the password value and assign it to the same field or another hidden field in the beforeSubmit handler(in your case the validate function) and remove the dataToSend object totally.
Something like:
Without any hidden element:
function validate(){
//Other Code
pass2.val($.md5(pass2.val()));
}
With a hidden element in the form:
function validate(){
//Other Code
$("#hdnPass").val($.md5(pass2.val()));
pass2.val("");
}

Categories