How to extract the response from ajax call using js? - javascript

I have a ajax call on my function
js part
_this.ajaxPost(appUrl + "reports/appointment/save", post_str, function(response) {
var res = eval("(" + response + ")");
if (!res.error) {
var data = res.msg;
} else {
if (res.status == "error") {
_this.showPopMsg("error", 'Error when updating db ', res.msg);
}
}
}, function(response) {
alert(response);
var res = eval("(" + response + ")");
_this.showPopMsg("error", 'Updating DB', res.msg);
});
php part
echo json_encode(array("error"=> false, "status"=>"success", "msg"=>$conditions['reg']->result()));
which returns a response like,
{"error":false,"status":"success","msg":[{"name":"dreamhunter","mob_num":"9876543210","email":"afl#thnfgd"}]}
and I'm trying to extract the msg part using js, the msg part contains an array like
[{"name":"dream hunter","mob_num":"9876543210","email":"afl#thnfgd"}]
and here name,mob-num and email are keys and I'm trying to extract their values
I have tried
var res = eval("(" + response + ")");
var data = res.msg;
alert(data[name]);//which is the first key
which is not working. How can I extract this?

Assuming you have the following response:
var x = '{"error":false,"status":"success","msg":[{"name":"dreamhunter","mob_num":"9876543210","email":"afl#thnfgd"}]}'
Using JSON.Parse you can extract the object:
var y = JSON.parse(x);
Now you have an object like this:
{
error:false,
msg: [{
email: "afl#thnfgd"
mob_num: "9876543210"
name: "dreamhunter"
}],
status:"success"
}
To access the properties, such as the email for example, of the first message you can do this:
console.log(y.msg[0].email);
var x = '{"error":false,"status":"success","msg":[{"name":"dreamhunter","mob_num":"9876543210","email":"afl#thnfgd"}]}'
var y = JSON.parse(x);
console.log('msg[0].email: ', y.msg[0].email);

You can view the data using :-
alert(data[0].name);

Use the JSON object methods to handle JSON in javascript.
For instance
var data = JSON.parse('{"error":false,"status":"success","msg":[{"name":"dreamhunter","mob_num":"9876543210","email":"afl#thnfgd"}]}')
alert(data.msg[0].name)

Related

How can I resolve XML Parsing Error: not well-formedLocation?

On load of my page I execute this function
function getConnection() {
$.ajax({
type: "GET",
url: "../webservice/anonymous_PS.asmx/Get",
data: { "PSname": "LISTE_CONNEXTION" },
async : false ,
success: function (response) {
var data = response.getElementsByTagName("NewDataSet")[0]
for (let i = 0; i < data.children.length; i++) {
var c1Nb = $(data.children[i]).find('c1').text()
var c2Nb = $(data.children[i]).find('c2').text()
var c1 = document.getElementById("cs" + c1Nb)
var c2 = document.getElementById("cs" + c2Nb)
var line = $("#l_" + c1Nb + "_" + c2Nb)
}
}
})
}
But when I do that I have this error on Firefox :
XML Parsing Error: not well-formed
Location:
Line Number 1, Column 131:
and on chrome sometimes I have this error :
devtools was disconnected from the page
How can I resolve my issue ?
Try parsing your response, you can use $.parseXML(response) if you want to parse your response to xml or $.parseHTML(response) if you want to parse your response to html.
Once the parsing is done then your getElementsByTagName("NewDataSet")[0] will work and you will not get any error.
The final code will look something like:
var parsedResponse = $.parseXML(response);
var data = parsedResponse.getElementsByTagName("NewDataSet")[0];

API Jive get categories error : Uncaught Passed URI does not match "/places/{uri}": /api/core/v3/places/

