very simple error in Ajax that I can't solve - javascript

This is my simple code to call asmx webservice (xml).
function maxTransaccion() {
$.ajax({
type: "POST",
url: "WebService.asmx/MAxTransaccion",
contentType: "application/json; charset=utf-8",
dataType: "json",
crossDomain: true,
success: function(s) {
return s.d;
}
});
}
But I received this error:
message: "s is not defined"
proto: Error
I am doing something wrong? I use this ajax structure multiple times within a .js file. But only in this function it gives me error, what scares me is that it is so simple

First of all, if your service responds with a XML, then you should adapt for that:
$.ajax({
type: "POST",
url: "WebService.asmx/MAxTransaccion",
dataType: "xml",
crossDomain: true,
success: function(s) {
return s.d;
}
});
I think changing dataType and omitting contentType might do the trick.
The next thing that could be improved is your success-handler.
Check for the property first, before using it:
function(s) {
if (s && s['d']) {
doSomethingWith(s.d);
}
}
But because you are most likely receiving a XML and not a JSON-object, you might want something like this:
function(xml) {
var responseNode = $(xml).find('node');
doSomethingWith(responseNode.text());
}
Also like mentioned in the comments, just returning in an AJAX-call, will probably do nothing. So you need another function, where you get your result and doSomethingWithIt.

Related

Returns error when consuming this php response

Return error in the query
From the browser the answer is correct.
$.ajax({
type: "POST",
url: url,
async: true,
contentType: " charset=utf-8",
dataType: "XMLHttpRequest",
success: function (response) {
console.log(response);
},
error: function (msg) {
console.log(msg);
}
});
The message says "error".
I see three issues. First, dataType is a choice of xml, json, script, or html, unless you did something really fancy. jQuery can guess it based on received data though, so there is normally no need to set it. But if you want to be explicit (assuming your page returns json):
dataType: "json"
Second, contentType value looks like some truncated thing. I would just completely remove it, as you are not sending any data and just requesting a page.
Finally, when you are sending no data and just requesting a resource, the best is to use GET.
All in all:
$.ajax({
type: "GET",
url: url,
async: true,
dataType: "html",
success: function (response) {
console.log(response);
},
error: function (msg) {
console.log(msg);
}
});

Undefined index Jquery Ajax POST

