Simple thing!!..In asp.net- MVC project. i have a button . and i have a external javascript file mydata.js. in that file contains a function checkJS().
function checkJs()
{
debugger;
alert("your output!!!");
}
My code:
<div id="mydivid" style="background-color:lightblue;">
STAGE
</div>
<input type="button" id="btnid" value="Load Data" />
When i click a button , Its just call the jQuery click function
$(document).ready(function () {
$("#btnid").click(function (event) {
debugger;
$.getScript('mydata.js', function() {
// debugger;
checkJs();
});
});
});
I used initialy 1.12.4.js library file in the head tag
and i added my external js file in head tag.
what is the problem in my code. why the button click did not reached the external method.
1.Make sure that jQuery library added before your external java-script file.
When you ensure the first point do like below:-
$(document).ready(function () {
$("#btnid").click(function (event) {
checkJs();
});
});
2.If you want to use $.getScript() then do like below:-
$(document).ready(function () {
$("#btnid").click(function (event) {
$.getScript('mydata.js').done(function(data, textStatus) { // check the file path of mydata.js is correct or not?
checkJs();
});
});
});
The above code will work only when you have jQuery library added before this code and you remove the external JavaScript file path from your head.
Note:-
data:- returned data from external script
textStatus:- status of the call to external script (plain-text like "Success")
For more knowledge check this link:- jQuery.getScript()
You can directly call your function without getScript if you have already included the mydata.js in head.
If not, and want to do it with getScript then make sure you are giving correct path, load js in done callback and if still not then check if calls goes to fail callback.
$(document).ready(function () {
$("#btnid").click(function (event) {
debugger;
$.getScript('mydata.js').done(function(data, textStatus, jqxhr) {
checkJs();
}).fail(function(){
if(arguments[0].readyState==0){
//script failed to load
}else{
//script loaded but failed to parse
alert(arguments[2].toString());
}
})
});
});
Done callback has 3 parameters with has following values in it.
data: has the returned data(script)
textStatus: it returns the status in plain text, e.g. "Success"
jqxhr : its jqXHR object, which is a superset of the XMLHTTPRequest object and has the "status" property which returns status code.
Related
I'm trying to do a Youtube API and I feel like I got everything working except this gapi and res thing? It says gapi is not defined. How can I make this work?
function tplawesome(e,t){res=e;for(var n=0;n<t.length;n++){res=res.replace(/\{\{(.*?)\}\}/g,function(e,r){return t[n][r]})}return res}
$(function() {
$("form").on("submit", function(e) {
e.preventDefault();
// prepare the request
var request = gapi.client.youtube.search.list({
part: "snippet",
type: "video",
q: encodeURIComponent($("#search").val()).replace(/%20/g, "+"),
maxResults: 3,
order: "viewCount",
publishedAfter: "2015-01-01T00:00:00Z"
});
// execute the request
request.execute(function(response) {
var results = response.result;
$("#results").html("");
$.each(results.items, function(index, item) {
$.get("tpl/item.html", function(data) {
$("#results").append(tplawesome(data, [{"title":item.snippet.title, "videoid":item.id.videoId}]));
});
});
resetVideoHeight();
});
});
$(window).on("resize", resetVideoHeight);
});
function resetVideoHeight() {
$(".video").css("height", $("#results").width() * 9/16);
}
function init() {
gapi.client.setApiKey("AIzaSyD646m4ZfK5yKBZj9p95LohN-PTUnRHBRY");
gapi.client.load("youtube", "v3", function() {
});
}
gapi is an object created by the Google API javascript library that manages all interactions (i.e. does all the heavy lifting of the requests) for you. If the object is not defined, you may not have included the library itself in your page. Somewhere in your HTML, you'll need a script tag that loads the library located at:
https://apis.google.com/js/client.js
Note that, in loading the library with a script tag, you should also pass it a callback ... this is a function that will be automatically called as soon as the library is done loading. So in your case, your init() method is that callback, and so your script tag would look like this:
<script src="https://apis.google.com/js/client.js?onload=init"></script>
The browser will get the library, load it, then run init() when the library is done loading, and all will be ready for your form to execute when triggered.
I am loading external content into a div element using jquery.load() without a selector. If the content loaded has embedded JS, the JS works as expected. HOWEVER, if the content includes a script tag with src=path-to-js-code the js-code is not loaded.
Am I correct in this observation and if so is there a good solution other than embedding the JS in the loaded content?
EDIT :
A few clarifications and observations:
To load the content I am using
$("#DivId").load("path/to/content.php", CallbackFunction(response, status, xhr) {
error checking and post processing code
});
Changing the load code to:
$.get("path/to/content.php", CallbackFunction(response, status, xhr) {
error checking
$("#DivId").html(response);
post processing
});
Does not seem to change the behavior (more on the behavior below)
I have not tried parsing the response to retreive the script src and then using getScript().
Now more on the behavior...
Using Firefox, it seems that the external JS is loaded but only if it has been about 2 min from the last load. I do not see an attempt in Firebug unless the refresh is about 2m after the last load of the external JS. (weird). When I was making JS code changes and hitting refresh, it was not loading my new code and thus the original question.
So i will withdraw my question in light of this clarified behavior (2m caching?).
Thanks.
Both the .load() and .html() jQuery methods utilise the .innerHTML property. This won't execute scripts added with <script> tag. Use a regular AJAX call e.g. .get() then in the callback use .append() to add your HTML string and the scripts will run once it's parsed e.g.
$.get("path/to/content.php", function(response, status, xhr) {
// error checking
$("#DivId").append(response); // Any <script> tags in the response string will execute
// post processing
});
Thing is you need to make sure you're running trusted code if it's added by .append()
I was wondering you can get the script src in the response text of $.load method with regular expressions, then use $.getScript() method to load the script, maybe something like this:
$("#DivId").load("path/to/content.php", function(response, status, xhr) {
var regexp = new RegExp('script.*?src="(.*?)"'),
execresults = regexp.exec(response);
if(execresults.length > 1)
{
// the first result is the entire match including
// the 'script..src=', so abandon it
var matches = execresults.slice(1);
$.each(matches, function(){
$.getScript(this, function(){
// do something after load script
});
});
}
});
Hope this can help
This is the easy way to load an external JS to your jQuery
$.ajax({
type: "GET",
url: "path/to/content.php",
dataType: "script"
success:CallbackFunction(response, status, xhr)
});
3rd party websites can place my script tag on their websites, like so on for example ExternalSite.html in the head section:
<script type="text/javascript">
(function () {
var ttScript = document.createElement('script'); ttScript.async = true;
ttScript.src = '//www.example.com/script/myscript.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ttScript);
})();
</script>
On my own server, in the file myscript.js I have this code:
$.ajax({
url: "http://www.example.com/iplookup.php",
data: null,
type: 'GET',
crossDomain: true,
dataType: 'jsonp'
}).done(function (json) {
self.ip = json;
});
But once a user visits the 3rd party site, on the first line here I get Uncaught ReferenceError: $ is not defined
Now this is probably because I don't reference jQuery on the 3rd party site, where I include the myscript.js file. The problem is that:
I do not know if this 3rd party site even has jQuery running
I don't know how to reference jQuery from myscript.js, also without possibly interfering with an existing jQuery reference on the 3rd party site
First make a check
for jQuery load using javaScript
window.onload = function() {
if (window.jQuery) {
// jQuery is loaded
// Now insert your scripts
} else {
// jQuery is not loaded
// Load it manually from any cdn e.g., //ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js
}
}
There are some other similar ways of checking which we can use
if (typeof jQuery != 'undefined') {
// jQuery is loaded
} else {
// jQuery is not loaded
}
if (jQuery) {
// jQuery is loaded
} else {
// jQuery is not loaded
}
There 's a working fiddle available by atornblad which also tells the time jQuery took to load.
You can have a look for a better reference.
Hope this helps..
I'm really new to web programming. I'm trying to make a form post and get the callback.
I'm trying to use this plugin here: http://malsup.com/jquery/form/#ajaxSubmit
But when I call the: $("#my_form").ajaxSubmit(options); Nothing happens..
What I have done so far:
I have this form
<form method="post" id="my_form" action="record.php" enctype="multipart/form-data" >
// stuff inside..
<input type="button" id = "recordDatabase" value="Rcord on Database" />
</form>
And I have this script:
<script src="http://malsup.github.com/jquery.form.js"></script>
$(document).ready(function()
{
var options =
{
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
};
$("#recordDatabase").click(function()
{
alert('About to submit: \n\n');
$("#my_form").ajaxSubmit();
alert('submited: \n\n');
return false;
});
});
Finally my two functions are:
function showRequest(formData, jqForm, options)
{
// formData is an array; here we use $.param to convert it to a string to display it
var queryString = $.param(formData);
alert('About to submit: \n\n' + queryString);
return true;
}
function showResponse(responseText, statusText, xhr, $form)
{
alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
'\n\nThe output div should have already been updated with the responseText.');
}
I´m doing exactly like the example on the site(http://malsup.com/jquery/form/#ajaxSubmit), but it doesn´t work.
Any idea what's wrong?
I don't think you can hotlink to the jQuery plugin on Git. Try downloading the plugin and saving it as a JS file in your application web root.
It looks like you are not referencing your scripts correctly. According to your comment, you have included your scripts like this:
<script src="ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="localhost/js/jqueryPlugin.js"></script>
These are relative URLs. The browser will request the resources from your site by tacking on those relative URLs to the end of the current directory.
Suppose this page is at http://localhost/myapp/mypage.html. The browser will look for your script files at:
http://localhost/myapp/ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js
http://localhost/myapp/localhost/js/jqueryPlugin.js
These URLs probably don't exist. Maybe your browser is smart enough to recognise "ajax.googleapis.com" as a domain name and request the data from the domain, but it's less likely that it will recognize "localhost" as a domain.
Add // to the beginning of the URL. This is a "Schema-relative URL" and will use either http or https depending on what the current page is using. We use these kind of URLs to avoid security prompts warning users that some of the content on the page is not secure. Your scripts would then look like this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//localhost/js/jqueryPlugin.js"></script>
Suppose I have a page such as the following
<html><head></head><body><!--STUFF-->
<script>
if(SomeBooleanVariable) {
$.getScript('js/file.js');
}
</script>
</body></html>
and my file.js file simply contains raw jQuery events with no wrapping. It is exactly as follows:
$(document).on("eventHere", "classHere", function(e) {
//Stuff
});
$(document).on("eventHere", "classHere", function(e) {
//Stuff
});
This is simply not working. When I include the contents of file.js directly into the HTML it works fine however the JS does not seem to be included properly. I have tried putting "alert(3);" at the top of file.js but it does not fire. I have tried the following:
$("head").append("<script src=\"js/file.js\" />");
$(document).append("<script src=\"js/file.js\" />");
-and-
document.write("<script src=\"js/file.js\" />");
If you want to load that .js file dynamically, change your code to this:
if(SomeBooleanVariable) {
$.getScript("ajax/test.js")
.done(function(script, textStatus) {
console.log(textStatus);
})
.fail(function(jqxhr, settings, exception) {
console.log("Triggered ajaxError handler.");
});
And see if you get any error in console
It may be, that you are, for example, using mod_rewrite and jQuery tries to load script relative to the "folder" your subpage is in. Example: you are # http://www.example.com/link-to-subpage/. In this case, jQuery will try to load http://www.example.com/link-to-subpage/js/file.js, while it resides # http://www.example.com/js/file.js. In this case, use an absolute path. So, instead of:
js/file.js
write:
/js/file.js