i use Jive and i want to get all categories and for each category, i want to create a checkbox for each of them.
Currently, i have my array with all categories, but when i try to create checkbox, it return me this error :
" Uncaught Passed URI does not match "/places/{uri}": /api/core/v3/places/ "
Someone can help me ?
///////////////// function checkbox for each category ////////////////
$("#submit_a_question").click(function(e) {
e.preventDefault();
$("#modal").addClass('is-show');
$("#ideasContainer").height((height + 100) + "px");
resizeIframe();
fieldsPlaceholder(appLang);
var categoriesToShow = categories(placeID);
var container = $('#listCheckboxCategories');
var listCheckboxCategories = $('#listCheckboxCategories');
var CheckboxCreate = $('input />', {type: 'checkbox'});
if(tileConfig.isThereFilterRadios == "Yes"){
$('#ShowCategories').show();
$('#listDropdownCategories').show();
$.each(categoriesToShow.res, function(index, value) {
CheckboxCreate.appendTo(container);
});
}
///////// function to get all categories in an array /////////
function categories(placeID){
var request = osapi.jive.corev3.places.get({
uri : '/api/core/v3/places/' + placeID
});
// var res = [];
request.execute(function(response) {
if (typeof response.error != 'undefined') {
console.log("API call failed");
} else {
console.log(response);
response.getCategories().execute(
function (res){
console.log("cat",res);
});
}
});
}
I was able to execute the call successfully by using "/places/{placeId}" in the URI as below:
osapi.jive.corev3.places.get({uri: '/places/1003'}).execute(function(response) {
console.log(response);
});
For which I have received the place object in the response, as expected:
{ type: "space",
parent: "http://localhost:8080/api/core/v3/places/1000",
placeTopics: Array(0),
displayName: "water-cooler",
iconCss: "jive-icon-space", …}
Are you sure your "placeId" has the correct value? Maybe log the URI you are sending before making the call and check if the format matches the one I have mentioned above. Thanks.

How do I display JSON data to an HTML DOM Element after JSON.parse()?

I have two functions I am using to pull JSON from my server side to then display it to HTML.
The first function that pulls the data from the route handler is successfully pulling the data and parsing it successfully with JSON.parse() and displaying the needed information to the console without issue. I am not having and ajax or route handling issue...
Here is how I am dealing with the JSON first in my function called "projectInfo()":
projInfo = JSON.stringify(data);
console.log("DEBUG DONE WITH CAPTURING project_info DATA: " );
// This console.log() prints the JSON string
// successfully pulled from route handler
// var projInfo is a local string var declared in the scope of
// this first function
console.log("var projInfo: " + projInfo);
// parse JSON data in projInfo and store in string var p
// string var p is a local var declared inside of the scope
// of this function
p = JSON.parse(projInfo);
console.log("Parsed Project JSON: " + p.Project);
// update "Global" pInfo with the value of the JSON data for
// "Project" as needed
pInfo = p;
console.log("What is inside of pInfo???: " + pInfo);
// This last console.log prints [object Object] to console
// How do I pul the value out of this Object?
The second function calls the first function in order to update a global variable with the parsed JSON data that I need to then display the global variable's data to the DOM element that I am trying to display.
Here is how I am trying to update my global var with a JSON Object in my function called "loginFun()":
// Call projectInfo() in order to update Global pInfo
// with the needed project info
projectInfo();
// This console.log() prints nothing...?
console.log("projectInfo var data should be aa2: " + pInfo);
document.getElementById("userBar").style.display = "";
// This is where I try to Display pInfo in the DOM but I only get Undefined...?
document.getElementById("signedinas").innerHTML = "<font face=\"verdana\" size =\"4\" color=\"white\">Logged in as: " + username + " Project: " + pInfo + " </font>";
When I JSON.parse() the data in the first function I run a console.log() statement and I get the needed data to print from a variable local to the function I am getting my JSON with using ajax and I verify that the function is in fact doing what I need so that part is good up until I get the [object Object] output.
I am having issues when I call this function from my second function to then try to use the global variable which should have the data stored.
when I try to use the global variable with the needed data I get an 'undefined'...
I have also tried returning the data that has been parsed in the first function to then storehttps://codepen.io/lopezdp/pen/owKGdJ the value returned into a local variable in the second function but I still get 'undefined'.
If you would like to see the complete code for both functions I have put them on a CodePen to make it easier at:
https://codepen.io/lopezdp/pen/owKGdJ
How can I get my Project Data to display in my DOM element?
EDIT: The JSON Data that I am using looks like this:
{"User":"aa2","Owner":"aa2_role","Status":"locked","Port":"5432","Description":"Transferred from CFS01 on Jun29","Project":"aa2","Server":"localhost"}
I rewrote your login function like this and it worked for me. I also eliminated the projectInfo() function!
var allMn = [];
var tags = [];
var pInfo = '';
function loginFun() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
if (username == "" || password == "") {
alert("Required fields cannot be left blank.");
} else {
$.ajaxSetup({
cache: false
});
$.ajax({
type: 'GET',
url: 'http://139.169.63.170:' + port + '/login/' + username + "zlz" + password,
cache: false,
success: function (data) {
// NEED SUB ROUTINE HERE FOR AJAX CALL DPL
// Make async call to ccdd tool database to get new data
// This collects allMn[] data!!!
getMnJson();
// END SUB ROUTINE HERE
// Checks to make sure user is logged in if not
// the condition redirects user to loginFun()
if (data.search("HTTP ERROR: ") != -1) {
alert("Login Failed.");
document.getElementById('username').value = "";
document.getElementById('password').value = "";
document.getElementById('searchResults').innerHTML = "Login Failed";
document.getElementById('searchRBar').style.display = "";
loginFun();
} else {
login = 1;
// Call projectInfo() in order to update pInfo with the needed project info
//projectInfo();
var projInfo = '';
var p = '';
// Get all Mn Data on startup tp display in DOM -DPL
$.ajax({
type: 'GET',
url: 'http://139.169.63.170:' + port + '/role',
dataType: 'json',
cache: true,
success: function (data) {
// projInfo = JSON.stringify(data);
console.log("DEBUG DONE WITH CAPTURING project_info DATA: " );
// console.log("var projInfo: " + projInfo);
// parse JSON data in projInfo
p = data['Project']; //JSON.parse(projInfo);
console.log("Parsed Project JSON: " + p);
// update "Global" pInfo with the value of the JSON data for "Project" as needed
pInfo = p;
console.log("What is inside of pInfo???: " + pInfo);
document.getElementById("signedinas").innerHTML = "<font face=\"verdana\" size =\"4\" color=\"white\">Logged in as: " + username + " Project: " + pInfo + " </font>";
}
}).fail(function () {
alert("Login Failed.");
document.getElementById('username').value = "";
document.getElementById('password').value = "";
console.log("Error. /role data access Error.");
});
console.log("projectInfo var data should be aa2: " + pInfo);
document.getElementById("userBar").style.display = "";
// Display pInfo in the DOM
// document.getElementById("signedinas").innerHTML = "<font face=\"verdana\" size =\"4\" color=\"white\">Logged in as: " + username + " Project: " + pInfo + " </font>";
$("div.create").children().remove();
//-------------------------------------------------------------------END OF GLOBAL VARIABLES
$.ajaxSetup({
cache: false
});
// get table data from proxy server on port 7071 DPL
// NEED SUB ROUTINE HERE FOR AJAX CALL
// Make call to server-side code to reload JSON data into table from port 7071
pushJsonData();
// END SUB ROUTINE HERE!!!
// getTblJson();
}
}
}).fail(function () {
alert("Login Failed.");
document.getElementById('username').value = "";
document.getElementById('password').value = "";
console.log("Error. Need user Credentials");
});
}
}

$.getJSON() to $.ajax()

I would like to ask how could I convert the following $.getJSON() to $.ajax() please.
I have a set of arrays from var googleApi like this:
Array [Object, Object, Object, Object, Object]
// if stringified
[{"id":"0","name":"user1","type":"mf","message":"bonjour user1"},
{"id":"1","name":"user2","type":"ff","message":"hello user2"},
{"id":"2","name":"user3","type":"mm","message":"konnichiwa user3"},
{"id":"3","name":"user4","type":"mf","message":"ni hao user4"},
{"id":"4","name":"user5","type":"ff","message":"high 5! user5"}]}
I would like to ask how could I identify if the value of a declared variable (eg. content with the value of user1) is the same as a value within the list of name keys in the array?
Below is my attempt and you might find my full code in $.getJSON() here:
$.getJSON():
var googleApi = 'https://api.com/url_here';
$.getJSON(googleApi, function(json){
console.log(JSON.stringify(json));
var item = json.result.find(function(e){
return e.name == content;
}) || json.result[0];
console.log("PRINT ID: " + item.id);
var name = item.name || content;
$('#nameText').text(name);
console.log("Name: " + name);
});
Below is my attempt on $.ajax() but I got an error of "TypeError: data.result is undefined";I have also tried using $(this) to replace data.result but without luck... it would be very nice if someone could identify what have I done wrong please:
var googleApi = "https://sheetsu.com/apis/v1.0/f924526c";
var googleKey = "0123456789";
var googleSecret = "987654321";
var data = [];
$.ajax({
url: googleApi,
headers: {
"Authorization": "Basic " + btoa(googleKey + ":" + googleSecret)
},
data: JSON.stringify(data),
dataType: 'json',
type: 'GET',
success: function(data) {
console.log(data);
var item = data.result.find(function(e){
return e.name == content;
}) || data.result[0];
console.log("PRINT ID: " + item.id);
var name = item.name || content;
$('#nameText').text(name);
console.log("Name: " + name);
});
Merci beaucoup :))) x
...how could I identify if the value of a declared
variable ... is the same as a value
within the list of name keys in the array?
As per your provided response object you could iterate through it and check the values against your variable content:
var content = "user1";
$.each(response, function(i, v) {
if (v.name == content) {
console.log(v.name);
}
});
Example Fiddle
As for the second part of your question:
but I got an error of "TypeError: data.result is undefined";
The reason you may be getting your error is because find is expecting a jQuery object, you have received a JSON object back from your endpoint, so using dot notation as above will should work as well:
success: function(data) {
$.each(data, function(i, v) {
if (v.name == content) {
console.log(v.name);
}
});
}
You can see the answer to this question for a bunch of awesome information on how to access / proccess objects.
Also note your success callback in your code above is not closed, which will create errors.
function getID(name){
$.each(data,function(key,value){ //value = object.value (name)
$.each(value,function(key1,value1){ //value1 = user name (actual names in array)
if(value1 == content){
console.log(value.id);
var name = value.name;
$('#nameText').text(name);
console.log("Name: " + name);
return;
}
});
});
}
getID(data);
return false;

Get json value from response

{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}
If I alert the response data I see the above, how do I access the id value?
My controller returns like this:
return Json(
new {
id = indicationBase.ID
}
);
In my ajax success I have this:
success: function(data) {
var id = data.id.toString();
}
It says data.id is undefined.
If response is in json and not a string then
alert(response.id);
or
alert(response['id']);
otherwise
var response = JSON.parse('{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}');
response.id ; //# => 2231f87c-a62c-4c2c-8f5d-b76d11942301
Normally you could access it by its property name:
var foo = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"};
alert(foo.id);
or perhaps you've got a JSON string that needs to be turned into an object:
var foo = jQuery.parseJSON(data);
alert(foo.id);
http://api.jquery.com/jQuery.parseJSON/
Use safely-turning-a-json-string-into-an-object
var jsonString = '{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';
var jsonObject = (new Function("return " + jsonString))();
alert(jsonObject.id);
var results = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}
console.log(results.id)
=>2231f87c-a62c-4c2c-8f5d-b76d11942301
results is now an object.
If the response is in json then it would be like:
alert(response.id);
Otherwise
var str='{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';

Categories

Resources