I have this function, and every time I call it, I need the imagesUploadScript variable to be updated with a new URL. I've implemented in the server side a JSON response with the desired URL for each request, but I'm not able to get that JSON value with jQuery.
$(function () {
$('.editor').editorInsert({
editor: editor,
addons: {
images: {
imagesUploadScript: /* The url*/
}
});
});
I have tried this, but doesn't seem to work :S
$.getJSON("/admin/upload_url",function(result){
return JSON.stringify(result)
})
EDIT
I have restructured my code, this way my function accepts a callbacks as #Mohamad suggested and thanks to this question:
function getURL(callback) {
var url;
$.ajax({
type: "GET",
async: false,
url: "/admin/upload_url",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
url = data['url'];
callback(url);
} //success
});
}
But I'm not able to return the url for imagesUploadScript but yes this way
getURL(function(url){
console.log(url);
});
I'm confused, how should I declare this function inside the other one so imagesUploadScript get's a new URL every time is called ?
Thanks in advance for any help ! :D
Related
$(document).ready(function () {
$.ajax({
url: "/file_lines",
type: 'GET',
// contentType: 'application/json', // format of Data to be sent to the server
// data: 'json',//Data to be sent to the server
dataType: 'text', //The type of data that you're expecting back from the server.
success: function (lines) {
document.getElementById("tmp").innerHTML = lines
**console.log(document.getElementById("tmp").innerHTML)**
},
error: function (){
alert("get debug log's lines failed");
return false;
}
});
})
// console.log($('#tmp').html())
**var num = document.getElementById("tmp").innerHTML
console.log(num)**
I am so confuse that why I can get innerHtml value of "tmp" in the $(document).ready() but can not get this value outside $(document).ready()! I thought DOM object should be global. So I am quite confuse about this result. Could somebody help me?
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
I have this url as json object which is provided by google API.
https://www.googleapis.com/customsearch/v1?key=AIzaSyAo6DqmlMti9ID7lL532A7-6Miu1QHcMqI&cx=013881670411723352605:b1y6-jfsiki&q=web%20developer?alt=json-in-script&callback=listEvents
I want to use javaScript and want to see complete json object.This is my script code , but it doesn't work. please help me , i am struggling from 3 days.
function listEvents(root){
$.getJSON('https://www.googleapis.com/customsearch/v1?key=AIzaSyAo6DqmlMti9ID7lL532A7-6Miu1QHcMqI&cx=013881670411723352605:b1y6-jfsiki&q=web%20developer?alt=json-in-script&callback=listEvents', function(data) {*/
alert(root)
});
}
function init() {
listEvents();
}
window.onload = init;
Thanks in advance
You are giving a callback option in url that is again a call to listEvents(). That is not correct. Use your own success callback. this will work:
function listEvents() {
$.getJSON('https://www.googleapis.com/customsearch/v1?key=AIzaSyAo6DqmlMti9ID7lL532A7-6Miu1QHcMqI&cx=013881670411723352605:b1y6-jfsiki&q=web%20developer?alt=json-in-script', function (data) {
console.log(data)
});
}
Demo example
The output is in JSONP format and not JSON
JSONP({JSON})
Jquery JSONP: http://learn.jquery.com/ajax/working-with-jsonp/
(function($) {
var url = 'https://www.googleapis.com/customsearch/v1?key=AIzaSyAo6DqmlMti9ID7lL532A7-6Miu1QHcMqI&cx=013881670411723352605:b1y6-jfsiki&q=web%20developer?alt=json-in-script&callback=listEvents';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'listEvents',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json);
},
error: function(e) {
console.log(e.message);
}
});
})(jQuery);
BTW your Google Daily Limit Exceeded
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
I am trying to implement Repository pattern in JavaScript. I have ViewModel which i want to initialize with the data when i call Initialize method on it. Everything seems to be falling in places except that i am not able to return the data from my AJAX call. I can see that data is coming back from the ajax call but when i trying to capture the data in SomeViewModel's done function, it is null.
Can someone please point me out where i am going wrong here?
P.S: Please notice that i am not making Async call so the call chain is properly maintained.
This is how my Repository looks like:
function SomeRepository(){
this.LoadSomeData = function loadData()
{
$.ajax({
type: "POST",
url: "someUrl",
cache: true,
async: false,
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
//success: handleHtml,
success: function(data) {
alert('data received');
return data;
},
error: ajaxFailed
});
function ajaxFailed(xmlRequest) {
alert(xmlRequest.status + ' \n\r ' +
xmlRequest.statusText + '\n\r' +
xmlRequest.responseText);
}
}
};
This is how my ViewModel looks like:
function SomeViewModel(repository){
var self = this;
var def = $.Deferred();
this.initialize = function () {
var def = $.Deferred();
$.when(repository.LoadSomeData())
.done(function (data) {
def.resolve();
});
return def;
};
}
This is how i am calling from an aspx page:
var viewModel = new SomeViewModel(new SomeRepository());
viewModel.initialize().done(alert('viewmodel initialized'));
alert(viewModel.someProperty);
I have used successfully an auxiliar variable to put the ajax result, when ajax call is inside a function (only works if ajax is async=false) and i need the function does return the ajax result. I don't know if this is the best solution.
function ajaxFunction(){
var result='';
$.ajax({
type: "POST",
url: "someUrl",
cache: true,
async: false,
contentType: "application/json; charset=utf-8",
data: "{}",
dataType: "json",
//success: handleHtml,
success: function(data) {
alert('data received');
result=data;
},
error: ajaxFailed
});
return result;
}
Doesn't matter that it's synchronous (though it really shouldn't be). Returning a value from inside the ajax callback will not cause the value to be returned from the containing function.
Using asynchronous ajax is generally a much better idea anyway, but that will force you to create an API that allows its clients to pass in handlers to be called when the ajax request completes. To do that, you'd give your "LoadSomeData" function a parameter. A caller would pass in a function, and your ajax "success" handler would pass on the results (or some transformation of the results; depends on what it is that you're doing) to that callback. It's the same idea as the callbacks used in the ajax call itself.