How to extract a single value from an array - javascript

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;

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 get values from multidimensionnal table in javascript?

i have an array of urls. I insert into it values like this :
var replacementArray=[];
function insert(arr,url, shorturl) {
arr.push({
url: url,
shorturl: shorturl
});
}
This is an example of one such URL array:
replacementArray:{
[url:"tuto.com", shorturl:"xfm1")],
[url:"youtube.com", shorturl:"xfm2")],
[url:"google.com",shorturl:"xfm3"]}
I have to compare the shorturl of this array with a string. If the strings match then i retrieve the url. Here is my first attempt at doing this :
var chaine="xfm1";//this is an example
for(var j=0;j<replacementArray.length;j++)
if (replacementArray[j][shorturl]==chaine){
var url= replacementArray[url];
}
This seems to not be working. Why is that?
Associative arrays with arbitrary keys don't exist in javascript
You can have data that works as an associative array, but then you need to use an object to store the keys.
The example data you provided is not valid JS. It is an object of arrays instead of being an array of objects. For your function to work as expected, the data
needs to be in the following format:
[
{
url: 'tuto.com',
shorturl: 'xfm1'
},
{
url: 'youtube.com',
shorturl: 'xfm2'
},
// etc...
]
The [] is for creating an array, which will have numeric indexes only.
The {} creates objects that can store key-value pairs like an associative array in other languages.
So in your function you can loop through the array indexes by incrementing i and access the values associated with your keys using replacementArray[i].shorturl or replacementArray[i]['shorturl'] (notice the string) - the way you do it is up to your preference, they both work the same.
Hope this helps!
var arr=[];
function insert(arr,url, shorturl) {
arr.push({
url: url,
shorturl: shorturl
});
}
insert(arr,"google.com", "xfm.io1");
insert(arr,"gogle.com", "xfm.io2");
insert(arr,"gole.com", "xfm.io3");
function getUrl(yourVariable){ //chaine
for(var j=0;j<arr.length;j++)
if (arr[j].shorturl == chaine){
return arr[j].url;
}
return null;//not found yourVariable
}
var chaine= "xfm.io1"; //your Short URL
console.log(getUrl(chaine)); //testing the function
First of all you given: (which is not an acceptable data structure)
replacementArray:{
[url:"tuto.com", shorturl:"xfm1")],
[url:"youtube.com", shorturl:"xfm2")],
[url:"google.com",shorturl:"xfm3"]}
which must be like this: (array of objects)
replacementArray:[
{url:"tuto.com", shorturl:"xfm1"},
{url:"youtube.com", shorturl:"xfm2"},
{url:"google.com",shorturl:"xfm3"}]
Then to get shortUrl code will be like
function getUrl(yourVariable){ //chaine
for(var j=0;j<replacementArray.length;j++)
if (replacementArray[j].shorturl == chaine){
return replacementArray[j].url;
}
return null;//not found yourVariable
}
Read over these corrections/suggestions:
As others have mentioned, you should create an array of objects, instead of an object with arrays
Reference the property 'shorturl' either using array syntax (i.e. replacementArray[j]['shorturl']) or dot notation (i.e. replacementArray[j].shorturl). If you use array syntax then the property needs to be in a string literal (unless you create a variable to represent the field - e.g. var shorturl = 'shorturl';).
var replacementArray = [];
function insert(arr, url, shorturl) {
arr.push({
url: url,
shorturl: shorturl
});
}
//utilize the function declared above
insert(replacementArray ,"tuto.com", "xfm1");
insert(replacementArray, "youtube.com", "xfm2");
insert(replacementArray, "google.com", "xfm3");
var chaine = "xfm1"; //this is an example
var url; //declare url here so it won't be undefined if no url is found in the array
for (var j = 0; j < replacementArray.length; j++) {
if (replacementArray[j]['shorturl'] == chaine) {
//need to reference replacementArray[j] instead of replacementArray['url']
url = replacementArray[j]['url'];
}
}
console.log('url: ',url);
Consider using Array.prototype.find() or a similar functional-style method (e.g. filter() if you wanted to find multiple values) to determine the site with the matching shorturl value. That way you don't have to worry about creating and incrementing the iterator variable (i.e. j) and using it to reference elements in the array. For more information, try these exercises about functional programming in JS.
var replacementArray = [];
function insert(arr, url, shorturl) {
arr.push({
url: url,
shorturl: shorturl
});
}
//utilize the function declared above
insert(replacementArray ,"tuto.com", "xfm1");
insert(replacementArray, "youtube.com", "xfm2");
insert(replacementArray, "google.com", "xfm3");
var chaine = "xfm1"; //this is an example
var foundSite = replacementArray.find(function(site) {
return (site.shorturl == chaine);
});
if (foundSite) { //if we did find a matching site
var url = foundSite.url;
console.log('url: ',url);
}
Try this in your 'for' loop:
if(replacementArray[j].shorturl == chaine){
// Do stuff here...
}
With [shorturl], you are accessing a property name based on the value of shorturl, which is not defined.

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

Create no. of elements in an array equivalent to an user's input in jquery

I want to create an array using jquery where the no. of elements in it depends on a number enter by an user. For example; If an user enters 5 then the array should contain 5 elements as 0,1,2,3,4.
This is what I have been trying so far ....
function loadPage(id, id2, id3){
var hs= document.getElementById(id).value;
var selected= document.getElementById(id2).value;
var distid = document.getElementById(id3).value;
var ui = hs+selected;
alert(ui);
var res;
var valArray = [];
$.ajax({
type:"POST",
url:"DynaServlet",
data:{ui:ui},
datatype: "text",
success:function(result){
res = result;
alert(res);
valArray.push(res);
alert(valArray[0] + "array");
}
});
The loadPage() appends ids of two elements which forms a unique id and through a java servlet a property file is been searched and the id's corresponding value is received. Depending on this value I want to create an array with no. of elements equivalent to the value received.

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