I am trying to get access to the data returned from an ajaxSubmit request.
$("#searchbutton").on('click', function() {
$("#searchform").ajaxSubmit({
success: function(data) {
populate('#registrationform', data);
},
resetForm: true
});
});
The data that is returned is not being recognise by my populate function, If i do however with raw data,
$("#searchbutton").on('click', function() {
$("#searchform").ajaxSubmit({
success: function(data) {
populate('#registrationform', {studentId: 1, firstName: 'Kay'});
},
resetForm: true
});
});
my populate function works. Any ideas why the data returned is not recognised?
My guess is that the data is actually coming back as a String, NOT a JavaScript object. If you are inspecting with console.log(data), this distinction would be very easy to miss.
Looking at the documentation for the success method and the dataType option, it is quite possible that your server's response is being taken for a simple String. Try explicitly setting dataType: "json" and see what comes back. That, or deserialize to an object with JSON.parse().
Use it like,
$("#searchbutton").on('click', function() {
$("#searchform").ajaxSubmit({
success: function(data) {// data should be return as json
populate('#registrationform',{studentId: data.id, firstName: data.name});
},
resetForm: true
});
});
Related
I am trying to make post request with the following parameters:
const postParams = { 'submission': submission };
However, when the request is actually sent, I observe that submission becomes submission[] in the browser's network tab. This is problematic because my server expects submission and not submission[]. Check the image below for more information.
[Note that the [] was appended to submission][1]
[1]: https://i.stack.imgur.com/pXpNq.png
Note that submission (the variable) is an array of integers, so while it makes sense why the [] is attached, is there a way to get rid of that?
Below is the full function.
const postParams = { submission: str_sub };
console.log(postParams)
$.post(root+'/problems/multiple_choice/'+problem_pk+'/run',
postParams,
function(data) {
// Omitted / not relevant
})
.fail(function(jqXHR, textStatus, errorThrown) { console.log(textStatus); });
This is jQuery's default behaviour where it follows PHP (instead of traditional) conventions.
See the documentation.
Use .ajax instead of .post and include traditional: true in the options object.
$.ajax(
root+'/problems/multiple_choice/'+problem_pk+'/run',
{
data: postParams,
traditional: true,
success: (data) => { ... }
}(
Can't seem to find what I'm looking for in searches so this might be a duplicate but I haven't found an original yet sooo....
I have a an ajax call:
$.ajax({
url: "/events/instructor/",
type: 'POST',
data: {
instructorID: $(this).attr("id")
},
complete: function (data) {
$("#name").html(data["responseText"]["name"]);
$("#email").html(data["responseText"]["email"]);
$("#photo").html(data["responseText"]["photo"]);
$("#summary").html(data["responseText"]["summary"]);
$("#url").html(data["responseText"]["url"]);
}
});
The data being returned is encoded in JSON by the server (C#).
Obviously, data["responseText"]["fieldName"] isn't doing the trick. I could do splits and whatnot but that would mean that if the format changes, I'd need to make sure that the code above keeps up with the changed shape of the data.
How can I say something as simple as data["responseText']["fieldName"] to get the value out of that key?
i think you need to parse json first. look at the api.jquery.com/jquery.parsejson
// data = '{ "name": "John" }'
var obj = jQuery.parseJSON( data );
console.log( obj.name);
// result will be "John"
P.S. also better use 'succes' instead 'complete', you can read about this here Difference between .success() and .complete()?
success: function(data) {
console.log("response is good", data);
},
error: function (){
console.log("something is went wrong");
}
try using like this:
complete: function (data) {
var data=JSON.parse(data);
$("#name").html(data.responseText.name);
$("#email").html(data.responseText.email);
$("#photo").html(data.responseText.photo);
$("#summary").html(data.responseText.summary);
$("#url").html(data.responseText.url);
}
to get only correct response use success.
I am trying to get a value from a json object after making an ajax call. Not sure what I am doing wrong it seems straight forward but not able to get the data
The data that comes back looks like this
{"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
The code, removed some of the code
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
console.log(result.data); //<== the data show here like above
alert(result.data.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I tried in the Chrome console like this
obj2 = {}
Object {}
obj2 = {"data":"[{\"Id\":3,\"Name\":\"D\\u0027Costa\"}]"}
Object {data: "[{"Id":3,"Name":"D\u0027Costa"}]"}
obj2.data
"[{"Id":3,"Name":"D\u0027Costa"}]"
obj2.data.Id
undefined
obj2.Id
undefined
Update
The line that solved the issue as suggested here is
var retValue = JSON.parse(result.data)[0]
Now I can used
retValue.Name
to get the value
Actually, looking at this, my best guess is that you're missing JSON.parse()
.ajax({
type: 'POST',
url: "http://localhost:1448/RegisterDetails/",
dataType: 'json',
data: { "HomeID": self.Id, "Name": $("#txtFamilyName").val()},
success: function (result) {
var javascriptObject = JSON.parse(result);
console.log(javascriptObject ); //<== the data show here like above
alert(javascriptObject.Id); //<==nothing show
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I also find that doing ajax requests like this is better:
var result = $.ajax({
url: "someUrl",
data: { some: "data" },
method: "POST/GET"
});
result.done(function (data, result) {
if (result == "success") { // ajax success
var data = JSON.parse(data);
//do something here
}
});
For clarity it just looks better, also copying and pasting into different functions as well is better.
The id property is in the first element of the data-array. So, alert(result.data[0].Id) should give the desired result. Just for the record: there is no such thing as a 'JSON-object'. You can parse a JSON (JavaScript Object Notation) string to a Javascript Object, which [parsing] supposedly is handled by the .ajax method here.
The data field is just a string, you should parse it to a JSON object with JSON.parse(result.data), since data is now an array you will need to need to use an index [0] to have access to the object. Know you will be able to get the Id property.
JSON.parse(result.data)[0].Id
I'm trying to execute a $.post() function with an array variable that contains the data, but it seams that I'm doing something wrong because it won't go or it's not possible
var parameters = [menu_name, file_name, status, access, parent, classes];
console.log(parameters);
$.post('do.php', { OP: 'new_menu', data: parameters }, function(result) {
console.log(result);
}, 'json'); //Doesn't work
Firebug debug: NS_ERROR_XPC_BAD_CONVERT_JS: Could not convert JavaScript argument
So, which would be the propper way of doing it (if possible)?
i am using for such kind of issues always the $.ajax form like this:
$.ajax({
url: 'do.php',
data: {
myarray: yourarray
},
dataType: 'json',
traditional: true,
success: function(data) {
alert('Load was performed.');
}
});
the traditional is very important by transfering arrays as data.
Could be the variables in the parameters array
Having ran your code and supplemented the parameters for something like:
var parameters = ['foo','bar'];
It seems to work fine. I think the problem must be in the variables that you are passing as part of the array. i.e. are menu_name, file_name, status, access, parent and classes variables all as you expect them to be? e.g. console log them and see what they are coming out as. One might be an object which doesn't convert to json.
Use JSON.stringify()
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify
$.post('do.php', {
OP: 'new_menu',
data: JSON.stringify(parameters)
},
function(result) {
console.log(result);
},
'json'
);
And then, in the server-side use json_decode() to convert to a php array.
http://php.net/manual/es/function.json-decode.php
Ok, so with the help of these StackOverflow fellows I managed to make it work just the way I wanted:
var parameters = {
'name': menu_name.val(),
'file': file_name.val(),
'status': status.val(),
'group': group.val(),
'parent': parent.val(),
'classes': classes.val()
};
$.post('do.php', { OP: 'new_menu', data: parameters }, function(result) {
console.log(result);
}, 'json');
I have a Service which returns JSON using C#'s JavaScriptSerializer class.
jQuery
$.get('GlobalService/Index',
{ crudOperation: crudOperation,
globalType: globalType,
globalObject: globalObject
},
function (data) {
alert(data);
});
the callback function displays in the alert
[object XMLDocument]
How do I get to and parse the JSON object? The object has basic construction
{"field1":"data","field2":"more data",/*...~10 more of these*/}
$.get('GlobalService/Index',
{
crudOperation: crudOperation,
globalType: globalType,
globalObject: globalObject
},
function (data) {
// access it as you would normally access a JS object
alert(data.field1);
},
'json'); // do not forget to pass the json data type here, otherwise it
// will just guess it (probably wrong, as it shows in your case)
Easiest way.
#see getJSON
also,
parseJSON
Your code is working fine, just an alert cannot show the object data:
$.get('GlobalService/Index',
{ crudOperation: crudOperation,
globalType: globalType,
globalObject: globalObject
},
function (data) {
console.log(data); //view data in console
alert(data.field1);
});
You must specify a dataType of "json" in order to let the method know how parse the returned data:
$.get('GlobalService/Index',
{ crudOperation: crudOperation,
globalType: globalType,
globalObject: globalObject
},
function (data) {
alert(data);
}, 'json');
See $.get() documentation at jQuery: http://api.jquery.com/jQuery.get/.
Note that if you don't specify dataType, jQuery will do a smart guess of what the server is returning and it is very clear that it is misunderstanding the server response with an XML block of code.