Adding javascripts functions dynamically in mvc3 - javascript

I'm creating a dynamic-form infrastructure. This infrastructure will get a certain XML which will include all of the form data, from the order in the page to validators.
The dynamic page may also contain fields which will require some sort of validation. The validation is not only trivial (such as "numeric"\"alphanumeric"), it might be something more complicated.
That's why I want to pass in my XML the validators javascripts.
When developing on traditional Web Application, it's simple to plant this code in the page header. But I don't know how to do so when using MVC3, since it's not a normal client-server application.
It's important to explain - in my controller, I pass this dynamic-form class the xml file, it does all it should, and in the end, I plant the result in ViewBag.table.
Anyone know how can I can plant the javascript code from the controller to view header?
EDIT:
I tried thw following:
$(document).ready(function () {
$.ajax({
url: '#Url.Action("SetJScript", "MyPages")',
type: 'POST',
success: function (result) {
var myscript = document.createElement('script');
myscript.setAttribute('type', 'text/javascript');
myscript.innerHTML = '$( document ).ready( function ( e ){' + result + '});';
document.getElementsByTagName('head').item(0).appendChild(myscript);
}
});
and also:
$(document).ready(function () {
$.ajax({
url: '#Url.Action("SetJScript", "MyPages")',
type: 'POST',
success: function (result) {
var myscript = document.createElement('script');
myscript.setAttribute('type', 'text/javascript');
myscript.innerHTML = "function test() {alert('aa');}";
document.getElementsByTagName('head').item(0).appendChild(myscript);
}
});
or change the:
myscript.innerHTML = "function test() {alert('aa');}";
to:
myscript.innerHTML += "function test() {alert('aa');}";
so it will be added to the existing "$documnet.ready" function.
None of it worked.
I kept getting "Unknown error"
Thank you all.

Hope it helps..
$(document).ready(function () {
$.ajax(
{ url: '#Url.Action("SetJScript", "MyPages")',
type: 'POST',
success: function(result)
{ var myscript = document.createElement('script');
myscript.setAttribute('type','text/javascript');
myscript.innerHTML = 'function test() {alert("aa");}';
document.getElementsByTagName('head').item(0).appendChild(myscript);
} //end of success
});
});

Related

JS Script Loading

I am working on js script loading techniques and want to show a custom loader while all my content/resources are loading. Below is working as far as I can tell to load js scripts in order but my web app is throwing some errors after it starts.
My question is: how is the below script (which is called as a <script> right after jQuery at the bottom of my HTML) different from simply having all these js scripts called as <script>'s in the head of the HTML? Why errors on one but not the other?
$(document).ready(function(){
jLoader(scripts[0]);
});
var i = 0;
function jLoader (script){
return $.ajax({
method: "GET",
dataType: "script",
url: script,
context: document.body,
cache:true,
}).done(function() {
console.log(script + ' loaded!');
step();
}
});
}
function step(){
i = i + 1;
jLoader(scripts[i]);
}
var scripts = ['js/materialize.js','http://cdn.leafletjs.com/leaflet-0.7.5/leaflet.js','js/leaflet.awesome-markers.js',
'js/bouncemarker.js','https://cdn.firebase.com/js/client/2.3.1/firebase.js','js/geofire.min.js','js/myScript.js'];
There is a closing curly brace too much after step();
When you put the variable definitions on top it should work::
var i = 0;
var scripts = ['http://cdn.leafletjs.com/leaflet-0.7.5/leaflet.js','https://cdn.firebase.com/js/client/2.3.1/firebase.js'];
$(document).ready(function(){
jLoader(scripts[0]);
});
function jLoader (script){
return $.ajax({
method: "GET",
dataType: "script",
url: script,
context: document.body,
cache:true,
}).done(function() {
console.log(script + ' loaded!');
step();
});
}
function step(){
i = i + 1;
jLoader(scripts[i]);
}
At least here it does: http://jsfiddle.net/adweqcm2/
But remember: in production environments it is recommendable to concatenate your scripts.

calling jquery AJAX dynamically

The following code is not working for me and I don't know why...
this is my js code:
var getEventsFunctionScript = document.createElement('script');
getEventsFunctionScript.setAttribute('type', 'text/javascript');
getEventsFunctionScript.innerHTML = "function getEvents(){$.ajax({url:'myPHP_file.php',type:'post',data:{'ajaxData':'1'},success:function(response){alert('AJAX executed!!');}});}";
w.document.body.appendChild(getEventsFunctionScript);
this us my php code:
if (isset($_POST['ajaxData'])) {
exit;
}
My problem is that this is not working, Ajax is never executed (I never see the alert)
could someone give any idea about why this is not working?
thank you very much
You need to call your function afterwards:
getEventsFunctionScript.innerHTML = "function getEvents() {
$.ajax({
url: 'myPHP_file.php',
type: 'post',
data: {
'ajaxData': '1'
},
success: function (response) {
alert('AJAX executed!!');
}
});
}
getEvents();";

Loading all files in jQuery ajax before success function PHP jQuery

I have a script like this.
The jQuery ajax loads all my files with no issues.
The ajax_load_books.php file have lot of css and js(inline edit, sliders etc.) files in it.
The problem is:
How to load all the files before the success function so that the user can see the loader_div message untill all the files are loaded.
In other words - Load all the js/css files and proceed with the success function.
Even I have checked with .load() function. Could someone redefine the below code .
<script type="text/javascript">
$(document).ready(function () {
$(".form-control").change(function () {
var id = $(this).val();
var dataString = 'id=' + id;
$.ajax({
type: "POST",
url: "ajax_load_books.php",
data: dataString,
cache: false,
beforeSend: function () {
$("#loader_div").show();
},
success: function (html) {
$("#loader_div").hide();
$("#txtHint").html(html);
}
});
});
});
</script>
Thanks,
Kimz
For the css files, you can find them using jQuery.parseHTML() function, but the <script> will be stripped with this so instead we would have to use regex for the <script> tags.
Try:
<script type="text/javascript">
$(document).ready(function () {
$(".form-control").change(function () {
var id = $(this).val();
var dataString = 'id=' + id;
$("#loader_div").show();
$.ajax({
type: "POST",
url: "ajax_load_books.php",
data: dataString,
cache: false,
beforeSend: function () {
//parsing <link>
var $str = $('<output>');
//loading html into fake tag
$str.load("ajax_load_books.php");
//now $str includes all your page code
temp = $.parseHTML(str);
$.each(temp, function (i, el) {
//finding the <link> tag
if (el.nodeName == 'LINK') {
//appending it to the <head> tag
$('head').append("<link rel='stylesheet' href='" + el.getAttribute('href') + "'>");
}
});
//for script we will use regex
var pattern = /<script[^>]+?>.*?<\/script>/gi;
var matches = str.match(pattern);
var scripts = "";
for (var i in matches) {
scripts += matches[i];
}
//appending script tag to <head>
$('head').append(scripts);
},
success: function (html) {
$("#loader_div").hide();
$("#txtHint").html(html);
}
});
});
});
</script>
Demo
There is a drawback with this, your stylesheets and script code will repeat. If the above code causes issue running because of the repetition, you should place the code of beforeSend() before the AJAX and have a parameter sent from your AJAX function indicating that when an AJAX is called with this parameter, to execute all the HTML except the stylesheets and js scripts.

Reading a file into a string in jQuery/JS

The title is quite self-explanatory: I need to read a HTML file through jQuery and store its contents into a string variable.
I tried using .load and $.get, but they wouldn't do what I needed.
This is the code I've tried so far, based on the comments below, but they didn't populate my template variable at all:
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template);
AND:
var template = "";
var fileUrl = "includes/twig/image_box.twig";
jQuery.get(fileUrl).then(function(text, status, xhr){
var html = String(text);
template.concat(html);
// console.log(html); // WORKS!
});
console.log(template); // Does not work
It's weird why this isn't working. Weird for me at least. This is how I'd populate a variable in PHP so I've carried the same logic to JS. Maybe there is an alternative way?
P.S:V I've also tried all alternative ways, like concatenating with += and assigning inside the callback function to template with =, but nothing worked.
Thanks to the ones who are trying to help me!
Maybe you should try a AJAX request with $.ajax()
Check the jQuery API here
$.ajax({
url: 'yourHTMLfile.html',
type: 'get',
async: false,
success: function(html) {
console.log(html); // here you'll store the html in a string if you want
}
});
DEMO
EDIT: Added a demo!
I reread your question and I noticed you're calling the console log right above the ajax request but you forgot the ajax is asynchronous that means the page will do a request and only will set the template value when the response return with success(if it returns). So the console.log(template) don't appears because it may be not loaded yet.
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
console.log(template); // the change!
}
});
or
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
async: false,
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template); // the change!
You can try this:
//as you see I have used this very page's url to test and you should replace it
var fileUrl = "/questions/20400076/reading-a-file-into-a-string-in-jquery-js";
jQuery.get(fileUrl).then(function(text, status, xhr){
//text argument is what you want
});
and if it won't work try if your browser can open the file. if it could you'd better try ajax method in jQuery if not you might have some problems regarding permissions or somethings like that in you application server.

js file cant use jquery

I have a weird bug where I include this files in my section
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="js/barScriptOOP.js"></script>
in the barScriptOOP.js I have this
function position_bar(){
//global variable
this.sizes = Array();
}
//class methods => getData (from xml file), draw(draws the bar )
position_bar.prototype ={
getData: function(is_load){
var xmlData = Array();
$.ajax({
type: "GET",
url: "Bar.xml",
dataType: "xml",
context: this,
success: function(xml) {
//extracting new data - some code here
xmldata = "blabla";
this.draw(is_load, xmlData);
}
})//end ajax
},
//other functions
when I use this script, I get a '$.ajax is not a function' error.
1. I tried editing out this.draw(is_load, xmlData); and it didn't errored me.
my programs rpeatly calls the getData function.
note: I also get a '$.browser is undefined' error which is in the other function(this is the first error I get).
meaning ==> the going to another function unables jquery.
any idead what is going on here?
Instead of using $ as your jquery reference, try putting this line at the start of your script
var $j = jQuery.noConflict();
$j(function() {
alert('doc ready');
});
(also, it's strange that your script tag doesn't have a type attribute set, though I doubt that's the issue)

Categories