This is what I'm doing:
function AddSupervisor()
{
var employeeID = $('#ID').val();
var supervisorId = $('#SupervisorId').val();
var supervisors = '';
if (supervisorId > 0)
{
$.ajax({
url: '#Url.Action("AddSupervisor", "Contact")',
type: 'GET',
dataType: 'json',
data: { EmployeeID: employeeID, SupervisorID: supervisorId },
success: function(data) {
supervisors = data;
$('#divSupervisorList').text(supervisors.replace(",", "<br />"));
},
error: function(data) {
}
});
}
}
This is the error:
Uncaught TypeError: supervisors.replace is not a function
If I do this:
$('#divSupervisorList').text(data);
The the result on screen is this:
John Foo, Jane Bar
What I want is:
John Foo
Jane Bar
But I'm having trouble replacing the , with a <br />. At first I tried:
$('#divSupervisorList').text(data.replace(",", "<br />"));
And when that didn't work, I went to using a string that is declared before the ajax call. I also tried using .split() but got the same error.
Not sure what I'm doing wrong.
UPDATE:
As many have pointed out, my return data is not a string, but an object:
(4) ["Adam Brown", "Karl Walser", "Jeremy Smith", "Nathan Graham"]
0 : "Adam Brown"
1 : "Karl Walser"
2 : "Jeremy Smith"
3 : "Nathan Graham"
So, now I gotta figure out how to split this array into a string :-)
My guess is that the data param is actually an array, not a string, and you're seeing it with commas only because JS is sneakily stringifying it that way. You could combine them in a string using the join method for arrays:
supervisors.join('<br />')
However, if you try to use "<br />" in jQuery's text function, it will get escaped. You can use the html function instead. So,
$('#divSupervisorList').html(supervisors.join('<br />'));
The data you are having in response is a Json and not a string.
function AddSupervisor()
{
var employeeID = $('#ID').val();
var supervisorId = $('#SupervisorId').val();
var supervisors = '';
if (supervisorId > 0)
{
$.ajax({
url: '#Url.Action("AddSupervisor", "Contact")',
type: 'GET',
dataType: 'json',
data: { EmployeeID: employeeID, SupervisorID: supervisorId },
success: function(data) {
supervisors =JSON.stringify( data);
$('#divSupervisorList').text(supervisors.replace(",", "<br />"));
},
error: function(data) {
}
});
}
}
Read more:. [https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify].
To replace commas inside each member of your array, you need to map .replace() on the array values:
let result = data.map(function(o){return o.replace(',','<br />')});
To join the members of the array, separating them with a <br />, you need .join():
let result = data.join('<br />');
Note there are no actual commas separating the array members, that's just a conventional way of displaying array values so humans can read and understand them, but there's nothing to replace. All you need to do is join the members with the separator of your choice (<br />) which, by default, is a comma.
So this would also give you the same result:
let result = data.join().replace(',','<br />');
... because .join() would glue the strings using , and .replace() would replace them with <br />s.
According to the jQuery docs:
[dataType is] "json": Evaluates the response as JSON and returns a JavaScript object
So your data is actually an object. You need to access the relevant string property, e.g. data.supervisors.replace(...) - depending on your object model.
I recommend adding a console.log(data) call to your success callback and checking the developer console in your browser by pressing F12 to investigate the source of your issue.
Update: The output of above call to console.log hints at data being an array. Thus, you need to replace
$('#divSupervisorList').text(data.replace(",", "<br />"));
with
$('#divSupervisorList').html(data.join("<br />"));
Related
I want to receive the value thought iterator, when I use
$('#someModal').find('input[name=nameProBangHHModal]').val(data[0].TenNhanQuyCach);
it works as expected.
But when I use an iterator, the return shows [object Object].TenNhanQuyCach - not the data returned.
I try to search for other topic but I'm stuck on this. How to get the data returned in array[data[0]] with the value from the iterator method?
Thank you for your time!
$.ajax({
url: 'someurl to retrive data',
type: 'POST',
data: {id:id},
success: function(data,status) {
var tenCot = ['nameProBangHHModal','valueBangHHModal',];
var tenCotTrongCsdl = ['TenNhanQuyCach','DonViTinh',];
console.log(tenCotTrongCsdl[0]);
for (i=0;i <= tenCot.length - 1;i++) {
$('#someModal').find('input[name="' + tenCot[i] + '"]').val(data[0]+'.'+tenCotTrongCsdl[i]');
}
oh i find out the answer after search topic for array: this one: How can I access and process nested objects, arrays or JSON?.
and find out that need to use [] for variable, not the ".".
this one work for me:
$('#someModal').find('input[name="' + tenCot[i] + '"]').val(data[0][tenCotTrongCsdl[i]]);
I'm only posting relevant code here. I'm trying to access an array in a json array. How do I access an array inside an array?
So this is the code serverside :
$scriptfull = array();
while($r = mysqli_fetch_assoc($resultstmt_scriptfull)) {
$scriptfull[] = $r;
}
$resulterr = array('message' => 'Success',
'fullscript'=>$scriptfull);
header('Content-Type: application/json');
echo json_encode($resulterr);
I know how to access JSON array in Javascript. The problem I do not know how to access a base object that is itself an array within a JSON array.
When I do :
success: function(output)
{
console.log(output.fullscript);
}
I see result in console
(1)[...]
0:{...}
scriptAA1: "a1"
scriptAA10: "a10"
scriptAA2: "a2"
scriptAA3: "a3"
But nothing prints in the HTML if I try
success: function(output)
{
$('.scriptview').html(output.fullscript);
}
I tried accessing it using below code but nothing prints:
success: function(output)
{
$('.scriptview').html(output.fullscript[1]);
}
What you are doing is trying to print a javascript array of objects at html which of course does not make sense and that why nothing is printed. You can either print the javascript array as a string (which probably is not what you want) like this:
$('.scriptview').html(JSON.stringify(output.fullscript));
I think you should explain better what exactly you are trying to print to html.
Edit:
As I understood you want something like what you are getting in your console. For something like this, the code below will do:
var outputString = '';
output.fullscript.forEach(function(object, index){
outputString += '<br> Object with index: ' + index + '<br>';
for (var prop in object){
outputString += 'Property ' + prop + ': ' + object[prop] + '<br>';
}
});
$('.scriptview').html(outputString);
Since you are trying to output the result as a string, you can use
success: function(output)
{
$('.scriptview').html(JSON.stringify(output.fullscript));
}
Update1
If you want the result formatted with whitespaces, the 3rd argument of the stringify method does that:
success: function(output)
{
$('.scriptview').html(JSON.stringify(output.fullscript, null, '\t'));
}
Update2
A more shorter, readable and efficient way is to just display using the jQuery text method instead of html:
success: function(output)
{
$('.scriptview').text(JSON.stringify(output.fullscript, null, '\t'));
}
This looks more tidy...
I'm trying to send object array to node.
If i'm sending it without stringify, i'm getting an array with the same length that i sent, but empty (["", ""]);
if i send it with JSON.stringify , this it the result:
{'[{"itemNumber":"13544","currentShelf":"1A1","amount":"1","newShelf":"","actionType":"in","whareHouse":"Main"},{"itemNumber":"13544","currentShelf":"1B1","amount":"1","newShelf":"","actionType":"in", "whareHouse":"Main"}]': '' }
This is how i'm sending it:
for (var i=1; i<=m; i++){
itemIdTemp= document.getElementById("itemIdShell"+i).value;
shellTemp= document.getElementById("id_shell"+i).value.toUpperCase();
newShellTemp= document.getElementById("id_shell_new"+i).value.toUpperCase();
shellAmountTemp = document.getElementById("amountShell"+i).value;
itemAmount=0;
let itemData={
itemNumber:itemIdTemp,
currentShelf:shellTemp,
amount:shellAmountTemp,
newShell:newShellTemp,
actionType:direction,
whareHouse:"Main",
};
console.log(itemData);
itemsObject.push(itemData);
}
console.log(itemsObject);
$.post('/itemShell/updateMulti',
JSON.stringify(itemsObject),
function(data){
console.log(data);
});
The object contain a string of the array and i can't get it.
I tried Json.Parse(), it won't work in this case.
any suggestions?
Have a look at this example code
const jsObjectArray = [
{name: "Homer", age:56 },
{name: "Marge", age:50 },
];
const buf = JSON.stringify(jsObjectArray);
console.log("Stringified object: "+buf);
//
// Now convert it back to an object
//
const newObject = JSON.parse(buf);
console.log("Reconstituted object: "+newObject);
It's in this codepen too:
https://codepen.io/mikkel/pen/KRayye
I found the problem.
It must be declare as JSON type when post to Node, so u need to use ajax:
$.ajax({
url: '/itemShell/updateMulti',
type:"POST",
data:JSON.stringify(dataTosend),
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){}
}
and i also change it to object type like this:
dataToSend={dataArr:itemsObject}
So in node it's appearing as array
My Guy work a little bit on the string before sending it
First get the string the stringify is returning
var json_string = JSON.stringify(itemsObject);
var string = json_string.replace("'", "\'");
string = '{\'[{"itemNumber":"13544","currentShelf":"1A1","amount":"1",
"newShelf":"","actionType":"in","whareHouse":"Main"},
{"itemNumber":"13544","currentShelf":"1B1","amount":"1",
"newShelf":"","actionType":"in", "whareHouse":"Main"}]\': \'\' }';
first_str = string.split("': "); // remove the last useless chars
second = first_str[0].substring(2, first_str[0].length); // remove the first two chars
$.post('/itemShell/updateMulti', second,
function(data){
console.log(data);
});
the second should have the correct string.
GOODLUCK
I have the following JSON object data returned from my apicontroller :
[
{"id":2,"text":"PROGRAMME","parent":null},
{"id":3,"text":"STAGE","parent":2},
{"id":4,"text":"INFRA","parent":2},
{"id":5,"text":"SYSTEM","parent":3},
{"id":6,"text":"STOCK","parent":3},
{"id":7,"text":"DPT","parent":3},
{"id":9,"text":"EXTERNAL","parent":null}
]
I want to replace "parent":null with "parent":'"#"'
I have tried the code below, but it is only replacing the first occurrence of "parent":null. How can I replace all "parent":null entries?
$(document).ready(function () {
$.ajax({
url: "http://localhost:37994/api/EPStructures2/",
type: "Get",
success: function (data) {
var old = JSON.stringify(data).replace(null, "'#'"); //convert to JSON string
var new = JSON.parse(old); //convert back to array
},
error: function (msg) { alert(msg); }
});
});
Thanks,
You need to make the replace global:
var old = JSON.stringify(data).replace(/null/g, '"#"'); //convert to JSON string
var newArray = JSON.parse(old); //convert back to array
This way it will continue to replace nulls until it reaches the end
Regex docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Also, as a side note, you should avoid using new as a variable name as it is a reserved word in javascript and most browsers will not allow you to use it
#JonathanCrowe's answer is correct for regex, but is that the right choice here? Particularly if you have many items, you'd be much better off modifying the parsed object, rather than running it through JSON.stringify for a regex solution:
data.forEach(function(record) {
if (record.parent === null) {
record.parent = "#";
}
});
In addition to being faster, this won't accidentally replace other nulls you want to keep, or mess up a record like { text: "Denullification Program"}.
I have found several posts similar to this topic but nothing I have tried has actually worked. My question is simple and should be easy to answer. My return json object will have one key and one value. For my code below, the alert shows "[{"DISCOUNT":1}]" and all I am trying to do is parse out the "1" and display it. Ultimately, I want to plug that value into a variable and use for multiplication, but I can't even get the darn number to display by itself. My code is below:
function codeMatchTest() {
if ($('#dbReturnString').val() == '') {
alert("Please enter a discount code.");
} else {
$.ajax({
type: "POST",
url: "PROMO.svc/MatchCode",
contentType: "application/json",
dataType: "json",
data: JSON.stringify({ codeInput: $('#dbReturnString').val().toLowerCase() }),
success: function (json) {
alert(json.d);
/*alert (json.d.discount); // getting "undefined"
$.each(json.d, function (key, value) {
var discount = value;
});
alert("Success: " + discount); //getting "undefined" */
},
error: function () {
alert("There was an error with your request.");
}
});
}
}
I have found no good references on how to actually use the data in a json object. My json object will only consist of a single key and value and I will only ever need to use the value.
Also, I have tried several iteration using $.each and none work. Based on the jquery documentation, it should be very easy but I am having not luck.
If your alert is showing "[{"DISCOUNT":1}]" that means you have an object within an array.
try alert(json.d[0].DISCOUNT);
JSON parsed objects are case sensivetive, plus its seems that json.d contains a string (wich seems to be in json) rather than an object. Try:
var discount = JSON.parse(json.d);
discount = discount[0].DISCOUNT;
success: function(json) {
alert(json.d[0]["DISCOUNT"]);
}
First comment on your code, you are reinventing what jQuery does.
data: JSON.stringify({ codeInput: $('#dbReturnString').val().toLowerCase() }),
It should just be
data: { codeInput: $('#dbReturnString').val().toLowerCase() },
Now to get the data it is simple, you are returning an array with an object in it.
Let us look at it as a regular variable and not an Ajaqx call.
var json = [{"DISCOUNT":1}];
So you got an array? How do you get the object inside of it? You reference the index. Since you said there will only be one index being returned, than use [0] to access it.
success: function (json) {
alert(json[0].DISCOUNT);
To access the first item from the json you may use
alert(json.d[0].DISCOUNT);
Because json.d is an array and it contains one object which is 0 index. So, json.d[0] will select the first item/object from the array and using .DISCOUNT you can access the object's property. It's also possible to access the property like
alert(json.d[0]["DISCOUNT"]);
Try this way
You can use JSON.parse(json.d) / json.d
var data = json.d;
for(i=0;i<data.length;i++) {
alert(data[i].fieldname);
}