I have this small but annoying problem. I really not usual with a web thing. I try to request to my php file using ajax jquery. When I want to retrieve the data I send from ajax, it return undefined index. I dunno what's the problem, it make me spend a lot of time to solve it. Thanks
Below is my ajax code
var at=this.name.substring(this.name.length,7);
var value_header = $("#key"+at).val();
var jsObj = { new_value:value_header, id:at, data:'header'};
console.log(JSON.stringify(jsObj));
$.ajax({
type: 'POST',
headers: 'application/urlformencoded',
url: 'admin_crud.php',
data: jsObj,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
console.log("Sukses");
}
When I call the below code in my php file, the result is 'Undefined index: data'
echo $_POST['data'];
//Edit
So, when I try var_dump($_POST);, the result is array(0) {}. Where is my mistake? I thought I had send the right one
//Edit
As I mention above, I want it to run perfect without error. Thanks
Remove headers, change your datatype to text and catch errors in the ajax call
$.ajax({
type: "POST",
dataType: "text",
data: jsObj,
url: "admin_crud.php",
success: function (result) {
console.log("success", result);
},
error: function (e) {
console.log("Unsuccessful:", e);
}
});
I have another solution beside #Marco Sanchez too, I don't know it always work or not, but in my case, it work :
$.ajax({
type: 'POST',
url: 'admin_crud.php',
headers: "Content-type: application/x-www-form-urlencoded"
data: "new_value="+value_header+"&id="+at+"&data=header",
success: function(data){
console.log("Sukses");
console.log(data);
}
});

Second Ajax call already populated with success results

I have an Ajax call being made from a button press which returns me some data then goes off and creates a grid. The first time the function is called the Ajax call is made, data is returned and the grid is displayed. Happy Days.
However any subsequent call to the function, where none of the data parameters are changed, result in the Ajax call not being made to the server and the function skips straight to 'success' with the results from the successful call already populated.
Changing any of the 'postParameters' results in a successful Ajax call and the data is refreshed.
function btnClick(){
//blah blah
getGridData();
}
function getGridData() {
var postParameters =
{
SiteID: "#Model.SiteID",
DateFilterFrom: $("#datepickerFrom").val(),
DateFilterTo: $("#datepickerTo").val(),
CustomerFilter: $("#customers").val()
};
$.ajax({
url: "#Url.Action("SalesForecast_Read", "Planning")",
type: "GET",
contentType: "application/json; charset=utf-8",
data: postParameters,
dataType: "json",
success: function (results) {
createHighlights(results.Highlights);
createGrid(results.Entries);
},
error: function (e) {
alert(e.responseText);
}
});
};
I know there must be an important Javascript concept I am missing but I just cant seem to be able to nail it.
Can anyone help put me in the right direction?
Have you tried to disable the cache with:
$.ajax({
url: "#Url.Action("SalesForecast_Read", "Planning")",
type: "GET",
cache: false,
contentType: "application/json; charset=utf-8",
data: postParameters,
dataType: "json",
success: function (results) {
createHighlights(results.Highlights);
createGrid(results.Entries);
},
error: function (e) {
alert(e.responseText);
}
});
Explanations
The cache basically tries to save a call to the server by saving the return value of the calls.
It saves them using a hash of your query as a key, so if you make a second query that is identical, it will directly return the value from the cache, which is the value that was returned the first time.
If you disable it, it will ask the server for every query.
You can add cache: false to your ajax request.
$.ajax({
url: "#Url.Action("SalesForecast_Read", "Planning")",
type: "GET",
contentType: "application/json; charset=utf-8",
data: postParameters,
dataType: "json",
cache:false,
success: function (results) {
createHighlights(results.Highlights);
createGrid(results.Entries);
},
error: function (e) {
alert(e.responseText);
}
});
IE might not listen to you though. For that you can add a field to the POST Parameters, where you add the current time in miliseconds, so even IE does not cache.
try to add this in ur ajax call:
$.ajax({
cache: false,
//other options...
});
This will force the recall of the ajax each time.
For more information please check the following link :
api.jquery.com/jquery.ajax

IE pop up 'Syntax Error' when JSONP gets no response

Current application has to retrieve information from another application, and this other application is not required to be active to respond the JSONP request so the initiate requester will pop up an alert message about it.
function jsonRequest(requestURL, errorMsg){
var err = "";
var requestData= {param1: value1, param2: value2};
$.ajax({
type: 'GET',
async: true,
data: requestData,
jsonpCallback: 'jsonCb',
url: requestURL,
timeout: 20000,
dataType: 'jsonp', /* this trigger the syntax error window by IE*/
contentType: "application/json; charset=utf-8",
success: function(data) {
if(data.hasError != null){
error = data.error;
alert(error);
}else{
//.... logic to output valid values
} // closing } is not missing..duh
},//success
error:function(x, timeout, m) {
alert(errorMsg);
}
});
return err;
}
so then there are three possible scenarios:
JSONP request receives valid data from the other application
JSONP request receives empty data from the other application
JSONP request gets no response(the other application is not active)
So far so good until testing on IE. The problem is when it comes to scenario 3 then IE pop up its classic Syntax Error, after click 'close' then the alert message in $.ajax error:{..} shows up
Message: Syntax error
Line: 1
Char: 1
Code: 0
URI:.......
IE debug tool is pretty lame so it wont allow me to go any details. After I check javascript/jsp code line by line I found the cause of the issue:
In Scenario 3, once I change dataType: "jsonp" to dataType: "json" in the javascript code, then the error no more pop up, but of course the whole ajax request gonna fail. I cannot find out what returns to IE by the debugging tool, when the other application is inactive.
I wonder if there is any effective way to let IE to tolerate JSONP or any method to debug where is the cause of the issue.
The fact that IE9 works in any scenario with your code is a testament to the sheer incompetence of the microsoft programmers that created the javascript engine for that dinosaur
/rant - Solution to your problem follows: look for // you forgot this closing brace
function activateManifestJson(aUrl, code, timeoutErr){
var error = "";
// RESTful request data
var urlData = {param1: value1, param2: value2};
$.ajax({
type: 'GET',
url: aUrl,
async: true,
data: urlData,
jsonpCallback: 'jsoncallback',
timeout: 20000,
dataType: 'jsonp', /* this trigger the syntax error window by IE*/
contentType: "application/json; charset=utf-8",
success: function(json) {
if(json.hasError != null && json.hasError == "true"){
error = json.error;
alert(error);
}else{
//.... logic to output valid values
// *******************************************
} // you forgot this closing brace
// ***********************************************
},//success
error:function(x, tm, m) {
alert(timeoutErr);
}
});
return error;
}
After several hours desperately debugging, finally the fix to this issue emerged:
Just put this setting in ajax code and then the script error never pop up:
crossDomain: true,
so that
$.ajax({
type: 'GET',
url: aUrl,
async: true,
data: urlData,
jsonpCallback: 'jsoncallback',
crossDomain: true, /***** the life saver ****/
timeout: 20000,
dataType: 'jsonp',
contentType: "application/json; charset=utf-8",
success: function(json) {
if(json.hasError != null && json.hasError == "true"){
error = json.error;
alert(error);
}else{
//.... logic to output valid values
}
},//success
error:function(x, tm, m) {
alert(timeoutErr);
}
});
works just fine

Accessing ajax POST response in javascript

I'm making ajax POST request from javascript function:
function UpdateMetrics() {
$.ajax({
type: "POST",
url: "MyHandler.ashx?Param1=value1",
data: "{}",
contentType: "text/json; charset=utf-8",
dataType: "text",
success: function (msg) {
var jsonUpdatedData = msg;
...
}
});
}
From my handler, I'm sending json string with:
context.Response.write(json);
I think I'll get it in msg.
I also want to send other string (count). So I'm trying to use header info along with json data. So I added this line:
context.Response.Headers.Add("MaxCount",Convert.ToString(tempList.Count));
If this is right way to do it, how can I access it in my success function?
To access headers in your success function, add in 2 more arguments to your function, the status code and the jqXHR object, which you can read the documentation for at api.jquery.com.
So, your function should look like:
success: function (msg, status, jqXHR) {
var jsonUpdatedData = msg;
...
}
However, as pointed out in comments, it's probably best not to use the header to send data. You should probably just include it in the json you send out.
You also need to tell jQuery to interpret the response as json by setting
dataType: "json"
Otherwise, it will just be returned to you as text.
Your requirement to get the header data in ajax post success can be achieved using getResponseHeader method please refer the below code snippet.
function UpdateMetrics() {
var callback = $.ajax({
type: "POST",
url: "MyHandler.ashx?Param1=value1",
data: "{}",
contentType: "text/json; charset=utf-8",
dataType: "text",
success: function (msg) {
var jsonUpdatedData = msg;
var headerdata = callback.getResponseHeader("MaxCount");
// Where MaxCount is name provided in the header.
...
}
});
}
Thanks

Categories

Resources