JavaScript - Intercept any ajax request to add parameter - javascript

I'm creating a simple JavaScript code to intercept any AJAX request with the idea of add an extra param that I need to read in the server side (Java). Until now I have this code that I have tested with different kind of request, with and without jquery as well, works fine:
(function(open) {
XMLHttpRequest.prototype.send = function() {
console.log('Start a new AJAX request');
var myExtraParam = 'ABC123'; // value that I need to send, but it's dynamically, it will come from a function
open.apply(this);
};
})(XMLHttpRequest.prototype.send);
What I have been looking is the way to attach an extra parameter, on this scenario, the variable "myExtraParam" when I call the apply method.
I'm using plain JavaScript
EDIT:
As param, I'm asuming a value that I can read in the server, like when you do: myurl?myExtraParam=ABC123

Setting a parameter seems like a lot of work dealing with querystring or appending it to the request body. Safer thing seems to be using a header.
(function() {
var orgSend = window.XMLHttpRequest.prototype.send;
window.XMLHttpRequest.prototype.send = function() {
this.setRequestHeader("foo", "bar")
return orgSend.apply(this, [].slice.call(arguments));
};
})();

Related

jQuery function that call controller method from client side every 10 seconds mvc razor

I got a problem that i cannot solve cause of my incomplete knowledge of jQuery/Java syntax but which problem can be fast solved by someone with more experience than me.
I want to build a simple script to run on client side that will call a controller method every 10 seconds (method is responsible for receive data from message server)
all i do so far is search web and more i read more i get confused..
basic need are
use jQuery ( there was a tip that says it is best choice)
call method every 10 seconds
method i want to call is: "callGetMessagesFromClientSide" and it's in CoordinatorsController
<script src="~/Scripts/jquery-2.1.1.js" type="text/javascript"></script>
<script>
var callETs = setInterval(function () { callMessages() }, 10000);
function callMessages()
{
var url = #Url.Action("callGetMessagesFromClientSide", "Coordinators")
$.get(url);
}
</script>
You need to wrap generated URL in quotes.
Use
var url = '#Url.Action("callGetMessagesFromClientSide", "Coordinators")';
instead of
var url = #Url.Action("callGetMessagesFromClientSide", "Coordinators")
Rest of your code should work.
function callMessages() {
var url = '#Url.Action("callGetMessagesFromClientSide", "Coordinators")';
$.get(url, function(response) {
//Perform some operation in the callback if require
});
}
You're most of the way there, try this:
function callMessages()
{
var url = '#Url.Action("callGetMessagesFromClientSide", "Coordinators")';
var update = $.get(url);
update.done(function(response) {
//handle server response
});
}
depending on what the server returns (e.g. JSON, HTML etc) depends on how you handle it

Call a dynamic python function after the webpage is loaded in Django

I have a function in python which will return one of many Image URLs. I would like to implement a button on a webpage made with django which will change the image's source to the returned value. The issue I've run into is that django template tags are only accessible when the page is rendered, as explained here. Since the real code cannot be recreated in javascript, is there a workaround to get access to the python function's return data every time the button is pressed?
Here is some code to clarify my question:
class Foo(models.Model):
def get_image_url():
if(random.randint(0,1)):
return 'http://img1.jpg'
else:
return 'http://img2.jpg'
This is how I would want it to behave in javascript, if it were possible.
function updateImage(){
document.getElementById("testImage").src="{{ foo.get_image_url }}";
}
Thanks.
Sounds like you have to use AJAX for this. You can define a Django view which returns a JSON message with something like:
{
status: "ok",
url: "img1.jpg"
}
So in your code, you can define an event handler (in JavaScript) with something like this:
// Attach a listener to a button for a click event,
document.getElementById("testImageButton").addEventListener("click", function() {
var xhr = new XMLHttpRequest();
// This URL returns the above JSON.
xhr.open("GET", "/images/random");
xhr.onloadend = function() {
// Should have error handling in case response does not return correctly.
var imageResult = JSON.parse(xhr.response);
if(imageResult['status'] == 'ok') {
// update the image src
document.getElementById("testImage").setAttribute("src", imageResult['url']);
}
}
xhr.send()
})
So the only "dynamic function part" is whatever is inside your Django view function.

