Error occurs when i use jQuery Ajax - javascript

$('#deviceLoadMore') is a link. When this link is being clicked, it will trigger a ajax to the web service I have created.
The problem I'm having now is it keeps on throwing this error in the console.log
Uncaught TypeError: Converting circular structure to JSON. But when I just paste the ajax part in the console.log, it able to retrieve the data back. I have checked that all the value is just a normal string and integer.
I was wondering why i can trigger in console log without having any issue and couldn't if i just click on the link?
var currentContextSection = '<%=currentSection %>';
var currentTemplateIds = '<%=templateIds %>';
var currentItemPerPage = <%=itemPerPage %>;
var currentPageIndex = <%=currentPage %>;
var arguments = { templateIds:'<%=templateIds %>' , currentSection:'<%=templateIds %>', currentPage:currentPageIndex, itemPerPage:currentItemPerPage };
$(document).ready(function () {
$('#deviceLoadMore').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/AJAX/WS.asmx/GetItems",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(arguments),
dataProcess: false
}).done(function (data) {
test = data;
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
});
});
});
------ EDIT -------
If I have this:
var arguments = {"templateIds":currentTemplateIds ,"currentSection":currentContextSection,"currentPage":currentPageIndex,"itemPerPage":currentItemPerPage};
and executing with the ajax data:JSON.stringify(arguments), i will get the following errror:
Converting circular structure to JSON.
When I console.log the "arguments", it displays:
Object {templateIds: "963C1D18A93849309D6014CE2135173C", currentSection: "Personal", currentPage: 1, itemPerPage: 8}
And it displays this when I console.log JSON.stringify(arguments):
"{"templateIds":"963C1D18A93849309D6014CE2135173C","currentSection":"Personal","currentPage":1,"itemPerPage":8}"
After google around for some successfully implemented ajax sample, I changed my code to the following, and it works! And I have no idea why it works this way.
$(document).ready(function () {
$('#deviceLoadMore').click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/AJAX/WS.asmx/GetItems",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({"templateIds":currentTemplateIds ,"currentSection":currentContextSection,"currentPage":currentPageIndex,"itemPerPage":currentItemPerPage}),
dataProcess: false
}).done(function (data) {
test = data;
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
});
});
});

try after removing, JSON.stringify from
data: JSON.stringify(arguments),

Related

HTTP get requests in ajax

I am pretty new to javascript where I am trying with ajax to make an get request. I am trying to get the password from the response.
Javascript code:
$(document).ready(function () {
$("#LoginUser").click(function () {
$.ajax({
url: 'http://website/api/user/Mikkel1337',
dataType: 'json',
type: 'GET',
contentType: 'application/json',
error: function () {
alert("An error had occurred");
},
success: function (data) {
var jsonStr = JSON.stringify(data);
alert(jsonStr['password']);
}
});
});
})
The response JSON code looks like this:
{"userId":16,"firstName":"mojn","lastName":"mojn","email":"mojn#mojn.dk","accountName":"Mikkel1337","password":"123","userRoleId":1,"active":false,"userRole":null,"competetion":[],"judge":[],"team":[]}
When im running this I only get the error function. Any suggestions or solution is appreciated :)
Basically you are converting the JSON to string and trying to access the string as object. Please don't stringify the data, and for JSON why using long code, your code should be:
$(document).ready(function () {
$("#LoginUser").click(function () {
$.getJSON( "http://website/api/user/Mikkel1337", function( data ) {
// do something on success
alert(data.password);
});
});
});
Cheers !!!
dont need to JSON.stringify of data simple use
$(document).ready(function () {
$("#LoginUser").click(function () {
$.ajax({
url: 'http://website/api/user/Mikkel1337',
dataType: 'json',
type: 'GET',
contentType: 'application/json',
error: function () {
alert("An error had occurred");
},
success: function (data) {
alert(data.password);
}
});
});
})
You should pass two argument for error:function(jqXHR, exception) as below.
And check once your API Url using proper way, may be your API is not show you proper result and you not get any of data from that API so that may be a reason you get error message.
$(document).ready(function () {
$("#LoginUser").click(function () {
$.ajax({
url: 'http://website/api/user/Mikkel1337',
dataType: 'json',
type: 'GET',
contentType: 'application/json',
success: function (data) {
var jsonStr = JSON.stringify(data);
//also try this way to get JSON data:
// var jsonStr =JSON.parse(data);
alert(jsonStr['password']);
},
error: function (jqXHR, exception) {
alert("An error had occurred");
},
});
});
});

Handle undefined data in ajax request

