getting string from object - javascript

I am having a problem with this code, could someone help me out?
<script type="text/javascript">
$(document).ready(function()
{
$obj = $.get('getSesion.php',function(data){ } );
//$dato=JSON.stringify(obj);
//$dato=dojo.toJson(obj);
alert($obj);
if($obj != 'NULL')
{
$('#apDiv7').load('logeado.php');
}else{
$('#apDiv7').load('deslogeado.php');
}
}
);
</script>
The problem is that from $obj I get [object Object]. I searched how to convert it but I had no success.
MORE DETAILS. From data I can get a number (0-infinite) or the string NULL. Depend on what value I get, in apDiv7 I will load login window or a window's user connected.
I tried
var data =$obj.d;
but i get "undefined" string
Console log
http://imageshack.com/a/img46/4004/ufgv.jpg
Solution for this case:
var msg = $.ajax({type: "GET", url: "getSesion.php", async: false}).responseText;

.get is an async call, so you should be doing this logic in the callback:
$.get('getSesion.php',function(data) {
console.log(data);
});
Always use console.log so you can actually expand the complex object. Then simply reference the property names of the data response object.

Related

Passing data from javascript to PHP via POST not working

Im trying to send an array, populated using javascript on client-side, to a php file in the backend.
MAIN.JS
var list = iterateItems();
_ajax("https://127.0.0.1/prog1/final/class/ticket.php", list)
.done(function(list){});
});
function _ajax(url,data) {
var ajax = $.ajax({
type : "POST",
datatype : "string",
url : url,
data : data
})
return ajax;
}
function iterateItems() {
// array is an array populated in this function, returned to be sent to ticket.php
return JSON.stringify( array );
};
TICKET.PHP
<?php
var_dump(json_decode($_POST['list']));
?>
And executing this, I'm getting this result:
Notice: Undefined index: list in D:\127.0.0.1/prog1/final/class/ticket.php on line 2
NULL
Im not understanding why im getting an undefined index.
I tried googling this, but most responses seem to point in the direction of using some kind of HTTPS method, which is what I'm trying to achieve via POST.
Any help will be greatly appreciated. Thank you.
The 'list' undefined issue might be due to the structure of the JSON array you pass.
Try the below code and check if it works. If not let's check further :)
var list = {'list': iterateItems()};
_ajax("https://127.0.0.1/prog1/final/class/ticket.php", list)
.done(function(list){});
});
function _ajax(url,data) {
var ajax = $.ajax({
type : "POST",
datatype : "json",
url : url,
data : data
})
return ajax;
}
function iterateItems() {
// array is an array populated in this function, returned to be sent to ticket.php
return JSON.stringify( array );
};
Your PHP Code:
<?php
var_dump(json_decode($_POST['list']));
PHP can't parse JSON parameters automatically. $_POST will only be filled in from a URL-encoded string or a FormData object.
$.ajax will URL-encode an array automatically for you.
_ajax("https://127.0.0.1/prog1/final/class/ticket.php", array)
.done(function(list) {});
function _ajax(url, data) {
var ajax = $.ajax({
type: "POST",
dataType: "string",
url: url,
data: {list: data}
})
return ajax;
}
In PHP you then don't need to call json_decode(). The value of $_POST['list'] will be the array.

Cannot read property '0' of undefined using ajax to get json data

I have an error in my ajax:
Cannot read property '0' of undefined
dmpConnectInstance.hl_readCpxCard(getCpsPinCode(), function (a) {
var path = "cpx";
$.ajax({
type: "POST",
url: path,
data: a,
success: function (data) {
//
$("#res").html("okyou" + data.PracticeLocations[0].s_practiceLocationName);
console.log('yooo' +
data.PracticeLocations[0].s_practiceLocationName);
}
,
error: function () {
console.log('ko');
}
});
});
Here is the json format:
{
"PracticeLocations":[
{
"s_practiceLocationActivity":"SA07",
"s_practiceLocationHealthcareSettings":"SA07",
"s_practiceLocationName":"CABINET M. INFIRMIER3681"
}
],
"i_remainingPinCodeInputs":3,
"s_given":"ALAIN",
"s_internalId":"00B6036814",
"s_name":"INFIRMIER3681",
"s_profession":"60",
"s_professionOid":"1.2.250.1.71.1.2.7",
"s_speciality":"",
"s_status":"OK"
}
I think I have a problem with the data, when I debug data I got empty message.
Otherwise if I put directly into the function:
console.log('yooo'+a.PracticeLocations[0].s_practiceLocationName);
I got the result.
The JSON content you display in your post, is that what is going in or coming out, and how did you confirm the result if indeed the case? The nature of the error is saying that data.PracticeLocations is null and doesn't contain anything at position 0. If data came back as a truly empty result, then that would make sense and including the code that returns your response would help.
Your subsequent statement in the post was:
console.log('yooo'+a.PracticeLocations[0].s_practiceLocationName);
This has a.PracticeLocations, not data.PracticeLocations, which variable a is not referenced anywhere. I presume that is a typo?

Why getting NULL even JSON Array exist in response of jQuery.ajax?

