AJAX + dynamically adding java script function to the page - javascript

I am loading a portion of page using AJAX calls, which may contain script functions defined in them . Which are attached with the controls being loaded with different events. Now the problem is that when those events triggered i got the error "object not found" which indicate the function is not found/defined. While using Firebug i can see that the function is defined and available. So how can i make sure that browser can find the respective function.
I tried but either i am missing some thing or either its not working, Here is what i am doing
Page
--->Partial View A
----->Partial View B
Now Page Loads Partial A with Ajax Calls which further loads Partial B with Ajax Calls.Both Partial A & B contains few java script function that logically only associated with them not with master page.
The pages loads fine except the functions could not execute as "Object Not Found" comes in.

You should define functions using this syntax:
myFunction = function(foo) {}
not this syntax
function myFunction(foo) {}
The second form won't work when eval()'d (which is probably what's happening)

If you are using a framework or library you have to set a parameter in order to evaluate the script present in the response of the ajax request. It's usualy called evalScripts
evalScripts:true
You can also use the callbacks (success/error) of the request to trigger the events, so that it's easier to keep the code in one place and to avoid situations like this.
If you are using plain javasciprt and the XmlHttpObject, then you have to manually find all the script tags in your response and then eval() them.

Related

Pass Go function to html/js button "onclick" response

I am using Go's "net/http" package to pass data between the html and the backend in Go. For example, we can used the location of an image like this:
<img src={{.MyPicture}} width=200 height=auto/>
We can do the same thing to pass in functions to the html and call them:
{{if .MyBool}}
{{.MyFunction}}
{{end}}
Now my question is: how do I set the response of a button to call my function? I would expect this to work, but it doesn't:
<button onclick={{.ShowMoreLinks}}>Show more!</button>
I get "[js] Declaration or statement expected." I've tried wrapping it in a script (both inline and in the header), but neither of these seem to work. JS can't handle the passed in variable.
Actually, you're using Go's template mechanism to prepare the HTML that you send to the browser. This only fills in placeholders and ultimately only produces a string (in this case HTML) that will be sent over the network to the browser for interpretation. It's the browser that can only handle interactivity with the user via events such as "onclick". Furthermore, these events have to be Javascript code, like a JS expression or a function call:
onclick="jsFunction()"
You could make your Go template provide the function to be called in the placeholder:
onclick="{{.JSFuncCall}}"
Here ".JSFuncCall" would have to evaluate to some JS function name (and the parentheses to make the call) that you must have defined in your JS client-side code. That Javascript function could then make an XHR call to the server at some specific URL that triggers a Go handler, runs the Go code you want to run, and then returns a response that you can then handle back in the JS function.

I cannot do anything from the AWS.Request.send() callback

I'm using the AWS S3 Javascript SDK and i am trying to do some operations as using external functions or append some HTML code in a HTML div etc. all these things from my callback send() but nothing happens i get errors whereas i don't have any problem when i'm making these stuffs outside that send().
I have absolutely to write some specific code involving external functions inside this send() that just can't be made outside . How to resolve this issue ?
You can have a glance on the AWS.request.send() here

How to use external ajax response in Chrome Plugin

I have a existing file ajax,js in my website that makes an ajax request and creates a global JSON object, searchResult using that response. Now I am creating a Chrome plugin, that requires this JSON Object inside it. I have a content script for the plugin viz. plugin.js and I want to include the object inside plugin.js file.
When I try to log window.searchResult from within plugin.js, it shows as undefined.
but when I use browser console, it shows the value as expected.
Please help me with this.
Problem
Chrome content scripts and the page's own scripts live in isolated worlds.
Content scripts execute in a special environment called an isolated world. They have access to the DOM of the page they are injected into, but not to any JavaScript variables or functions created by the page.
Your code works in the console, since you execute it by default in the page's context. To see what the extension sees, you need to switch it.
Solution 1a
First, the generic solution (works even if you don't control the webpage)
There is a way around this, by injecting some code directly into the page's "world" (or properly called, context).
After injecting the code, your page-level script needs to communicate with the content script to pass the data. It's possible with custom DOM events (as, as you remember, DOM is shared). The page-level script sends an event with the data in the event's details.
Alternatively, you can just attach the data to some DOM node, say, an invisible <div>.
Solution 1b
Since you said it's your page, you can skip the inject-into-the-page step and have a listener ready in the page's own code.
The content script sends a custom event to request the data, and the page answers passes the data back as described in 1a.
Solution 2
In theory, you don't even need a content script.
You can use the "externally_connectable" mechanism to speak with the page directly.
Note though that the page has to initiate the conversation.

call a javascript function returned inside an xmlhttprequest

I have multiple forms dynamically being created via an xmlhttp request to a php script.
everything works except each returned chunk (form in my case) has a javascript as part of the returned packet to validate the form. There are MANY forms, all with different validations, and not all are loaded, only ones needed based on previous form response. How do I call the function?
The form is put inside a . I keep getting object or function undefined when I call the function.
It is impractical to load ALL the validation scripts at once not to mention the file bloat it causes.
I prefer not using jquery or other libraries as they have many functions not needed wich also adds to the bloat.
thnks!
Gary

Javascript difference between eval() and appending script tags

I was wondering if someone could explain the difference between using Javascript's eval(), and another approach, like using JQuery to create script tags and then appending that element to the page:
eval(somecode);
vs.
$("<script type='text/javascript'>"+somecode+"</script>").appendTo("head");
Not sure if this is relevant, but here's the context: I'm working with a version of the Drupal Popups module whose basic purpose is to easily turn regular links into popups by AJAX'ing an entire page request and appending it to the page in a modal window. This frequently includes external CSS and Javascript files. In an effort to improve the performance of all this AJAX loading I switched over to use AJAX queueing, and I changed an eval() of external scripts into the alternative listed about. However, that caused sporadic Javscript bugs on various other pages.
Well one (as far as differences go) is eval will return the result of an expression.
var result = eval('3+4'); // result = 7
As long as your javascript string is in the structure of a script block, i would suggest injecting it within a script tag/
Adding script tags will load the scripts synchronously, whereas loading when you eval text via XHR, that was loaded asynchronously. Because of the async, the scripts were probably loaded out of order.
Note there are a billion if-but-then cases to this, but I'm guessing this is the case based on your scenario.
Now, you could load the XHR synchronously, but then things will drastically slow down. Browsers can load six (ish) scripts at once but execute them in order. The XHR will load one at a time.
I strongly suggest using JSON-P.
Add a callback function name on the outgoing AJAX request by creating a script node on the fly (with src=[url]), and let the callback function get called with json data. You define the callback function in your page (properly namespaced) and put your update logic inside it.
The advantage of dynamic script node callback is that there is no same-domain restriction like in XHR.
For example, your site is www.foobar.com and some webservices are hosted on www.foobarapi.com. you create a script node in runtime with src="http://www.foobarapi.com/baz?a=foo1&b=foo2&callback=foo.bar.baz"
Meanwhile in your page, you have:
foo.bar.baz = function(data) {
// use the data
}
And your backend service, say a php, can look like:
$a=$GET['a'];
$b=$GET['b'];
$callback = $GET['callback'];
$c = someCalc($a, $b);
echo $callback . "({ \"c\" : $c });";

Categories