Split items separated by commas (,) in Javascript - javascript

My Javascript var contains a 2D array.
If I pop an alert on the the var i get the JSON serialized result, something like:
ID0, DESCRIPTION
I'd like to get each items separated by the , in the value option of the dropdownlist and the other item in the description.
Here's my Javascript code, it would work if split was working correctly but this pops an error because the var doesn't contain a pure string type.
$.ajax(
{
type: "POST",
url: "Projet.aspx/GetDir",
data: "{VP:'" + dd_effort_vp + "',DP:'" + dd_effort_dp + "',Direction:'" + dd_effort_d + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var cars = response.d;
$.each(cars, function(index, value) {
$('#<%= dd_effort_directionp.clientid()%>').append(
$('<option</option>').val(value[value.split(",",0)]).html(value.split(",",1))
}
}
});
I know split doesn't work that way here because of the return value is not a string but you get the result i'd like to achieve, get the first value before the comma has the VALUE of the Dropdownlist and the item after the comma as the HTML text.
Thanks ALOT!

How about value.split(",")[0] instead of value.split(",",0)?

Have you tried value.toString().split(",")?

Related

How can I divide a string into parts in jquery

I have this code below I just need to divide the string into parts in the onSelect parameter of auto complete function
$(function(){
$('#business_category').autoComplete({
minChars: 2,
source: function(term, response){
term = term.toLowerCase();
var countryName = $("select[name=country]").val();
var data_search_term = $("input[name=business_category]").val();
console.log(countryName);
$.ajax({
type: "POST",
url: "ajax/businesses_search_terms_count.php",
data: "countryName=" + countryName + "&searchTerm=" + data_search_term,
dataType: "json",
success: function(resp){
response(resp.data)
}
});
},
onSelect: function(event, term, item) {
console.log("searchedItem: " + term);
var data_search_term = $("input[name=business_category]").val();
$('#total-count').html(data_search_term);
}
});
});
Right now, when user selects any category my output is: (Audio and video => 6,488). But I want an output like this: (Audio and video). So I just want a string with the category field not with count number like => 6,488
As #Donny stated, you can achieve it with pure Javascript. My solution is very similar to his but I just wanted to share a little bit more concise solution using template strings:
const str = "(Audio and video => 6,488)";
console.log(`${str.split("=>")[0].trim()})`);
You can achieve your goal using pure JavaScript with string.split() and string.trim()
var str = "(Audio and video => 6,488)";
var res = str.split("=>")[0]; //Turn string into array splitting by '=>' and get the first element
res = res.trim(); //Remove side spaces
res += ')'; //add ')' to the end of the string
console.log(res); //prints to console '(Audio and video)'

JSON String - more than two parameters - receiving null at servlet

I am passing two JSON objects from jQuery - ajax call to servlet using JSON Stringify. But I am getting null. If I pass one Object I am getting expected data but I'm not able to receive two objects. Please help me to find my mistake.
$.ajax({
url : 'insertserv1',
type: 'POST',
dataType: 'json',
data: JSON.stringify({"test1" :masterdata,"test2" :InspTableArray}),
contentType: 'application/json',
mimeType: 'application/json',
success : function(data) {
alert('Hi');
}
});
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
if (br != null) {
json = br.readLine();
}
System.out.println(json); // getting expected data as {"test1":{"grn":"55555","pono":"888888","row":1},"test2":["Type/,"As ","ok","ok","ok","ok","ok"]}
try {
JSONObject rawdata = new JSONObject(json);
JSONObject datat1 = rawdata.getJSONObject("test1");
JSONObject datat2 = rawdata.getJSONObject("test2");
System.out.println(datat1); // return nulls
System.out.println(datat2); // return nulls
The JSON that is being sent in the InspTableArray is invalid so when you try and parse it in Java it breaks:
{"test1":{"grn":"55555","pono":"888888","row":1},"test2":["Type/,"As ","ok","ok","ok","ok","ok"]}
// Problem is this character here --------------------------^
// which breaks the JSON Array of strings
// The value should be "Type" instead of "Type/
// and is likely causing a SyntaxError: Unexpected token A in JSON at position 66
test2 seems to be an array of strings, apart from the first element which isn't a String and causes the rest of the Array to break and should be:
"test2":["Type","As ","ok","ok","ok","ok","ok"]
// ^------ forward slash replaced with closing double-quotation mark

imitating firebug Net tab

In Firebug net tab, in Response\Json tabs, I can see the value returned from CGI, using ajax:
I want to verify the exact characters values, so I can translate it into readable characters (and in the next step, store my values in the same encoding.)
How can I get this value in Javascript?
I tried to use encodeURI() on the ajax returned response, but I only got some [%EF%BF%BD] (the black-diamond-question-mark)
my JS code:
var jqxhr = $.ajax({
type: "GET",
url: AJAX_CGI_URL,
dataType : 'json',
cache: false,
data: { name: AJAX_PARAMS }
})
. . .
case "P_D":
for(var j = 0; j < varVal.length; j++) {
jj=j+1;
updateWidget("d" + jj, varVal[j]);
var res = encodeURI(varVal[j]);
console.log(jj + ": " + res);
} break;
=>
console log:
GET http://.../cgi-bin/xjgetvar.cgi ...
1: %EF%BF%BD%EF%BF%BD%EF%BF%BD%EF%BF%BD%20%EF%BF%BD%EF%BF%BD%EF%BF%BD
which is actually => %EF%BF%BD %EF%BF%BD %EF%BF%BD %EF%BF%BD %20 %EF%BF%BD %EF%BF%BD %EF%BF%BD
[relates to my previous question - JavaScript encodes Hebrew string
I thought it will be easy to get the values Firebug shows. but it is not trivial :( ]
so my question now is - How can I get the same values Firebug gets ?!

Bad format in JSON response AJAX

I have the follow code, it's call a web service in other PC server.
Data parameters are ok.
"{ ControlId: 'ZAsociated_26037', TaskId: 1495613, UserId: 166396, TBodyId: ''}"
$.ajax({
type: "POST",
cache: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{ ControlId: '" + controlId + "', TaskId: " + taskid + ", UserId: " +
userId + ", TBodyId: '" + $(tbody).attr("id") + "'}",
url: getWSPath() + "/GetZAsociatedResults", // CARGAR AQUI LA DIRECCION DEL WEBSERIVCE
success: function (data) {
if (data != null && data.d != "[]") loadAsociatedTable(controlId, data.d);
$("#loadingImg" + controlId).remove();
},
error: function (xhr, ajaxOptions, thrownError) {
$("#loadingImg" + controlId).remove();
alert("Error al obtener los datos: " +thrownError + "\nCodigo de error: " +xhr.status);
}
});
The error is, that when i have the data.d result of WS, JSON add adicionals "\" chars in string:
The begin of response:
[{\"Nombre del Documento\":\"Indemnizacion/Factura. 22076 - Proveedor - Sin: 38653 Global: No\",\"Estado\":\"Pago finalizado\",
I try to replace "\" to null string but it doesnt work
This AJAX when success call to loadAsociatedTable function and this do:
for (var i = 0; i < $.parseJSON(data).length;i++){
and have an error in $.parseJSON(data).length because don't converter this string to object.
I checked in Chrome and the JSON is ok, without this bar "\", and recognize that like a object, the problem is in IE v.11 only.
Can you Post the complete JSON which will help me to analyze
In meanwhile try this
Using Eval on data.d like eval("{"+data.d+"}");
or JSON.Parse(data.d)
try validate you json here http://jsonlint.com/
The server's JSON response is invalid. Some server programmer has misunderstood JSON double quote escaping and tried to apply it everywhere. Have the server return valid JSON. Most server environments have standard JSON libraries which will construct JSON which is not invalid. The correct JSON is of course just
[{"Nombre del Documento":"Indemnizacion/Factura. 22076 - Proveedor - Sin: 38653 Global: No","Estado":"Pago finalizado", ...
You can try to fix the JSON yourself, by replacing \" with ", which would just be
replace(/\\"/g, '"')
but the problem is that you will also destroy \" sequences representing double quote marks inside string values. That's quite a tricky problem to solve. So the best solution is to get the server to send down correct JSON to start with.
Finally I could solve the problem, I used JSON.parse() instead $.parseJSON(), maybe is JQuery version. AJAX response contains this additionals "\" but when I parse this object, JS convert it without problems.
Thanks for your help!

How to change the delimiters in a javascript string

First of all thanks in advance. I am new to javascript and I am facing an issue with a form that uses javascript to submit values. Everything works great, but the values are submitted as a string delimited by comma, and there is a possibility that the values are submitted have comma on it, so when I explode it on php, I mess up the form input. By example:
Form input 1: Highschool, Year 2
Form input 2: City
So, the resulting string is: Highschool, Year 2, City
and I need it to be: Highschool, Year 2||City
I can explode it on php and use the values, but no clue how to. I would really appreciate any advice.
Here is the javascript code:
function vpb_submit_items()
{
var vpb_items = [];
$.each($('.vpb_item'), function()
{
vpb_items.push($(this).val());
});
if(vpb_items.length == 0 || vpb_items.length == "")
{
vpb_items = "Empty Field";
}
var dataString = "items="+ vpb_items;
$.ajax({
type: "POST",
url: "process.php",
data: ""+dataString+"&date="+date,
Thanks again.
Use Array's join() method:
var dataString = "items="+ vpb_items.join('||');

Categories

Resources