I can set data into the State.data of History.js, like this:
var pushStateData = {};
function RetrieveSearchResults(type, url, searchData) {//, showResetButton,
controlToFocus, navDirection) {
pushStateData = {
SearchType : type,
SearchData : searchData,
};
RetrievePageResults(true, url, pushStateData);
}
function RetrievePageResults(pushNewUrl, url, pushStateData) {
navigationInProgress = true;
if (pushNewUrl) {
if (window.History) {
window.History.pushState(pushStateData, null, url);
}
$.get(url, pushStateData.SearchData, function (reply) {
$("#search-results").html(reply);
navigationInProgress = false;
});
}
If I set a breakpoint on the window.History.pushState statement, in Chrome, I can clearly see pushStateData has the desired values.
However, when I try to retrieve the data:
$(window).bind("statechange", function (e) {
if (!navigationInProgress) {
var State = window.History.getState();
if (window.console && window.console.log) {
console.log("popstate", State, window.location.href);
}
RetrievePageResults(false, State.cleanUrl, State.data);
}
});
When I set a breakpoint on the RetrievePageResults statement,
The State.data object no longer has any of the values I set. State.data is defined, and is not null, but it is an empty object without any apparent values.
Thanks,
Scott
I don't see anything wrong with State.data, when you issue a pushState, make sure you call the History.js method:
History.pushState({state:1}, "State 1", "?state=1");
Where:
First Parameter => The data
Second Parameter => The name
Third Parameter => The url
It seems your not passing the state, and the data will only be present if and only if you call the History.pushState. When your visiting the URL directly (/?state=1) you would have no data in the state, data will only be available when navigating back/forward while pushing state via History.pushState.
side note: Make sure your navigationInProgress variable is fixed, you don't want it to be stalled there. Reset it when the $.get request failed when listening on the error callback. And when your pushNewUrl is false, reset the navigationInProgress attribute.
Related
I am writing a Firefox extension using the WebRequest. I am in a situation that when I receive the response, I want to look back and find the request associated with this response to retrieve a custom request header. My current code is like this:
browser.webRequest.onBeforeSendHeaders.addListener(
addCustomHeader, // here I add custom_header:value
{urls: ["<all_urls>"]},
["blocking", "requestHeaders"]
);
...
browser.webRequest.onHeadersReceived.addListener(
process_response, // here I want to get back to the request and retrieve the custom header value
{urls: ["<all_urls>"]},
["blocking", "responseHeaders"]
);
The value of custom_header is set as a global variable, which changes per each request. And when I receive the response of, say, request_1, I want to retrieve the header value from request_1 in the process_response() function. However, if I directly use the value, I found it may have been changed by subsequent requests, say request_2 or request_3.
I noticed the response has a requestId property, and I guess I can use it to find the corresponding request. However, I am not able to find any document or example that tells me how. I'd appreciate for any hint!
Use a global map variable:
const reqMap = (() => {
const data = new Map();
const MAX_AGE = 10 * 60e3; // 10 minutes
const cleanup = () => {
const cutOff = performance.now() - MAX_AGE;
data.forEach(({ time }, id) => time < cutOff && data.delete(id));
};
return {
set(id, value) {
cleanup();
data.set(id, {value, time: performance.now()});
},
pop(id) {
const {value} = data.get(id) || {};
data.delete(id);
return value;
},
};
})();
function onBeforeSendHeaders(details) {
reqMap.set(details.requestId, {any: 'data'});
}
function onHeadersReceived(details) {
const data = reqMap.pop(details.requestId);
if (data) {
// ............
}
}
Iam using asp.net mvc4 and facing some problem in accessing viewbag.price.
This is what i am doing:-
[HttpPost]
public ActionResult FillModel(int id)
{
var vehModel = db.Vehicle_Model.Where(vehMod => vehMod.MakeID == id).ToList().Select(vehMod => new SelectListItem() { Text = vehMod.Model, Value = vehMod.pkfModelID.ToString() });
ViewBag.Price = 100;
return Json(vehModel, JsonRequestBehavior.AllowGet);
}
i am calling above using below:-
$.ajax({
url: '#Url.Action("FillModel","Waranty")',
type: 'post',
data: { id: id },
dataType: 'json',
success: function (data) {
$('#ddModel').empty();
$.each(data, function (index, val) {
var optionTag = $('<option></option>');
$(optionTag).val(val.Value).text(val.Text);
$('#ddModel').append(optionTag);
});
var a = '#ViewBag.Price';
},
error: function () {
alert('Error');
}
});
But i am not able to access ViewBag.Price.
Anyone know the reason??
thanks
The reason you aren't able to access items from the ViewBag inside your ajax success function is because the view that contains your script has already been rendered by the Razor view engine, effectively setting the variable a to whatever the value of #ViewBag.Price was at the time the page was rendered.
Looking at the process flow might be helpful:
(1) The request comes in for the view that has your script fragment in it.
(2) The controller method that returns your view is called.
(3) The Razor view engine goes through the view and replaces any references to #ViewBag.Price in your view with the actual value of ViewBag.Price. Assuming ViewBag.Price doesn't have a value yet, the success function in your script is now
success: function (data) {
$('#ddModel').empty();
$.each(data, function (index, val) {
var optionTag = $('<option></option>');
$(optionTag).val(val.Value).text(val.Text);
$('#ddModel').append(optionTag);
});
var a = '';
}
(4) The rendered html gets sent to the client
(5) Your ajax request gets triggered
(6) On success, a gets set to the empty string.
As you had mentioned in the comments of your question, the solution to this problem is to include a in the Json object returned by your action method, and access it using data.a in your script. The return line would look like
return Json(new {
model = vehModel,
a = Price
});
Keep in mind that if you do this, you'll have to access model data in your ajax success function with data.model.Field. Also, you shouldn't need to specify the JsonRequestBehavior.AllowGet option, since your method only responds to posts and your ajax request is a post.
So, I'm using FineUploader 3.3 within a MVC 4 application, and this is a very cool plugin, well worth the nominal cost. Now, I just need to get it working correctly.
I'm pretty new to MVC and absolutely new to passing back JSON, so I need some help getting this to work. Here's what I'm using, all within doc.ready.
var manualuploader = $('#files-upload').fineUploader({
request:
{
endpoint: '#Url.Action("UploadFile", "Survey")',
customHeaders: { Accept: 'application/json' },
params: {
//variables are populated outside of this code snippet
surveyInstanceId: (function () { return instance; }),
surveyItemResultId: (function () { return surveyItemResultId; }),
itemId: (function () { return itemId; }),
imageLoopCounter: (function () { return counter++; })
},
validation: {
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png', 'bmp']
},
multiple: true,
text: {
uploadButton: '<i class="icon-plus icon-white"></i>Drop or Select Files'
},
callbacks: {
onComplete: function(id, fileName, responseJSON) {
alert("Success: " + responseJSON.success);
if (responseJSON.success) {
$('#files-upload').append('<img src="img/success.jpg" alt="' + fileName + '">');
}
}
}
}
EDIT: I had been using Internet Explorer 9, then switched to Chrome, Firefox and I can upload just fine. What's required for IE9? Validation doesn't work, regardless of browser.
Endpoint fires, and file/parameters are populated, so this is all good! Validation doesn't stop a user from selecting something outside of this list, but I can work with this for the time being. I can successfully save and do what I need to do with my upload, minus getting the OnComplete to fire. Actually, in IE, I get an OPEN/SAVE dialog with what I have currently.
Question: Are the function parameters in onComplete (id, filename, responseJSON) getting populated by the return or on the way out? I'm just confused about this. Does my JSON have to have these parameters in it, and populated?
I don't do this (populate those parameters), and my output method in C# returns JsonResult looking like this, just returning 'success' (if appropriate):
return Json(new { success = true });
Do I need to add more? This line is after the saving takes place, and all I want to do is tell the user all is good or not. Does the success property in my JSON match up with the responseJSON.success?
What am I missing, or have wrong?
Addressing the items in your question:
Regarding restrictions inside of the "select files" dialog, you must also set the acceptFiles validation option. See the validation option section in the readme for more details.
Your validation option property in the wrong place. It should not be under the request property/option. The same is true for your text, multiple, and callbacks options/properties. Also, you are not setting your callbacks correctly for the jQuery plug-in.
The open/save dialog in IE is caused by your server not returning a response with the correct "Content-Type" header. Your response's Content-Type should be "text/plain". See the server-side readme for more details.
Anything your server returns in it's response will be parsed by Fine Uploader using JSON.parse when handling the response client-side. The result of invoking JSON.parse on your server's response will be passed as the responseJSON parameter to your onComplete callback handler. If you want to pass specific information from your server to your client-side code, such as some text you may want to display client-side, the new name of the uploaded file, etc, you can do so by adding appropriate properties to your server response. This data will then be made available to you in your onComplete handler. If you don't have any need for this, you can simply return the "success" response you are currently returning. The server-side readme, which I have linked to, provides more information about all of this.
To clarify what I have said in #2, your code should look like this:
$('#files-upload').fineUploader({
request: {
endpoint: '#Url.Action("UploadFile", "Survey")',
customHeaders: { Accept: 'application/json' },
params: {
//variables are populated outside of this code snippet
surveyInstanceId: (function () { return instance; }),
surveyItemResultId: (function () { return surveyItemResultId; }),
itemId: (function () { return itemId; }),
imageLoopCounter: (function () { return counter++; })
}
},
validation: {
allowedExtensions: ['jpeg', 'jpg', 'gif', 'png', 'bmp']
},
text: {
uploadButton: '<i class="icon-plus icon-white"></i>Drop or Select Files'
}
})
.on('complete', function(event, id, fileName, responseJSON) {
alert("Success: " + responseJSON.success);
if (responseJSON.success) {
$('#files-upload').append('<img src="img/success.jpg" alt="' + fileName + '">');
}
});
I have written this function in jQuery:
function checkAvailability(value) {
var result = true;
$.getJSON("registration/availability", { username: value }, function(availability) {
if (!availability)
result = false;
alert("in getJSON: " + result);
});
alert(result);
return result;
}
I have got alert from 'getJSON' after this second. Why has it happened this way?
I have Spring MVC project and Controller method which checks username availability. Controller method works properly. But I receive final result too late. How can I synchronize it to return properly value in my function?
EDIT
I am using this function in jQuery validate. I have extracted checkAvailability() function during my test.
$.validator.addMethod("checkAvailability", function(value, element, param) {
var das = checkAvailability(value);
return das;
}, jQuery.format("Someone already has that username. Please try another one."));
And this is my form validate:
$(".form").validate({
rules: {
username: {
checkAvailability: true
},
....
},
messages: {
}
});
EDIT 2
This is my Controller method. It returns boolean value. If username was taken it would return false value.
#RequestMapping(value="/registration/availability", method = RequestMethod.POST)
public #ResponseBody boolean getAvailability(#RequestParam String username) {
List<User> users = getAllUsers();
for (User user : users) {
if (user.getUsername().equals(username)) {
return false;
}
}
return true;
}
Why does this behave this way?
$.getJSON is shorthand for making an AJAX request. The 'A' in ajax stands for asynchronous. Meaning, the javascript engine fires the getJSON call and then immediately executes the next lines, which is alert(result); return result;
The actual value as returned by the web service will be received by your code at a later point in time. The success function that you passed into getJSON will be called once the js engine receives the response from the server. As you can see, it is too late by that point.
Further reading: https://developer.mozilla.org/en/AJAX
What can I do to make this work?
That depends on your situation. Who is calling checkAvailabilty? If you post some code on how this function is being used, I can give examples with my suggestions.
Off the top of my head, you could either make use of jquery deferreds, nice article on the same. Or you could pass in a callback function that is executed from inside your success function.
EDIT:
http://docs.jquery.com/Plugins/Validation/Methods/remote#options
The serverside resource is called via $.ajax (XMLHttpRequest) and gets
a key/value pair, corresponding to the name of the validated element
and its value as a GET parameter. The response is evaluated as JSON
and must be true for valid elements, and can be any false, undefined
or null for invalid elements,
To get a real world idea, check the demo http://jquery.bassistance.de/validate/demo/captcha/
Open Firebug or the developer tools of your choice. Go to the tab that lets you see AJAX requests. Enter the captcha, submit. Check ajax request as listed in the developer tool. Notice the query string parameters. Notice the response. Its a simple 'true' or 'false'.
Not sure if this helps or not but you can use
var result;
$.ajax( {
url : "registration/availability",
data : data,
async : false //syhcrononous ajax request ;)
}).done(function(data) {
result = data;
});
for more info you can refer JQuery AJAX doc
I need to store some data client side and this data is too large to store it in a cookie. LocalStorage seemed like the perfect way of doing this but the thing is that the website that i will be using this has some parts that work on https and others with just http and as local storage can't access data from https that you set with http this doesn't seem like a viable solution anymore.
Any idea if there is any solution to this? Any other alternatives?
Store all data on one domain, e.g. https://my.domain.org/.
On https protocols, simply use localStorage.setItem('key', 'value') to save the data.
On http protocols, embed a https frame, and use postMessage to save the data:
Demo: http://jsfiddle.net/gK7ce/4/ (with the helper page being located at http://jsfiddle.net/gK7ce/3/).
// Script at https://my.domain.org/postMessage
window.addEventListener('message', function(event) {
// Domain restriction (to not leak variables to any page..)
if (event.origin == 'http://my.domain.org' ||
event.origin == 'https://my.domain.org') {
var data = JSON.parse(event.data);
if ('setItem' in data) {
localStorage.setItem(data.setItem, data.value);
} else if ('getItem' in data) {
var gotItem = localStorage.getItem(data.getItem);
// See below
event.source.postMessage(
'#localStorage#' + data.identifier +
(gotItem === null ? 'null#' : '#' + gotItem),
event.origin
);
} else if ('removeItem' in data) {
localStorage.removeItem(data.removeItem);
}
}
}, false);
On the http(s) page, the frame can be embedded as follows (replace https://my.mydomain.com with the actual URL. Note that you can simply get a reference to the frame, and use the src attribute):
<iframe name="myPostMessage" src="https://my.domain.org/postMessage" style="display:none;"></iframe>
// Example: Set the data
function LSsetItem(key, value) {
var obj = {
setItem: key,
value: value
};
frames['myPostMessage'].postMessage(JSON.stringify(obj), 'https://my.domain.com');
}
LSsetItem('key', 'value');
Note that the method is asynchronous, because of postMessage. An implementation of the getItem method has to be implemented differently:
var callbacks = {};
window.addEventListener('message', function(event) {
if (event.source === frames['myPostMessage']) {
var data = /^#localStorage#(\d+)(null)?#([\S\s]*)/.exec(event.data);
if (data) {
if (callbacks[data[1]]) {
// null and "null" are distinguished by our pattern
callbacks[data[1]](data[2] === 'null' ? null : data[3]);
}
delete callbacks[data[1]];
}
}
}, false);
function LSgetItem(key, callback) {
var identifier = new Date().getTime();
var obj = {
identifier: identifier,
getItem: key
};
callbacks[identifier] = callback;
frames['myPostMessage'].postMessage(JSON.stringify(obj), 'https://my.domain.com');
}
// Usage:
LSgetItem('key', function(value) {
console.log('Value: ' + value);
});
Note that each callback is stored in a hash. Each message also contains an identifier, so that the window which receives the message calls the correct corresponding callback.
For completeness, here's the LSremoveItem method:
function LSremoveItem(key) {
var obj = {
removeItem: key
};
frames['myPostMessage'].postMessage(JSON.stringify(obj), 'https://my.domain.com');
}