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

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.

Related

How to pass data from Laravel View to Ajax or Javascript code without html div (id or class) - Laravel 5.3

So, currently I am passing values stored in Database MySQL to View (using Controller). I do simple querying ModelName::where()->first();.
I have my data right now in View. I want to use that data in Ajax or Javascript code that I am writing.
I can have 46 values and one way to do this is to have <div id="field1"></div> for 46 times set div style to display:none in css and in Javascript use document.getElementById('field1'); to access the values and finally, do whatever I want to do with it.
But I find this quite long and un-necessary to do as there is no point of printing all the values in html first and then accessing it. How can I directly get {{$data}} in Javascript?
myCode
public function index(Request $request){
$cattfs = Cattf::all();
$cattts = Cattt::all();
$cattos = Catto::all();
return view('/index',compact('cattfs'));
}
View
Nothing in the view. and I prefer it to be none.
Javascript and Ajax
$(document).ready(function()
{
init();
});
function init(){
my_Date = new Date();
var feedback = $.ajax({
url:url,
dataType: "JSON",
type: "GET",
}).success(function(data){
console.log(data);
//I have some data called data from url
//I want some data from controller like: cattf,cattt,catto
//I will combine url data and cattf and do simple arithmetic to it
//finally output to the view.
}).responseText;
}
One good way would be to actually make a small API to get your data. Let's say you wanted to retrieve users.
In the api.php file in your route folder:
Route::get('/posts', function () {
return Post::all();
});
and then you just need to use http://yourUrl.dev/api/posts as your URL sent in your .ajax() call to work with what you need.
I found best solution use this: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
It takes values from controller directly to Javascript.

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

Using jquery ajax load() to transfer multiple data fields

I have an HTML form that I am trying to convert to submitting using the Jquery load() function. I have it working for a single field, but I have spent hours trying to get it to work for multiple fields, including some checkboxes.
I have looked at many examples and there seems to be about three of four ways of approaching this:
Jquery .load()
jquery .ajax()
jquery .submit()
and some others. I am not sure what the merits of each approach is but the first example I was following used the .load(), so that is what I have persisted with. The overall object is to submit some search criterion and return the database search results.
What I have at present:
<code>
// react to click on Search Button
$("#SearchButt").click(function(e){
var Options = '\"'+$("#SearchText").val()+'\"' ;
var TitleChk = $("#TitleChk").prop('checked');
if (TitleChk) Options += ', \"TitleChk\": \"1\"';
// load returned data into results element
$("#results").load("search.php", {'SearchText': Options});
return false; //prevent going to href link
});
</code>
What I get is the second parameter appended to the first.
Is there a way to get each parameter sent as a separate POST item or do I have to pull it apart at the PHP end?
It would seem as if you're stumbling over the wrapper, let's go ahead and just use the raw $.ajax() and this will become more clear.
$("#SearchButt").click(function(e){
var Options = {};
Options.text = $('#SearchText').val();
Options.title = $('#Titlechk').prop('checked')) ? 1: 0; //ternary with a default of 0
$.ajax({
url: 'search.php',
type: 'POST',
data: Options
}).done(function(data){
$('#results').html(data); //inject the result container with the server response HTML.
});
return false;
});
Now in the server side, we know that the $_POST has been populated with 2 key value pairs, which are text and title respectively.

Sending lists of variables to python via AJAX through JQuery