I have the below ajax call and sometimes the request stops the page from loading as the data being passed is undefined.
I there a way to put a condition to handle the request if it has values that are undefined?
Can it be wrapped with a if condition?
newuser is not defined
$.ajax(
{
url: 'sample.aspx,
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data){
...
} ,
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
});
Simplest way would be to use a pipe:
$.ajax({url: 'sample.aspx',
data: newuser || {},//continue here...
If your variable was not initialized, empty object will be sent instead.
That's if and only if you can handle empty "newuser" for some reason.
I'm assuming that not closed URL is just a mistake in copy-paste, and not actually part of your code.
how about
if(newuser)
{
$.ajax(
{
url: 'sample.aspx,
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data){
...
} ,
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
});
}
If you are unable to handle an empty newuser you can try something like this:
if (newuser) {
$.ajax({
url: 'sample.aspx',
data: newuser,
type: 'POST',
dataType: 'html',
success: function(data) {
...
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
}
});
}

Retrieving data using ODATA with javascript

I'm trying to return a result set from crm using odata. i'm new to this.. i want to have an asp.net page displaying the values in a datagrid. i'm getting the error odata execution error popup. if i put in the correct server and query string it always fails though.. any suggestions on how to get this work properly
function ExecuteQuery(ODataQuery) {
//var serverUrl = Xrm.Page.context.getServerUrl();
var serverUrl = "https://server.server.com"; //would be the real server
// Adjust URL for differences between on premise and online
// if (serverUrl.match(/\/$/)) {
// serverUrl = serverUrl.substring(0, serverUrl.length - 1);
// }
alert("test");
var ODataURL = serverUrl + "/XRMServices/2011/OrganizationData.svc" + ODataQuery;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODataURL,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
//
// Handle result from successful execution
alert("success");
//data.d.results
},
error: function (XmlHttpRequest, textStatus, errorObject) {
//
// Handle result from unsuccessful execution
//
alert("OData Execution Error Occurred");
}
});
}
<script type="text/javascript">
ExecuteQuery("the query would go in here);
</script>

Unable to access json data retrieved from php page using jquery $.ajax

How to access this json data in JavaScript.
when I alert it the result is undefined
Here is jQuery code
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Here is the problem
alert(data[0]['Result']);
}
});
This is PHP code
$data=array($no);
for($i=0;($i<$no && ($row=mysql_fetch_array($result)));$i++)
{
$data[$i]=array();
$data[$i]['Result'] = $row['Result'];
$data[$i]['TestCode'] = $row['TestCode'];
$data[$i]['TestStatus'] = $row['TestStatus'];
$data[$i]['SrNo'] = $row['SrNo'];
}
$data1=json_encode($data);
echo $data1;
exit;
I have tested the PHP file independently,
The json data is output as follows:
[{"Result":"1","TestCode":"22","TestStatus":"0","SrNo":"1"},{"Result":"1","TestCode":"23","TestStatus":"1","SrNo":"2"}]
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Added parse json
var data = jQuery.parseJSON(data)
alert(data[0]['Result']);
}
});
You can access to your data by doing
data[0].Result
It's an Object, not an array.
so data[0]['Result'] it's not the proper way
EDIT:
Since you have more objects, you have to do a loop this way:
$.each(data, function(key, val){
console.log(val.Result);
console.log(val.TestCode);
//...
});
When you see something like
{
"foo":"bar",
...
}
you can access to it the same way as above:
name_of_the_object.foo
that will have the value "bar"
Try to add parse JSON. I have added. Now it may be work.
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Added parse json
var data = $.parseJSON(data)
alert(data[0]['Result']);
}
});

cannot display json data returned from jquery ajax call

can somebody please tell me, how can I display json data returning from the ajax call. I am new to this.
$.ajaxSetup({
cache: false,
timeout: 5000
});
//String.prototype.toJSON;
var the_object = {};
function concatObject(obj) {
strArray = []; //new Array
for (prop in obj) {
strArray.push(prop + " value :" + obj[prop]);
}
return strArray.join();
}
//var ntid = "hhsh";
//document.writeln("httpRequest.responseText");
$(document).ready(function() {
$("button").ajaxStart(function() {
alert('Triggered ajaxStart handler.');
});
$("button").click(function() {
$.ajax({
type: "POST",
dataType: 'JSON',
//data: "{'ntid':'john'}",
//contentType: "application/json; charset=utf-8",
//processData: false,
url: "Testing.aspx/SendMessage",
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
success: function(result, txtStatus, httpRequest) {
alert(txtStatus);
//$('#status').html(httpRequest.responseText);
//the_object = result;
$('#status').html(concatObject(result));
//$('#status').html(the_object);
//alert("hello" + concatObject(the_object));
//document.writeln(concatObject(the_object));
}
});
//alert(concatObject(the_object));
//$('#status').html(concatObject(the_object));
});
});
above is the js file. should i need to do something on asp file directly to display it. if yes, then how? please reply me soon. i m stuck here and unable to display data here. Its only diplaying this line:
toJSON value :function (key) { return this.valueOf(); }
Your result is most likely rooted with a property named d. Try modifying your success to use result.d;
This is usually a security measure that has to do with exploits which target a JSON collection with single root parent.

Categories