I have sample code for getting json value from servlet through Ajax call.
In success function I am getting response. It is showing Object : [{"userId":"dfeterter"}] in console.
But I am not able to get value of userId
$.ajax({
url: "Registration",
dataType: "json",
data: {
jsonbhvalue: bhvalue,
jsonuid: uid,
jsonpassword: password,
jsonfname: fname,
jsonlname: lname,
jsonmobile: mobile,
jsonemailid: emailid
},
success: function(variable) {
var obj = $.parseJSON(JSON.stringify(variable));
console.log("Object : " + obj);
console.log("cval : " + obj.userId)
});
});
Thanks To #RobertoNovelo.
You have to remove $.parseJSON as you are already setting JSON by ajax configuration. dataType: "json"
You need to use:
obj[0].userId
Your response is array of objects.
That is because your object is an array. You should either use obj[0] or assign the array to a variable and then use its members
objs = [{"userId":"dfeterter"}]
firstobj = objs[0]
console.log("Object : " + objs);
console.log("cval : " + objs[0].userId);
console.log("cval : " + firstobj.userId);
Related
i am using ajax call to store the data in to DB and controller is returning the list of commentObject.
how can i access this list in JSP?
my ajax call is:
function StoreCommentAndRefreshCommentList(e) {
var commentData = document.getElementById(ActualCommentTextId).value;
$.ajax({
type : 'POST',
url : 'CommentStoreAndRetrieve',
data : "commentData=" + commentData + "&ImageId=" + commetTextButtonId[1],
success : function(commentList) {
//alert('comments stored successfully');
//alert('comment data is...'+res.CommentDataDoc[0]);
},
error : function(e) {
alert('Error: ' + e);
}
});
}
please let me know how can i access list data here.
function StoreCommentAndRefreshCommentList(e) {
var commentData = document.getElementById(ActualCommentTextId).value;
$.ajax({
type : 'POST',
url : 'CommentStoreAndRetrieve',
data : "commentData=" + commentData + "&ImageId=" + commetTextButtonId[1],
dataType : "xml",
success : function(commentList) {
alert($(commentList).text());
},
error : function(e) {
alert('Error: ' + e);
}
});
}
You can f.e. create <input type='hidden' id='someId'/> in your JSP and then in your success function you can assign data like $("#someId").val(...);
Another idea would be create JS variable inside JSP by putting <script>var myVar = ""</script>. Then in your succes function you can refer to such 'global' variable. Althogh, I believe that usual assignment (myVar = response.yourList) wouldn't work for a response object (which is the case in your problem). The solution would be to create an array var arr = [] and then in for loop you can push some done into it.
I got the solution.
i did used $.each(res, function (key, val) to iterate one by and built the tags dynamically using val field. here key holds the index position and val holds the corresponding object. then i did accessed one by one field by val.filedname(which we did create for pojo).
Thanks everyone.
I have the following code:
var result = confirm("You want to Subscribe to our Newsletter?");
var emailAddress = $("#subscribeEmail").val();
if (result == true) {
$.ajax({
type: 'POST',
url: '/php/subscribeNewsletter.php',
data: '{"email": "' + emailAddress + '"}',
complete: function(r){
alert(r.responseText);
}
});
}
I believe the problem is to do with:
data: '{"email": "' + emailAddress + '"}',
I am receiving an empty $_POST array on the server side of things.
Pass an object literal, not a string:
data: {email: emailAddress },
jQuery will transform the object into the URL encoded key/value pairs, which will be picked up in the $_POST array on the PHP side.
Your current code is actually sending a JSON string as the raw POST data. jQuery is seeing the data type is a string, and so it doesn't do any processing, so you'd have to access the raw POST data on the PHP side and do a JSON decode to get it.
yes problem is: data: '{"email": "' + emailAddress + '"}', it should be object:
...
data: {"email": emailAddress},
...
provide the data attribute in the ajax call as a json object instead of string.
like
data: {"email": emailAddress },
You can use like below
$.get('/Presentation/AjaxData/History.aspx', { itemID: itemid }, function (data) {
$('.history-listing-tabs>.tab-item').html(data);
});
Try this format
data: {email: emailAddress}
Better pass data to a variable and use it while sending,
var temp = 'email:' + emailAddress;
...
data: temp;
.....
I'm having trouble with filtering the returned data from an Ajax JSON call. Right now, it returns:
{"results":[{"text":"RoboChat: What is it like to feel?","username":"RoboChat","createdAt":"2014-06-04T20:01:15.268Z","updatedAt":"2014-06-04T20:01:15.268Z","objectId":"wG2cs1OnVY"},
I'm trying to get it to return only the "text" object, like this:
"RoboChat:What is it like to feel?"
Here is my code:
function fetch () {
$.ajax({
url:"https://api.parse.com/1/classes/chats",
type : 'GET',
dataType : 'JSON',
data : JSON.stringify({
}),
success:function(data) {
$('.messages').append("<li>" + (JSON.stringify(data)) + "</li>")
}
});
};
I've tried passing a filter to JSON.stringify, but with no success, I'm not even sure if that's the way to approach filtering the data. Any help would be much appreciated.Thanks!
You can't really change what a request returns, but you can of course use the resulting value in any way you want. Since the response contains multiple objects with text properties, you have to iterate them and extract the text:
success: function(data) {
var results = data.results;
results.forEach(function (result) {
$('.messages').append("<li>" + result.text + "</li>");
});
}
The returned JSON has a results property which is an array, you can iterate through the array and read the text property of each element:
$.each(data.results, function(index, element) {
console.log(element.text);
});
For creating a li element for each array's element, you can use the $.map utility function:
var li = $.map(data.results, function(element) {
return '<li>' + element.text + '</li>';
});
$('.messages').append(li);
try for, the data has an array named results, from wich you have to select the first like following:
success: function(data) {
var results = JSON.parse(data).results;
results.forEach(function (result) {
$('.messages').append("<li>" + data.results[0].text + "</li>");
});
}
members = $.parseJSON(members);
$.each(members, function (i, item) {
$.ajax({
type: "POST",
url: "'.base_url(" / panel / listNottifications ").'/'.$id.'/" +
valueSelected,
data: {
list: item[i]
},
dataType: "json",
success: function (data){
var w = $("#Eventprogress").width() + perRequest + "%";
$("#Eventprogress").attr("data-original-title", w);
$("#Eventprogress").animate({
width: w
}, 600);
}
});
});
Members is an returned json var from get request equal as example
["11111|22222|3333|4444|555555"]
the error i got in fetching is ..
Uncaught SyntaxError: Unexpected token |
any ideas how to fetch the returned data ?
Thanks
this is not a JSON response, the json response should be an object with key, value syntax or an array or such objects,
this is neither one of them, but anyway you can check if the JSON is valid in Json Link
I have an js function that is collecting data and sending it to a php file.
I am trying to submit an array as part of the post:
function send_registration_data(){
var string = "{username : " + $('#username').val() + ", password : " + $('#pass1').val() + ", level : " + $("#userrole").val() + ", 'property[]' : [";
var c = 0;
$('input[name=property]:checked').each(function(){
if( c == 0){
string +="\"" +this.value+"\"";
c=1;
} else {
string +=",\""+this.value+"\"";
}
});
string+="]}";
$('#input').html( JSON.stringify(eval("(" + string + ")")) );
$.ajax({ url: './php/submit_registration.php',
//data: { username : $('#username').val() , password : $('#pass1').val() , email : $('#email').val() , level : $("#userrole").val() },
data: JSON.stringify(eval("(" + string + ")")) ,
type: 'post',
success: function(output) {
$('#output').html( output );
}
});
};
On submit my php file returns an the POST array as NULL. I am not sure what I am doing wrong here.
EDIT: IT is the same weather I try to convert the string to json or not.
ALso, the inputs contain just text names.
string keyword
Do not use the "string" keyword.
eval
Eval is evil - use it with caution.
strict mode
Make sure always to work in the "strict mode" by placing this line at the beginning of your code:
'use strict'
Building your response object
You do not have to glue your post object manually. Just do it this way:
var post = {
'username': $('#username').val(),
'password': $('#password').val(),
'myArray[]': ['item1', 'item2', 'item3']
};
jQuery the right way
Avoid messing up with unnecessary syntax.
$.post(url, post)
.done(function(response){
// your callback
});
Conclusion
'use strict'
var url = './php/submit_registration.php'; // try to use an absolute url
var properties = {};
$('input[name="property"]:checked').each(function() {
properties.push(this.value);
});
var data = {
'username': $('#username').val(),
'password': $('#pass1').val(),
'level': $('#userrole').val(),
'property[]': properties
};
// submitting this way
$.post(url, data)
.done(function(response) {
// continue
})
.fail(function(response) {
// handle error
});
// or this way
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify(data), // you'll have to change "property[]" to "property"
contentType: "application/json",
dataType: 'json',
success: function(response) {
// continue
}
});
You need to get from php://input if you are not using multipart/form-data, so, application/json
$myData = file_get_contents('php://input');
$decoded = json_decode($myData);
If you're sending this up as json, your $_POST variable will continue to be NULL unless you do this.