javascript variable name replacing actual value - javascript

I have a javascript function ...
function check_val(name, cat)
{
alert(cat);
var val = name.indexOf('[');
if (val == -1){
//$('input[type="checkbox"][value='+ name + ']')[0].click()
val = '"' + name + '"'
type = "'" + cat + "'"
$.get(url,{'ajaxtype':'content', type : val}, function(data{$('#search_container').html(data);$('#rotator').hide();});
}
}
when i call this function with argument say check_val('xyz','pqr')
The problem is when I check the request.get parameter I am getting
<QueryDict: {u'type': [u'"xyz"'], u'ajaxtype': [u'content']}>
instead of
<QueryDict: {u'pqr': [u'"xyz"'], u'ajaxtype': [u'content']}>

Build the object beforehand and use array subscript syntax:
var requestData = { 'ajaxtype': 'content' };
requestData[type] = val;
$.get(url, requestData,
function(data{$('#search_container').html(data);$('#rotator').hide();});

Instead of {'ajaxtype':'content', type : val} try {'ajaxtype':'content', "'" + cat + "'" : val}.
This way JS should know that it's not key name but variable.

Related

Laravel validation find input name with JQuery using dot array syntax

How can I find in JQuery input by name, if I have dot array syntax from Laravel?
Input example:
<input type="text" name="Payments[0][1][Amount]">
<input type="text" name="Reservations[0][Date]">
Laravel validation response from ajax request:
errors: {
Payments.0.1.Amount: "Field is required",
Reservations.0.Date: "Field should be date"
}
Problem: How can I looping through errors array in javascript access input names, if I only have array dot names?
For example, transform Payments.0.1.Amount to Payments[0][1][Amount], or Reservations.0.Date to Reservations[0][Date]
for (const [key, value] of Object.entries(errors)) {
key = somehowParseDotInputToArray(key); // how? :)
$('#app input[name="' + key + '"]').append( '<p class="error">'+ value +'</p>' );
}
Have allready found solution, maybe someone also helps :)
function DotArrayToJs(str){
var splittedStr = str.split('.');
return splittedStr.length == 1 ? str : (splittedStr[0] + '[' + splittedStr.splice(1).join('][') + ']');
}
Simply split the name in an error object from . . Using var $nameArr = name.split('.');
Suppose name = Reservations.0.Date it will be like
let nameArr = ['Reservations','0','Date']
then make name as you want so
var newName = $nameArr[0] + '['+ $nameArr[1] +']' + '[' +$nameArr[2] + ']';
newName will look like Reservations[0][Date]
loop this process for all name variable and make new error object.
Juste in case someone has multi-level arrays
function getFieldnameFromLaravelDotName(laravelDotName) {
let parts = laravelDotName.split(".");
let fieldName = "";
let prefix = "";
let suffix = "";
parts.forEach((part, i) => {
if (fieldName != "") {
prefix = "[";
suffix = "]";
}
fieldName += prefix + part + suffix;
});
return fieldName;
}
console.log(getFieldnameFromLaravelDotName("noDotInThis"));
console.log(getFieldnameFromLaravelDotName("one.level"));
console.log(getFieldnameFromLaravelDotName("many.level.array.plop"));

javascript - creating URI string from objects

I have the following variables in javascript
var domain= http://example.com/api/v1/purchases/get_purchases.json?
var header = 'df0a96ddbe1ada9fda4b1ed9b02cf67c'
var params = {
search:{
status_eq: 'frozen',
email_eq: 'a#a.com',
phone_number_eq: ''
}
}
var api_string = domain + header + params;
I need output of api_string to be:
http://example.com/api/v1/purchases/get_purchases.json?headers%5B_token%5D=df0a96ddbe1ada9fda4b1ed9b02cf67c&search%5Bemail_eq%5D=a#a.com&search%5Bphone_number_eq%5D=12345&search%5Bstatus_eq%5D=frozen
I tried JSON.stringify, encodeURI, encodeURIComponent but it doesnt work as expected.
I need to use this api_string in fetch function of react-native.
You could use a serializing function, like so:
serialize = function(obj, prefix) {
var str = [], p;
for(p in obj) {
if (obj.hasOwnProperty(p)) {
var k = prefix ? prefix + "[" + p + "]" : p, v = obj[p];
str.push((v !== null && typeof v === "object") ?
serialize(v, k) :
encodeURIComponent(k) + "=" + encodeURIComponent(v));
}
}
return str.join("&");
}
console.log(serialize(params));
Gives:
search%5Bstatus_eq%5D=frozen&search%5Bemail_eq%5D=a%40a.com&search%5Bphone_number_eq%5D=`
Good news, string concatination can be done with just the + operator. So you can do something like this
let result = domain + "headers%5B_token%5D=" + header + "&search%5Bemail_eq%5D=" + params.search.eqmail_eq
(obviously extend this for the rest of the parameters, assuming you only have those three params ever)
Have you tried using the npm package url ?
This is an example of how it works:
const url = require('url')
let my_url = url.format({
hostname: "mydomain.com",
protocol: "http",
query: {status_eq: 'frozen', email_eq: 'a#a.com',},
pathname: '/my/path'
})
here is the documentation if you need to know more about how it works.
WARNING
url.format takes in an object of the parameters you want to send to the server. Make sure that if one of the parameters you want to pass is an object you JSON.stringify it before adding it to the query. Here is a stackoverflow question that explains it.

JavaScript get Objects property

Hello guys I've web page which have a lot of scripts, I need to get one by it's name. for e.g 'data'. I need to convert data from this script to one string.
Script is the following:
<script>data = [{'Id': '12344567', 'name': 'TestName','Amount': '1066.00', 'NumberTax': '34.00','tranasactionNumber':'139', 'otherInfo': [{'sku': 'ET|Adult','name': 'Test','category': 'Normal','price': '1032.0', 'quantity':'3'}]}];</script>
This data has array with some elements and another array inside.
Using my script I can only get info and create string with String elements from my data, but how can I get elements from inner array?
var json = '[{';
for (var i in data[0]) {
console.log('type of data[0][i] = ' + typeof data[0][i]);
if (typeof data[0][i] === 'string') {
json = json + '\'' + i + '\'' + ': ' + '\'' + data[0][i] + '\', ';
console.log(i);
console.log(data[0][i])
} else {
//Get infro from inner array
}
}
json = json + '}]';
console.log(json);
Try JSON.stringify(data) to convert object to string instead of your function.
To access the object inside the array you can use the following code:
var obj = data[0]['otherInfo'][0];
You can then use the same code you have above to loop over it and append its elements. If I understand correctly that if what you wish to do.

jquery get value by variable name

I have a variable with jsonData in my page:
JSON_Values=[
{"ID":"1","Name":"MyName1","Selector":"S1"},
{"ID":"2","Name":"MyName2","Selector":"S2"}
]
The name JSON_Values can change so I have receive a variable that holds the name of the JSON_Values:
function useJSONData(nameOfVariable, filter) {
//How to access the Data inside of JSON_Values here???
//Value of nameOfVariable is correctly set to JSON_VALUES
var myJSONData = $(nameOfVariable);
jq.grep(myJSONData, function (n, i) {
return n.Selector === filter
});
}
Can someone provide me any help?
If nameOfVariable is in global scope (which you should avoid), you can use
window[nameOfVariable]
or if in object scope:
this[nameOfVariable]
You can accessing the json data like so: var id = myJSONData[0]["ID"]
You can loop through if you need to do something for each item.
Here's a little example: Hope its helpful.
function useJSONData(nameOfVariable, filter) {
//How to access the Data inside of JSON_Values here???
//Value of nameOfVariable is correctly set to JSON_VALUES
var myJSONData = $(nameOfVariable);
$.each( myJSONData, function( index, value ){
var id = myJSONData[index]["ID"]
var name = myJSONData[index]["Name"]
var selector = myJSONData[index]["Selector"]
var result = "<p>" + id + " | " + name + " | " + selector + "</p> <br>"
$("#output").append(result);
//value("<p>" + id + " | " + name + " | " + selector + "</p> <br />");
});
}
JSON_Values=[
{"ID":"1","Name":"MyName1","Selector":"S1"},
{"ID":"2","Name":"MyName2","Selector":"S2"}
]
useJSONData(JSON_Values);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="output"></div>

Passing multiple checkbox values in AJAX call

I use a ternary operator to check which checkboxes in a form have been selected. If a value has been selected, I affix the name-value pair to a query string which is then passed in an AJAX call. If not, I attach a name with an empty string value.
It works fine, I'm just wondering if there's a more compact/elegant way to do this as it seems somewhat verbose. I'm wondering if it's possible to use a for loop. The reason I'm not sure if this would work is it would involve dynamically assigning variable names within the loop based on the index.
var fields = $('input[name="apn"]').serializeArray();
var apn1 = fields[0] ? fields[0]["value"] : ''
query += '&apn1=' + apn1;
var apn2 = fields[1] ? fields[1]["value"] : ''
query += '&apn2=' + apn2;
var apn3 = fields[2] ? fields[2]["value"] : ''
query += '&apn3=' + apn3;
var apn4 = fields[3] ? fields[3]["value"] : ''
query += '&apn4=' + apn4;
var apn5 = fields[4] ? fields[4]["value"] : ''
query += '&apn5=' + apn5;
...
Map the values and indices to an array of objects, and just pass that directly to $.ajax, jQuery will use $.param on it for you :
var fields = $.map($('input[name="apn"]'), function(el, i) {
var o = {};
o['apn' + i] = el.value;
return o;
});
If its just checkboxes:
$('input[name="apn"]').each(function (i, el) {
if($(el).is(':checked')) {
query += '&apn'+i+'=' + el.value;
}
});
You can simply serialize the form:
var query = $("#FormId").serialize();

Categories