How Do I Create a $_POST array from textarea input - javascript

Here is what I am trying to do.
I have a textarea input box, I would like to enter in data in an array format like this into that textarea box
'key1'='value1'
'key2'='value2'
'key3'='value3'
I then want to take this data and use it in my ajax call like so
var a = $("textarea#array_box").val().split('\n');
$.ajax({
url: 'index.php/controller/function',
type: "POST",
data: a,
success: function(data) {
console.log(data);
I am trying to get the data to pass in so that in the controller if i did one of the return statements below I would get the resulting output.
return $_POST['key1'] // should return 'value1'
return $_POST['key2'] // should return 'value2'
return $_POST['key3'] // should return 'value3'
How do I code this so that I can type into my textarea box an array, and pass that array into my controller as a $_POST?

based on your code, you can do something like this:
<?php
$tempvar=$_POST['data'];
$result = array();
foreach($tempvar as $tempitem){
$tempitem=str_replace("'","",$tempitem); //we get rid of the ' symbols
$t=explode("=",$tempitem); //' divide them by the "=" symbol
$result [$t[0]]=$t[1];
}
//the result variable now holds the array
echo $result['key1'] // value1
?>

You can use .filter(Boolean) to remove empty elements from a array; $.each() to iterate a array, .trim() to remove space characters, .replace() with RegExp /=(?=')/ to replace = with :; RegExp /'/g to replace ' with "; create a string to concatenate string at each iteration; JSON.stringify() following $.each(); pass result of JSON.stringify() to JSON.parse() as data to POST
$("button").click(function() {
var a = $("textarea#array_box").val().split("\n").filter(Boolean);
var textareaData = "";
$.each(a, function(key, value) {
textareaData += value.trim()
.replace(/=(?=')/, ":")
.replace(/'/g, '"')
+ (key < a.length - 1 ? "," : "");
});
textareaData = JSON.stringify("{" + textareaData + "}");
console.log(textareaData);
$.ajax({
url: "/echo/json/",
type: "POST",
data: JSON.parse(textareaData),
success: function(data) {
console.log(data);
}
});
});
jsfiddle https://jsfiddle.net/ahnegop3/3/

ajax data format must be {key:value,key,value} .So to getting that format , you need do a little loop with $.each and do assign key and value by like this
object[key] = value
var a = $("textarea#array_box").val().split('\n');
var temp = [];
$.each(a,function(i,v){
s = v.split("="); //split again with =
s[0] = s[0].replace(/'/g,""); //remove ' from string
s[1] = s[1].replace(/'/g,"");
temp.push(s[0],s[1]);
});
a = {};
//creating data objects
$.each(temp,function(i,v){
if(i % 2 == 0){
a[temp[i]] = temp[++i];
}
});

Related

How to get form data with multi select in checkboxs - javascript

I have a form that I want to get all his values, and convert them to json object.
the problem is that I not get the multiselect fields, just one field.
this is my code
what I am missing?
let reportDropDowns = $('#getReport').serialize();
reportDropDowns = decodeURI(reportDropDowns);
let reportDropDownsJson = {};
reportDropDownsJson = JSON.parse('{"' + reportDropDowns.replace(/&/g, '","').replace(/=/g,'":"') + '"}', function(key, value) { return key===""?value:decodeURIComponent(value) });
this is my html
Instead of serializing the data directly via .serialize(), you should instead use .serializeArray() to get the data as an array. You can then manipulate the array into an object/JSON. Try this
let reportDropDownsJson = {};
$('#getReport').serializeArray().forEach(({name, value}) => {
if( reportDropDownsJson.hasOwnProperty(name) ){
if( !Array.isArray(reportDropDownsJson[name]) ){
reportDropDownsJson[name] = [reportDropDownsJson[name]];
}
reportDropDownsJson[name].push(value);
}else{
reportDropDownsJson[name] = value;
}
});

Reading *.csv file using JavaScript

I have a csv file which has the following data format:
2001:200::,2001:200:ffff:ffff:ffff:ffff:ffff:ffff,
42540528726795050063891204319802818560,42540528806023212578155541913346768895,JP,,,36.0000,138.0000,,0,0
2001:208::,2001:208:ffff:ffff:ffff:ffff:ffff:ffff,
42540529360620350178005905068154421248,42540529439848512692270242661698371583,SG,,,1.3667,103.8000,,0,0
I want to only parse the item after the 1st comma (IPv6 address), and the lat/long (36.0000,138.0000 in the first record) values for this record.
How can I use JavaScript/ jQuery to do this?
Use the split method to turn the string into an array and then iterate thru it as you wish.
var csv = "2001:200::,2001:200:ffff:ffff:ffff:ffff:ffff:ffff,4254052872679505006389120431980\n2818560,42540528806023212578155541913346768895,JP,,,36.0000,138.0000,,0,0";
var myArray = csv.split("\n");//You should know what kind of new line your csv is using
myArray.map(function (e) { //Applies this function over each element of myArray that is each line of your csv
var line = e.split(","); //Turn the comma separated string into an array
return "The second element is: " + line[1]; //Do what you need
});
Well the same way you would in any language. First you open the file. Read it line by line. Split each line on the comma. Use the index of the array to get the value you want.
jQuery.get('file.csv', function(data) {
alert(data); // this is a line
var tempArray = data.split(','); // array of data
for(var i = 0; i < tempArray.length; i++)
{
console.log(tempArray[i]); // probably index 1 is your IPv6 address.
}
});
Or just use CSV libraries, I'd suggest PapaParse(Browser) or BabyParse(NodeJS)
Here's what you do :
$.ajax({
type: "GET",
url: "data.csv",
success: function (data) {
var data = Papa.parse(data);
var output = {
"IPv6" : data.data[0][1],
"coordinates" : [data.data[1][5], data.data[1][6]]
} /* -> These are the values you're looking for! */
}
});
Because I can't demo the AJAX (due to cross-domain scripting issues), I'll demo just the success function below!
Demo
var data = '2001:200::,2001:200:ffff:ffff:ffff:ffff:ffff:ffff,'+ "\n" +
'42540528726795050063891204319802818560,42540528806023212578155541913346768895,JP,,,36.0000,138.0000,,0,0'+ "\n\n" +
'2001:208::,2001:208:ffff:ffff:ffff:ffff:ffff:ffff,'+ "\n" +
'42540529360620350178005905068154421248,42540529439848512692270242661698371583,SG,,,1.3667,103.8000,,0,0';
var success = function (data) {
var data = Papa.parse(data);
return output = {
"IPv6" : data.data[0][1],
"coordinates" : [data.data[1][5], data.data[1][6]]
}
}
document.body.innerHTML = '<pre>' + JSON.stringify(success(data), null, 2) + '</pre>';
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.1.2/papaparse.js"></script>

Using values from JSON array

I have an AJAX returning JSON array from PHP.
I have the JSON array successfully returning to the AJAX request, and i am cycling through the results.
Q. How do i use the specific values from the array in this instance?
Currently i can alert the string of the results.
I wish to be able to use the values independently.
The array outputs in a string: {"btn_col_preset_id":"1","btn_col_preset_title":"Pink","btn_col_preset_bg":"#ff66ef","btn_col_preset_text":"#16f3ed"}
The js/json
for (var i in myObject) {
if (myObject.hasOwnProperty(i)) {
//console.log(myObject[i]);
// alert(JSON.stringify(myObject[i]));
val1 = ???; // this is what i am trying to achieve
}
}
Updated
The full Ajax in which i am trying to get a single value based on key. This outputs empty alerts.
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
beforeSend: function() {
},
success: function(data) {
var myObject = data;
// loop over each item
for (var i in myObject) {
if (myObject.hasOwnProperty(i)) {
//console.log(myObject[i]);
// alert(JSON.stringify(myObject[i]));
alert(myObject["btn_col_preset_id"]);
}
}
}
});
Either set
header('Content-type: application/json');
in your php which will tell the javascript to interpret the data as JSON.
Or use
JSON.parse();
in your javascript to convert the string to an object.
First of all, you need to parse the JSON-encoded string then you can use it as an object in Javascript
var data = JSON.parse(result_of_the_request), i;
for(i in data)
{
alert("The item '" + i + "' has a value of '" + data[i] + "'");
}
Note that, if you're using jQuery, there is an awesome shortcut to get the result of the resquest directly as a Javascript object. It's called $.getJSON().

jQuery serialize and validate data

I have the following line returned from serializing data
rl=250&first_name=&surname=&email=&phone=&country_id=1&agency_name=&sitename=
I want to loop through these and check if there is an empty field and if there is then I can throw an error.
I can get the index and element but the element is rl=250 or first_name=
How can I check if the element is set or not. I have also tried using serializeArray() but it returns me [Object, Object, Object, Object, Object, Object, Object, Object] which should have the name and value but I do not know how to access these
You need to split this using '&'. Then you should apply for loop and in that loop you again need to split that string with '=' sign. Then if you get second element of loop as blank, you can throw error
serializeArray is a good way.
https://api.jquery.com/serializeArray/
As you can see, it returns arrays of objects so in your case it is something like tihs:
[
{
rl: 250
},
{
first_name: undefined
}
]
After this you can iterate on the array of the objects with for loop on the values.
I found this function by Jack alan
https://stackoverflow.com/a/16215183/1430587
function deparam(query) {
var pairs, i, keyValuePair, key, value, map = {};
// remove leading question mark if its there
if (query.slice(0, 1) === '?') {
query = query.slice(1);
}
if (query !== '') {
pairs = query.split('&');
for (i = 0; i < pairs.length; i += 1) {
keyValuePair = pairs[i].split('=');
key = decodeURIComponent(keyValuePair[0]);
value = (keyValuePair.length > 1) ? decodeURIComponent(keyValuePair[1]) : undefined;
map[key] = value;
}
}
return map;
}
You could do something like this:
$(document).ready( function(e) {
$("#frm-login").submit(function() {
var DATA = $(this).serializeArray();
len = DATA.length,
dataObj = {};
for (i=0; i<len; i++) { // acceesing data array
dataObj[DATA[i].name] = DATA[i].value;
}
if ( !dataObj['user-id'].trim() || !dataObj['user-pass'].trim() ) { //cheking if empty field
alert('empty');
}else{
alert('full');
}
//console.log(DATA);
$.ajax({
type: "POST",
url: 'user-login-process.php',
data: DATA,
success: function(response){
//alert(response); // show response from the php script.
}
});
return false; // avoid to run the actual submit of the form.
});
}); //document

jQuery AJAX, array not getting serialized

I'm trying to post a multidimensional array using jQuery. I have verified that immediately before sending the array, it contains the contents it is supposed to (by checking specific elements and alerting them).
However, when I send the request, it's sending this:
Array
(
[undefined] =>
)
Here's the whole thing...
var mainArray = new Array();
$(".list").each(function(){
var day = $(this).attr("id");
var order = 1;
$("#" + id + " li").each(function(){
var subArray = new Array();
var id = $(this).attr("id");
subArray["id"] = id;
subArray["order"] = order;
subArray["day"] = day;
mainArray.push(subArray);
order++;
});
});
// This displays what I would expect
alert(mainArray[0]['id']);
alert(mainArray[1]['id']);
alert(mainArray[2]['id']);
alert(mainArray[3]['id']);
// This doesn't work
$.ajax({
type: 'post',
url: 'test2.php',
data: mainArray,
success: function(data) {
$("#test").html(data);
}
});
Any ideas? My understanding is that jQuery is supposed to serialize the array automatically?
Your code is totally wrong!
At first, give your 2-dimensional array some name for example items (or whatever you want). Second, you can't use Array for creating hash (theoretically you can but it's bad and jQuery doesn't understand this), you have to use object literals {} instead of Array, use Array only with numeric keys (use literals [] for creating array instead of new Array). Your code:
var mainArray = [];
$(".list").each(function(){
var day = $(this).attr("id");
var order = 1;
$("#" + id + " li").each(function(){
var subArray = {};
subArray["id"] = $(this).attr("id");
subArray["order"] = order;
subArray["day"] = day;
mainArray.push(subArray);
order++;
});
});
$.ajax({
type: 'post',
url: 'test2.php',
data: { items: mainArray },
success: function(data) {
$("#test").html(data);
}
});
P.S.: you can use $.param (convert js objects into query string) to figure out your mistakes
Stringyfy the data before you send it to the server
Also it's a better practice to send the data as a Map..
Instead of this
data: mainArray,
Try
data: { 'arr': JSON.stringify(mainArray) },

Categories

Resources