jQuery AJAX, array not getting serialized - javascript

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) },

Related

How do I get the specific part of a URL using jQuery and JavaScript?

I am checking out an order in WordPress via jQuery AJAX. Upon successfully posting, WordPress returns a response to me with a result success value and url value.
I want to get the particular part of this url so I can use the id as an object for my purpose.
This is the structure of the url: http://localhost/mywebsite/checkout/order-received/28564?key=wc_order_5b4dbc6b2f459
This is my current code:
j('.my-checkout').on('submit', function(evt) {
evt.preventDefault();
var billing_customer_type = j("#billing_customer_type").val();
// and so on...
j.ajax({
type: 'POST',
url: 'http://localhost/mywebsite/ajax=checkout',
cache: false,
data: {
'billing_customer_type': billing_customer_type,
// and so on..
},
success: function(result) {
var orderResponseUrl = result.redirect;
j('.order-response-url').html(orderResponseUrl);
// http://localhost/mywebsite/checkout/order-received/28564?key=wc_order_5b4dbc6b2f459
orderResponseUrl.split("/");
console.log(orderResponseUrl[3]);
},
error: function(xhr, status, error) {
console.log(error);
},
complete: function() {}
});
});
The result of my code above is just the the letter "p". I think because it started of the first letter of http and I used the index [3].
Do you know how can I get the specific part of the url that is 28564?
If the URL that you need to interact with is always the same, you can split the returned url at the 'order-received/' portion (which gives an array of everything before that, and everything after it).
Then rather than splitting again on the '?" which is another way of doing it - you can use parseFloat() to get the order number. This works since parseFloat returns all numerical values up to but not including the first non-numerical character ("?").
var urlStr = 'http://localhost/mywebsite/checkout/order-received/28564?key=wc_order_5b4dbc6b2f459';
var orderNumber = parseFloat(urlStr.split('order-received/')[1]);
console.log(orderNumber); //gives 28564
Because when you do orderResponseUrl.split("/"); it does NOT change orderResponseUrl, it creates a new array.
var parts = orderResponseUrl.split("/");
console.log(parts);
if the length is always same then you can use substring function.
var str = "Hello world!";
var res = str.substring(1, 4);
now res contain
console.log(res); // ell
if you do not know the index, you can find like this.
var str = "Hello world, welcome to the universe.";
var n = str.indexOf("welcome");
now n look like
console.log(n); // 13

How Do I Create a $_POST array from textarea input

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

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>

How to extract a single value from an array

I am very new to JavaScript so forgive me if this is a dumb question:
I have this Ajax call:
$.ajax({
type: 'GET',
url: 'product_prices/' + value,
success: function (data) {
console.log('success', data)
}
});
The value "data" produces an array:
success [{"price":"120.00"}]
What I need, is to extract the value of price (the 120) and use it later in an addition.
How do I get this value out?
You can do:
var price = data[0]['price'];
or:
var price = data[0].price;
Either of these work like this: you are accessing the first value in your array named data, and then the field in that value named "price". Assigning it to a variable isn't necessary.
However, you would probably want to do this inside a loop, iterating over all values of data so that, in the case the first element of data isn't what you want, you can still catch it. For example:
data.forEach(function(i) {
console.log(data[i].price);
//do stuff with the value here
});
data has an array of objects with a price property. Access the first object in the array and parse it's price as a number:
parseFloat(data[0].price);
Test it,
You must parse JSON string before using it!
var data = JSON.parse('[{"price":"120.00"}]');
var Price = data[0].price; // 120.00
//OR IF it's Single And not Array
var Price = data.price; // 120.00
Since your response is an array, access the first position, and then access the object property:
data[0].price; //"120.00"
var result = {},
sum = 0;
$.ajax({
type: 'GET',
url: 'product_prices/' + value,
success: function (data) {
result = data[0];
}
});
sum = parseFloat(result.price) + 2.25;

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().

Categories

Resources