In my project I have javascript iterating through a set of radio buttons. First it checks to see if the selected button in the nameset has been changed, then if it has been, it records the value of the newly selected button for that row, appending it to a variable dataString, before moving on to the next buttonset. This is all well and good, it collects all the data perfectly. I run into issues when I try to send that data through AJAX, however.
For each row that is changed, I append a rowName variable and a deviceName variable do dataString. Ideally I want to send these such that when I get the data to Python, I end up with a rowName list and a deviceName list, as happens when you send multiple variables of the same name.
My AJAX call is as follows:
var call= $.ajax({
type: "POST",
url: "http://localhost/cgi-bin/savestate.py",
data: dataString
}).done(function() {
document.getElementById("upper").innerHTML+=(call.responseText);
});
As I said, the data I need to send gets collected well enough. Right now, dataString is formatted so that it looks like this:
"{rowName: 'firstRowName', deviceName: 'firstDeviceName', rowName: 'secondRowName', deviceName: 'secondDeviceName'}"
I have also tried changing the AJAX call so that the data: call looks like:
data: {dataString}
And formatted dataString to look like:
"rowName: 'firstRowName', deviceName: 'firstDeviceName', rowName: 'secondRowName', deviceName: 'secondDeviceName'"
Either way I try to send it, the data does not get to the python script. When I return the data from Python, it comes out as
FieldStorage(None, None, [])
Now since the format of the data: attribute in the AJAX call is {keyname: value, etc}, is it possible to send the data in a premade list in that format, or do I have to change the way I've formatted dataString and send it some other way?
I ended up achieving the desired effect two ways.
First Method: Thinking back to how I performed AJAX requests prior to implementing JQuery, I formatted dataString to
rowName=firstRowName&deviceName=firstDeviceName&rowName=secondRowName&deviceName=secondDeviceName
and so on. Then I simply appended that to my url in the AJAX call, so that it looked like:
url:"http://localhost/cgi-bin/saveState.py"+dataString
Second Method: The other way that I got it to work was to format the dataString the same way as in the First Method, but then simply use that as my data attribute.
data: dataString
I found it strange that this worked, since it doesn't at all follow the usual format for the data: call. But alas, it did indeed work.
In your initial attempt, you are sending POST data to your Ajax method in JSON format. However, FieldStorage is expecting it in form format (application/x-www-form-urlencoded). The two methods you mention in your answer give it to the Ajax method in form format.
Besides your solutions, another approach is to use a JSON parsing library instead of FieldStorage. Exactly how you do this depends on the framework you are using - is it Django, Pyramid, etc?

Using JSON to store multiple form entries

I'm trying to create a note taking web app that will simply store notes client side using HTML5 local storage. I think JSON is the way to do it but unsure how to go about it.
I have a simple form set up with a Title and textarea. Is there a way I can submit the form and store the details entered with several "notes" then list them back?
I'm new to Javascript and JSON so any help would be appreciated.
there are many ways to use json.
1> u can create a funciton on HTML page and call ajax & post data.
here you have to use $("#txtboxid").val(). get value and post it.
2> use knock out js to bind two way.and call ajax.
here is simple code to call web app. using ajax call.
var params = { "clientID": $("#txtboxid") };
$.ajax({
type: "POST",
url: "http:localhost/Services/LogisticsAppSuite.svc/Json/GetAllLevelSubClients",
contentType: 'application/json',
data: JSON.stringify(params),
dataType: 'json',
async: false,
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
}
I have written a lib that works just like entity framework. I WILL put it here later, you can follow me there or contact me to get the source code now. Then you can write js code like:
var DemoDbContext = function(){ // define your db
nova.data.DbContext.call(this);
this.notes=new nova.data.Repository(...); // define your table
}
//todo: make DemoDbContext implement nova.data.DbContext
var Notes = function(){
this.id=0; this.name="";
}
//todo: make Note implement nova.data.Entity
How to query data?
var notes = new DemoDbContext().notes.toArray(function(data){});
How to add a note to db?
var db = new DemoDbContext();
db.notes.add(new Note(...));
db.saveChanges(callback);
Depending on the complexity of the information you want to store you may not need JSON.
You can use the setItem() method of localStorage in HTML5 to save a key/value pair on the client-side. You can only store string values with this method but if your notes don't have too complicated a structure, this would probably be the easiest way. Assuming this was some HTML you were using:
<input type="text" id="title"></input>
<textarea id="notes"></textarea>
You could use this simple Javascript code to store the information:
// on trigger (e.g. clicking a save button, or pressing a key)
localStorage.setItem('title', document.getElementById('title').value);
localStorage.setItem('textarea', document.getElementById('notes').value);
You would use localStorage.getItem() to retrieve the values.
Here is a simple JSFiddle I created to show you how the methods work (though not using the exact same code as above; this one relies on a keyup event).
The only reason you might want to use JSON, that I can see, is if you needed a structure with depth to your notes. For example you might want to attach notes with information like the date they were written and put them in a structure like this:
{
'title': {
'text':
'date':
}
'notes': {
'text':
'date':
}
}
That would be JSON. But bear in mind that the localStorage.setItem() method only accepts string values, you would need to turn the object into a string to do that and then convert it back when retrieving it with localStorage.getItem(). The methods JSON.stringify will do the object-to-string transformation and JSON.parse will do the reverse. But as I say this conversion means extra code and is only really worth it if your notes need to be that complicated.

Categories