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
Related
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.
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);
}
});
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
How can I add a JSON file in jsfiddle? I have a JSON file but I am not able to attach it in jsfiddle. I can make a JSON object and use it, but is there any way to add an external JSON file to a fiddle?
Myjson.com provides api, which runs in Jsfiddle.net.
Custom my myjson:
// Loading JSON with CROS
var url = 'https://api.myjson.com/bins/3ko1q';
$.ajax({
type: 'GET',
url: url,
async: false,
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert('success');
console.log(data);
},
error: function (e) {
alert('error');
console.log(e);
}
});
Myjson GET Example:
// 1. Create valid uri via POST
// 2. GET using newly created uri
var obj = {
"key": "value",
"key2": "value2"
};
var data = JSON.stringify(obj);
$("#clickMe").click(function () {
$.ajax({
url: "https://api.myjson.com/bins",
type: "POST",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, textStatus, jqXHR) {
// load created json
$.get(data.uri, function (data, textStatus, jqXHR) {
var json = JSON.stringify(data);
$("#data").val(json);
});
}
});
});
You can harness the power of Cross-Origin Resource Sharing (CORS) to achieve your task.
Basically how CORS works is that if the Access-Control-Allow-Orign header is set in the HTTP response, then the content loaded by AJAX can be used in our script regardless of the fact it is on the same domain or some other.
Now for your purpose, you can upload your local JSON file to Dropbox's Public folder and get a Public URL, that you can load by a simple AJAX call.
The AJAX call will succeed in this case because Dropbox sets the following value in the response Access-Control-Allow-Orign:* which means any domain can use the loaded content.
Jquery code will be something like this(you can even use pure JavaScript if you prefer ).
var url = 'https://dl.dropboxusercontent.com/u/94145612/example.json';
var myJsonData= {};
$.ajax({
type: 'GET',
url: url,
async: false,
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert('success');
console.log(data);
myJsonData= data;
},
error: function (e) {
alert('error');
console.log(e);
}
});
Example JSFiddle
Based on your comment, you want to use a pure JSON file as an external resource in a jsFiddle. You can't do this, because pure JSON is not JavaScript. Say you try to include http://example.com/foo.json as an external resource, and that file contains the following:
{"foo":"bar"}
This will result in Uncaught SyntaxError: Unexpected token :, because the JSON object is not valid JavaScript by itself.
But if you assign the JSON object to a variable, like so:
var foo = {"foo":"bar"};
then no problem.
Solution: use a modified version of your file to initialize a variable for use in the jsFiddle.
I have a problem. I'm trying to send content of a textarea with an ajax call, but it doesn't seem to be working, and I don't know why.
There's the method called GetStatus(string statusText) which need to receive the content.
Here's the javascript code:
$("#btnSaveStatus").on("click", function () {
var statusText = $(".textareaEdit").val();
$.ajax({
type: "GET",
url: "Default.aspx/GetStatus",
data: "{statusText:'" + statusText + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// $('#littlbioID').text(result.d);
}
});
});
Please advise. You should also know that I'm new into web development.
You can't have a request body in a GET request, you have to use a POST request for that
The string you are constrcting is not valid JSON since:
Property names must be strings
You have no idea what the user will enter in the textarea - it might contain characters with special meaning in JSON
Generate your JSON programatically.
{
type: "POST",
url: "Default.aspx/GetStatus",
data: JSON.stringify({
statusText: statusText
}),
// etc
Obviously, the server side of the process needs to be set up to accept a POST request with a JSON body (instead of the more standard URL Form Encoded format) as well.
Try this:
$("#btnSaveStatus").on("click", function () {
var statusText = $(".textareaEdit").val();
var jsonText = new Object();
jsonText.statusText = statusText;
$.ajax({
type: "POST",
url: "Default.aspx/GetStatus",
data: JSON.stringify(jsonText);,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// $('#littlbioID').text(result.d);
}
});
});