Reputation: 13
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);
Upvotes: 1
Views: 87
Reputation: 1466
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 yourmaterialUsed
array is too huge, you should usePOST
method instead.
Upvotes: 1
Reputation: 889
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...
Upvotes: 1
Reputation: 1042
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.
Upvotes: 0
Reputation: 34
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.
Upvotes: 0