How to pass data from one HTML page to another HTML page using JQuery?

I have two HTML pages that work in a parent-child relationship in this way:
The first one has a button which does two things: First it requests data from the database via an AJAX call. Second it directs the user to the next page with the requested data, which will be handled by JavaScript to populate the second page.
I can already obtain the data via an ajax call and put it in a JSON array:
$.ajax({
type: "POST",
url: get_data_from_database_url,
async:false,
data: params,
success: function(json)
{
json_send_my_data(json);
}
});
function json_send_my_data(json)
{
//pass the json object to the other page and load it
}
I assume that on the second page, a "document ready" JavaScript function can easily handle the capture of the passed JSON object with all the data. The best way to test that it works is for me to use alert("My data: " + json.my_data.first_name); within the document ready function to see if the JSON object has been properly passed.
I simply don't know a trusted true way to do this. I have read the forums and I know the basics of using window.location.url to load the second page, but passing the data is another story altogether.
session cookie may solve your problem.
On the second page you can print directly within the cookies with Server-Script tag or site document.cookie
And in the following section converting Cookies in Json again
How about?
Warning: This will only work for single-page-templates, where each pseudo-page has it's own HTML document.
You can pass data between pages by using the $.mobile.changePage() function manually instead of letting jQuery Mobile call it for your links:
$(document).delegate('.ui-page', 'pageinit', function () {
$(this).find('a').bind('click', function () {
$.mobile.changePage(this.href, {
reloadPage : true,
type : 'post',
data : { myKey : 'myVal' }
});
return false;
});
});
Here is the documentation for this: http://jquerymobile.com/demos/1.1.1/docs/api/methods.html
You can simply store your data in a variable for the next page as well. This is possible because jQuery Mobile pages exist in the same DOM since they are brought into the DOM via AJAX. Here is an answer I posted about this not too long ago: jQuery Moblie: passing parameters and dynamically load the content of a page
Disclaimer: This is terrible, but here goes:
First, you will need this function (I coded this a while back). Details here: http://refactor.blog.com/2012/07/13/porting-javas-getparametermap-functionality-to-pure-javascript/
It converts request parameters to a json representation.
function getParameterMap () {
if (window.location.href.indexOf('?') === (-1)) {
return {};
}
var qparts = window.location.href.split('?')[1].split('&'),
qmap = {};
qparts.map(function (part) {
var kvPair = part.split('='),
key = decodeURIComponent(kvPair[0]),
value = kvPair[1];
//handle params that lack a value: e.g. &delayed=
qmap[key] = (!value) ? '' : decodeURIComponent(value);
});
return qmap;
}
Next, inside your success handler function:
success: function(json) {
//please really convert the server response to a json
//I don't see you instructing jQuery to do that yet!
//handleAs: 'json'
var qstring = '?';
for(key in json) {
qstring += '&' + key + '=' + json[key];
qstring = qstring.substr(1); //removing the first redundant &
}
var urlTarget = 'abc.html';
var urlTargetWithParams = urlTarget + qstring;
//will go to abc.html?key1=value1&key2=value2&key2=value2...
window.location.href = urlTargetWithParams;
}
On the next page, call getParameterMap.
var jsonRebuilt = getParameterMap();
//use jsonRebuilt
Hope this helps (some extra statements are there to make things very obvious). (And remember, this is most likely a wrong way of doing it, as people have pointed out).
Here is my post about communicating between two html pages, it is pure javascript and it uses cookies:
Javascript communication between browser tabs/windows
you could reuse the code there to send messages from one page to another.
The code uses polling to get the data, you could set the polling time for your needs.
You have two options I think.
1) Use cookies - But they have size limitations.
2) Use HTML5 web storage.
The next most secure, reliable and feasible way is to use server side code.