Basically response consist of two things JSON Array and isValid(flag)
I can get flag value successful But it gives the null var resJSON = jQuery.parseJSON(data.notification);. I debug my script in chrome console but json response exist in data.
Might be following code and console result help you to understand my problem!
function getNotificationById(notificationId) {
jQuery.ajax({
type: "POST",
url: "<%=request.getContextPath()%>/GetNotifications/",
dataType : "json",
data: {"operation": "getNotificationById", "notificationId": notificationId},
success:function(data){
var resJSON = jQuery.parseJSON(data.notification);
// ^-- here is null
if (data.isValid) {
// ^-- response is true
jQuery.each(resJSON,function(i, value){
console.log(value.Body);
});
}
}
});
}
Chrome Console Result:
Edit
I have tried following solutions:
var resJSON = data.notification; // Chrome Console return **undefined**
You have a typo.
The data as shown in traces are included in data.notificaiton and not data.notification

Can't parse JSON response

I'm trying to parse the following JSON response:
{
"AgApplyTableE*!": [
{
"Index": 1,
"StringVal": "Error: Enabled virtual server 3 has no IP address.U+0085Error: Apply not done. Use 'diff' to see pending changes,U+0085 then use configuration menus to correct errors.U+0085"
}
]
}
Here's my code:
$('#applyfailreason').click(function (){
var t = $(this);
var DeviceName = $('.DeviceName').val();
var Username = $('.Username').val();
var Password = $('.Password').val();
$.ajax({
method: 'GET',
url: 'http://' + DeviceName + '/config/AgApplyTable',
headers: {
"Authorization": "Basic " + btoa('' + Username + '' + ":" + '' + Password + '')
},
dataType: 'json',
contentType: 'application/json',
success: function(data) {
var test = JSON.stringify(data);
console.log(test);
},
statusCode: {
406 : function() {
alert('There is an unexpected string in your data.\nFix the error and try again.');
},
401 : function() {
alert('Wrong username or password.');
}
},
});
});
I get the following on the console (which is ok):
{"AgApplyTableE*!":[{"Index":1,"StringVal":"Error: Enabled virtual server 3 has no IP address.U+0085Error: Apply not done. Use 'diff' to see pending changes,U+0085 then use configuration menus to correct errors.U+0085"}]}
But I want to print only the "StringVal" out of the JSON response.
Tried:
var test2 = JSON.stringify(data.StringVal);
console.log(test2);
Gives:
undefined
I also tried the following (with dataType: 'jsonp',):
var test4 = JSON.parse(data.StringVal);
But then Chrome sends a GET request to a strange URI (which actually gives 200OK):
config/AgApplyTable?callback=jQuery111306132095118518919_1436256387242&_=1436256387244
And I get the following error:
Uncaught SyntaxError: Unexpected token :
Any idea how to print to console only "StringVal" out of the JSON response?
Thanks.
Your response is an object containing one property named "AgApplyTableE*!", which is an array that contains one element, which is an object that contains the property "StringVal".
So you'd have to access it by data["AgApplyTableE*!"][0].StringVal.
Use console.log(data['AgApplyTableE*!'][0].StringVal)
In your response, there is no such thing as StringVal as direct suboridnate of data. The property StringVal is inside the internal object AgApplyTableE*! therefore data.StringVal is undefined.
Also, another problem I see here is that you're stringifying the response and then trying to access the property StringVal.
If you stringify, you test variable will be a string and string doesnt have a property StringVal (unless you set that in your proto)
EDIT:
Added missing [0] index.
Try
var test2 = data["AgApplyTableE*!"][0].StringVal;
console.log(test2);
test ={"AgApplyTableE*!":[{"Index":1,"StringVal":"Error: Enabled virtual server 3 has no IP address.U+0085Error: Apply not done. Use 'diff' to see pending changes,U+0085 then use configuration menus to correct errors.U+0085"}]};
console.log(test["AgApplyTableE*!"][0]["StringVal"]);
Demo
I think that is because you have two levels here, not only one. In order to get that value out, you probably would need something like
var test2 = JSON.parse(data);
console.log(test2["AgApplyTableE*!"][0].StringVal);
Altough I'm not sure AgApplyTableE*! is a really good identifier here. Probably you can change something else, and then you can also use . notation to reach the members.

jquery using json object

script.js
$('#loginform').submit(function(e){
$.ajax({
type:"POST",
url:"/accounts/login/ajax/",
data:$('#loginform').serialize(),
success: function(msg){
var msg = msg;
msg = JSON.parse(msg);
$('#messagestatus').html('');
if(msg.username != null){
$('#messagestatus').append(msg.username);
}
if(msg.password != null){
$('#messagestatus').append(msg.password);
}
}
});
e.preventDefault();
});
returned object
{'username':['Required'],'password':['Required']}
When I am using JSON.parse and I am alerting, it's showing the correct error, but when I am appending it to the messagestatus div its not responding, please help .
Your username and password are arrays in your json.Either make it that your json looks like
{'username':'Required','password':'Required'}
or change your script:
if(msg.username.length > 0)
{
$('#messagestatus').text(msg.username[0]);
}
if(msg.password.length > 0)
{
$('#messagestatus').text(msg.password[0]);
}
Might be significant, might not be, but your json object actually consists of sub-arrays:
{'username':['Required'],'password':['Required']}
^----------^ ^----------^
meaning that the decoded data structure in JS would actually be
obj['username'][0] and obj['password'][0]
First of all, parameters do not need to be redeclared in their function.
then, to parse your json using $.parseJSON() :
msg = $.parseJSON(msg);
Your JSON contains arrays, use msg["username"][0] to access the first string and not the full array.
And I would put e.preventDefault(); as first statement before AJAX.
And .html('') => .empty() but it's the same result.

Categories

Resources