I have the following code and want to use it as an object.
How to i access the properties of the object? currently i am always getting undefined!
function getLoggerInfo()
{
$.ajax({
url: "data.json",
type: "GET",
data: {emGetInfo: "logger"},
dataType: "json",
success: function(response){
//alert("1: " + this.loggerName);
loggerName = response.emGetInfo[0].loggerName;
protocol = response.emGetInfo[0].protocolVersion;
$("#console").text("Logger Name: " + loggerName + " - Protocol Version: " + protocol);
return;
},
error: function(jqXHR, textStatus, errorThrown){
$("#console").text("ERROR: AJAX errors. " + jqXHR + " : " + textStatus + " : " + errorThrown);
return;
},
statusCode: {
404: function() {
$("#console").text("404: The requested JSON file was not found.");
return;
}
}
});
}
// get loggerName...
$(document).ready(function () {
// Get logger info event...
$("#ajax").click(function() {
var loggerInfo = new getLoggerInfo();
alert("Loggername: "+ loggerInfo.loggerName);
});
});
AJAX is asynchronous - so it does not return data ... the following is a (rough) outline of what happens when you use the $.ajax() function
The data is sent to the url
The browser continues - executing other code as required
When the url (called in step 1) finishes being processed the success callback is executed.
Step 3 could be 1 second, 10 seconds, 5 minutes later
you should process the request in the success callback :
$.ajax({
url: "data.json",
type: "GET",
data: {emGetInfo: "logger"},
dataType: "json",
success: function(response){
// process here
loggerName = response.emGetInfo[0].loggerName;
alert(loggerName);
}
});
Related
Good evening,
I'm trying to do a AJAX call in a C# page and I'm dealing with some problems.
My jQuery code is:
$(document).ready(function () {
$.ajax({
type: "POST",
url: "conteudo.aspx/GetNewPost",
data: { ids: "<%=Request.QueryString["idconteudo"]%>" },
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (data) {
alert("ok");
}
});
});
And my code-behind is:
[WebMethod]
public static string GetNewPost(string ids)
{
// some code
return ids;
}
Does someone know what is going on?
PS: The error is Internal Server Error.
Please use code as below
Because you are using text data type from query string, you can make datatype as text
$(document)
.ready(function () {
var q = "<%=Request.QueryString["idconteudo"]%>";
alert(q);// just to check the value
// assuming that you had passed query string value
$.ajax({
type: "POST",
url: "conteudo.aspx/GetNewPost",
data: { "ids": q },
//contentType: 'application/json; charset=utf-8',
dataType: 'text',// data type should be text
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " +
XMLHttpRequest.toString() +
"\n\nStatus: " +
textStatus +
"\n\nError: " +
errorThrown);
},
success: function(data) {
alert("ok");
}
});
});
Edit 1 : If the Web Method is on ASPX page, you shall use below code, so that you get result in Json format
$(document)
.ready(function () {
var q = "<%=Request.QueryString["idconteudo"]%>";
//alert(q);
// just to check the value
// assuming that you had passed query string value
$.ajax({
type: "POST",
url: "conteudo.aspx/GetNewPost",
data: '{ids: "' + q + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " +
XMLHttpRequest.toString() +
"\n\nStatus: " +
textStatus +
"\n\nError: " +
errorThrown);
},
success: function (result) {
alert("ok" + result.d);
}
});
});
try:
var idconteudo = "<%=Request.QueryString["idconteudo"]%>";
...
...
url: "conteudo.aspx/GetNewPost",
data: "{ids: \"" + idconteudo + "\"" }",
contentType: 'application/json; charset=utf-8',
...
...
From what you have given us with your post, I see two things that are incorrect and one other thing that may have just not been posted in your question, but it is in fact in your real source.
1) Your data is written wrong. It should be:
$(document).ready(function () {
var test = "<%=Request.QueryString["idconteudo"]%>";
$.ajax({
type: "POST",
url: "conteudo.aspx/GetNewPost",
data: { 'ids' : test }, // the ids needs to have quotes to be correct syntax
dataType: 'text',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (data) {
alert("ok");
}
});
});
2) You say it's a POST but your method isn't decorated with the [HttpPost] Annotation.
3) Your dataType is set to 'json' but your method is returning a string.. so 'json' should be changed to 'text'.
Hope this helps!
My app is based substantially on CRUD operations. All operation work great on Safari and other browsers, but not in Firefox. I can not understand what could be the problem. I'm new on js because I come from obj-c whose environment provides an excellent debugging. When i post data from a form to server, I get a 500 internal server error.
I looked for information everywhere, but the suggested solutions do not work for my case. Any help is largely appreciated.
My code:
function save() {
var url;
if (save_method == 'add') {
alert('Method Add');
var ids = $('input[name="id"]').val();
var disciplinaNome = $('[name="disciplinaNome"]').val();
console.log(ids + disciplinaNome);
url = "http://SERVER.me/Api/v5/create/discipline";
$.ajax({
url: url,
type: "POST",
data: "disciplinaNome=" + disciplinaNome,
contentType: "application/x-www-form-urlencoded",
success: function(responseData, textStatus, jqXHR) {
$('#modal_form').modal('hide');
alert("data saved")
console.log("Data: " + responseData + "\nStatus: " + textStatus);
//if success close modal and reload ajax table
$('#example').dataTable().fnClearTable();
$('#example').DataTable().ajax.reload();
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error adding data');
}
});
} else {
url = "http://server/Api/v5/update/discipline";
alert('Method update');
}
$('[name="disciplinaNome"]').val());
var ids = $('input[name="id"]').val();
var disciplinaNome = $('[name="disciplinaNome"]').val();
console.log(ids + disciplinaNome);
var ajaxLock = 1;
// ajax adding data to database
$.ajax({
url: url,
type: "POST",
data: "id=" + ids + "&disciplinaNome=" + disciplinaNome,
contentType: "application/x-www-form-urlencoded",
success: function(responseData, textStatus, jqXHR) {
alert("data edited")
console.log("Data: " + responseData + "\nStatus: " + textStatus);
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
$('#example').dataTable().fnClearTable();
$('#example').DataTable().ajax.reload();
// reload_table();
ajaxLock = 0;
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error update data');
}
});
}
UPDATE with disciplinaNome
I cannot seem to understand why I cannot access an array I get send back by PHP.
I send this back when AJAX makes a call: $response['success'] = true;
I do this by echo json_encode($response); in my PHP file.
Now I want to access it in Javascript, but response.success doesnt work, it logs 'undefined' in the console. Now I check the response, and that is this: {"success":false}
But if I check for if(response.success) it always sends back false, because response.success is undefined. Does anyone know what I mean and what is causing this issue?
This is my AJAX call:
$$.ajax({
type: 'POST',
url: url + "applogin.php",
crossDomain: true,
data: {
username: e,
password: p
},
//dataType: 'json',
success: function(response) {
console.log(response);
if (response["success"]) {
window.localStorage["username"] = e;
window.localStorage["password"] = md5(p);
mainView.router.loadPage('beurslist.html');
} else {
console.log("Your login failed");
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error- Status: " + textStatus + " jqXHR Status: " + jqXHR.status + " jqXHR Response Text:" + jqXHR.responseText)
},
});
The answer by #SZenC is fine, there's a point though about best practices:
The reason jQuery didn't recognize the response as JSON is because the server probably didn't send a Content-type header, so just add to your server-side code a call to -
header('Content-type: text/json');
You won't need the explicit call to JSON.parse in each API call, you'll get better integration with test tools, and your app will be better self-documented for other folks who use/will-use this code (including yourself should your code need some future maintenance).
In any case it is advised also to document the expected input on the client side by either explicitly specifying dataType as json or by making the API call using a shortcut method such as $.getJSON().
Your ajax-call will return a string, you need to decode it with JSON.parse. You'd get something like this then.
$$.ajax({
type: 'POST',
url: url + "applogin.php",
crossDomain: true,
data: {
username: e,
password: p
},
//dataType: 'json',
success: function(r) {
var response=JSON.parse(r)
console.log(response);
if (response["success"]) {
window.localStorage["username"] = e;
window.localStorage["password"] = md5(p);
mainView.router.loadPage('beurslist.html');
} else {
console.log("Your login failed");
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error- Status: " + textStatus + " jqXHR Status: " + jqXHR.status + " jqXHR Response Text:" + jqXHR.responseText)
}
});
I am trying to get CRM data using the Ajax call. Data is being returned with 'd' and 'result' properties but I can't get it on client side. It says ajaxdata.d is undefined.
A sample Ajax call:
var context = Xrm.Page.context;
var serverUrl = context.getClientUrl();
var ODATA_ENDPOINT = context.prependOrgName("/xRMServices/2011/OrganizationData.svc");
var filter = "?&$select=cc_TypeID,cc_customentityId,cc_anotherAttribute&$filter=cc_TypeID eq '2'";
var odataUri = ODATA_ENDPOINT + "/cc_customentitySet" + filter;
console.log("odataUri: " + odataUri);
//Asynchronous AJAX function to Retrieve a CRM record using OData
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataUri,
async: false,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (ajaxdata, textStatus, XmlHttpRequest) {
//console.log("cc_campaignSynch.htm > ready > $.ajax success: " + data);
debugger;
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
console.log("cc_campaignSynch.htm > ready > $.ajax error: " + XmlHttpRequest.responseText);
}
});
Snapshot of data returned:
Updated Snapshot (JSON.parse used):
Might be something of nothing, but try changing "datatype" to "dataType"
To force jQuery magic work and recognize the data type, try to send the response back with HEADER: "Content-Type: application/json".
I am trying to get the following code to send variables to a PHP page via POST. I am not quite sure how to do it. This is my code sending data via GET and receiving it via JSON encoding. What do I need to change to pass variables to process_parts.php via POST?
function imagething(){
var done = false,
offset = 0,
limit = 20;
if(!done) {
var url = "process_parts.php?offset=" + offset + "&limit=" + limit;
$.ajax({
//async: false, defaults to async
url: url
}).done(function(response) {
if (response.processed !== limit) {
// asked to process 20, only processed <=19 - there aren't any more
done = true;
}
offset += response.processed;
$("#mybox").html("<span class=\"color_blue\">Processed a total of " + offset + " parts.</span>");
alert(response.table_row);
console.log(response);
imagething(); //<--------------------------recursive call
}).fail(function(jqXHR, textStatus) {
$("#mybox").html("Error after processing " + offset + " parts. Error: " + textStatus);
done = true;
});
}
}
imagething();
The default method is GET, to change that, use the type parameter. You can also provide your querystring properties as an object so that they are not immediately obvious in the URL:
var url = "process_parts.php";
$.ajax({
url: url,
type: 'POST',
data: {
offset: offset,
limit: limit
}
}).done(function() {
// rest of your code...
});
Try This
$.ajax({
url: "URL",
type: "POST",
contentType: "application/json;charset=utf-8",
data: JSON.stringify(ty),
dataType: "json",
success: function (response) {
alert(response);
},
error: function (x, e) {
alert('Failed');
alert(x.responseText);
alert(x.status);
}
});