Can i modify an external js file via Ajax post?

203 Views Asked by At

I Would like to know if there is a possibility to modify an external js file via ajax post, for example:

Into my external js file i've got a variable :

var color;

So i would like my users to be able change the value of this variable by typing the HEX code into an input text form.

So when the type and press submit button to grab this value and post it to external js file and modify the variable.

I want something like this:

var colorVal = $('input').val();

$.post("external-file-js.js", {color: colorVal}, function(result){});

In external js file something like:

var color = $.get(colorVal); // HERE i dont know how to grab the value

$('body').css('background-color',color);

Thank you :)

2

There are 2 best solutions below

5
Ezra Morse On BEST ANSWER

I need to understand the use case you are intending in order to provide a full answer. If all you are attempting to do is change the background color, why do you need to run an AJAX post at all? Why not just change it?

In extenal.js (which is included in html body):

function changeColor(color) {
  $('body').css('background-color',color);
}

Then you bind the following event to the input:

$('input').change(function () {

// Though you may want to perform validation first.
changeColor($(this).val());

});

The only problem is if you need to change it long term, for multiple users. Then you would need to store the value server side (with a post and some type of CRUD system, in which case, check out JSON/JSONP)

0
osekmedia On

It can be done. You would have to use some back-end code to rewrite your JS file. You would then need to remove any binds and use a script to reload your js document on the fly. Here is an example of loading JS on the fly. http://www.philnicholas.com/2009/05/11/reloading-your-javascript-without-reloading-your-page/

I am not sure why you would do this. I would just rework my JS file so I can avoid this mess.