Pass additional parameter to a JSONP callback

For a project of mine I need to do multiple calls to a (remote) API using JSONP for processing the API response. All calls use the same callback function. All the calls are generated dynamically on the client's side using JavaScript.
The problem is as follows: How do I pass additional parameters to that callback function in order to tell the function about the request parameters I used. So, e.g., in the following example, I need the myCallback function to know about id=123.
<script src="http://remote.host.com/api?id=123&jsonp=myCallback"></script>
Is there any way to achieve this without having to create a separate callback function for each of my calls? A vanilla JavaScript solution is preferred.
EDIT:
After the first comments and answers the following points came up:
I do not have any control over the remote server. So adding the parameter to the response is not an option.
I fire up multiple request concurrently, so any variable to store my parameters does not solve the problem.
I know, that I can create multiple callbacks on the fly and assign them. But the question is, whether I can avoid this somehow. This would be my fallback plan, if no other solutions pop up.
Your options are as follows:
Have the server put the ID into the response. This is the cleanest, but often you cannot change the server code.
If you can guarantee that there is never more than one JSONP call involving the ID inflight at once, then you can just stuff the ID value into a global variable and when the callback is called, fetch the id value from the global variable. This is simple, but brittle because if there are every more than one JSONP call involving the ID in process at the same time, they will step on each other and something will not work.
Generate a unique function name for each JSONP call and use a function closure associated with that function name to connect the id to the callback.
Here's an example of the third option.
You can use a closure to keep track of the variable for you, but since you can have multiple JSON calls in flight at the same time, you have to use a dynamically generated globally accessible function name that is unique for each successive JSONP call. It can work like this:
Suppose your function that generate the tag for the JSONP is something like this (you substitute whatever you're using now):
function doJSONP(url, callbackFuncName) {
var fullURL = url + "&" + callbackFuncName;
// generate the script tag here
}
Then, you could have another function outside of it that does this:
// global var
var jsonpCallbacks = {cntr: 0};
function getDataForId(url, id, fn) {
// create a globally unique function name
var name = "fn" + jsonpCallbacks.cntr++;
// put that function in a globally accessible place for JSONP to call
jsonpCallbacks[name] = function() {
// upon success, remove the name
delete jsonpCallbacks[name];
// now call the desired callback internally and pass it the id
var args = Array.prototype.slice.call(arguments);
args.unshift(id);
fn.apply(this, args);
}
doJSONP(url, "jsonpCallbacks." + name);
}
Your main code would call getDataForId() and the callback passed to it would be passed the id value like this followed by whatever other arguments the JSONP had on the function:
getDataForId(123, "http://remote.host.com/api?id=123", function(id, /* other args here*/) {
// you can process the returned data here with id available as the argument
});
There's a easier way.
Append the parameter to your url after '?'. And access it in the callback function as follows.
var url = "yourURL";
url += "?"+"yourparameter";
$.jsonp({
url: url,
cache: true,
callbackParameter: "callback",
callback: "cb",
success: onreceive,
error: function () {
console.log("data error");
}
});
And the call back function as follows
function onreceive(response,temp,k){
var data = k.url.split("?");
alert(data[1]); //gives out your parameter
}
Note: You can append the parameter in a better way in the URL if you already have other parameters in the URL. I have shown a quick dirty solution here.
Since it seems I can't comment, I have to write an answer. I've followed the instructions by jfriend00 for my case but did not receive the actual response from the server in my callback. What I ended up doing was this:
var callbacks = {};
function doJsonCallWithExtraParams(url, id, renderCallBack) {
var safeId = id.replace(/[\.\-]/g, "_");
url = url + "?callback=callbacks." + safeId;
var s = document.createElement("script");
s.setAttribute("type", "text/javascript");
s.setAttribute("src", url);
callbacks[safeId] = function() {
delete callbacks[safeId];
var data = arguments[0];
var node = document.getElementById(id);
if (data && data.status == "200" && data.value) {
renderCallBack(data, node);
}
else {
data.value = "(error)";
renderCallBack(data, node);
}
document.body.removeChild(s);
};
document.body.appendChild(s);
}
Essentially, I compacted goJSONP and getDataForUrl into 1 function which writes the script tag (and removes it later) as well as not use the "unshift" function since that seemed to remove the server's response from the args array. So I just extract the data and call my callback with the arguments available. Another difference here is, I re-use the callback names, I might change that to completely unique names with a counter.
What's missing as of now is timeout handling. I'll probably start a timer and check for existence of the callback function. If it exists it hasn't removed itself so it's a timeout and I can act accordingly.
This is a year old now, but I think jfriend00 was on the right track, although it's simpler than all that - use a closure still, just, when specifying the callback add the param:
http://url.to.some.service?callback=myFunc('optA')
http://url.to.some.service?callback=myFunc('optB')
Then use a closure to pass it through:
function myFunc (opt) {
var myOpt = opt; // will be optA or optB
return function (data) {
if (opt == 'optA') {
// do something with the data
}
else if (opt == 'optB') {
// do something else with the data
}
}
}

How to Force Javascript to Execute within HTML Response to Ajax Request

We're using Prototype for all of our Ajax request handling and to keep things simple we simple render HTML content which is then assigned to the appropriate div using the following function:
function ajaxModify(controller, parameters, div_id)
{
var div = $(div_id);
var request = new Ajax.Request
(
controller,
{
method: "post",
parameters: parameters,
onSuccess: function(data) {
div.innerHTML = data.responseText;
},
onFailure: function() {
div.innerHTML = "Information Temporarily Unavailable";
}
}
);
}
However, I occasionally need to execute Javascript within the HTML response and this method appears incapable of doing that.
I'm trying to keep the list of functions for Ajax calls to a minimum for a number of reasons so if there is a way to modify the existing function without breaking everywhere that it is currently being used or a way to modify the HTML response that will cause any embedded javascript to execute that would great.
By way of note, I've already tried adding "evalJS : 'force'" to the function to see what it would do and it didn't help things any.
The parameter is:
evalScripts:true
Note that you should be using Ajax.Updater, not Ajax.Request
See: http://www.prototypejs.org/api/ajax/updater
Ajax.Request will only process JavaScript if the response headers are:
application/ecmascript,
application/javascript,
application/x-ecmascript,
application/x-javascript,
text/ecmascript, text/javascript,
text/x-ecmascript, or
text/x-javascript
Whereas Ajax.Updater will process JS is evalScripts:true is set. Ajax.Request is geared toward data transport, such as getting a JSON response.
Since you are updating HTML you should be using Ajax.Updater anyways.
Does setting evalScripts: true as an option help?
You should be able to do something like this:
div.innerHTML = "<div onclick='someOtherFunctionTocall();'>";
If you need to execute something at the same time as injecting the HTML, can you modify the signature of ajaxModify() by passing another parameter, which will be the javascript function you're going to execute (if it's not null - which let's you keep it optional, as you surely won't want to execute something on EVERY AJAX response).
Just execute a custom my_function() after the ajax response
div.innerHTML=...ajax response text...
my_function()
then execute any function inside the custom my_function()
function my_function() {
function_1()
...
}
Note that my_function() should be somewhere outside the div.innerHTML.
you need to use eval() function to run the javascript in Ajax repose
this can be use full to separate the script and run it
function PaseAjaxResponse(somemixedcode)
{
var source = somemixedcode;
var scripts = new Array();
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
scripts.push(source.substring(s_e+1, e));
source = source.substring(0, s) + source.substring(e_e+1);
}
for(var x=0; x<scripts.length; x++) {
try {
eval(scripts[x]);
}
catch(ex) {
}
}
return source;
}
alliteratively for more information see this
http://www.yasha.co/Ajax/execute-javascript-on-Ajax-return/article-2.html

Categories

Resources