how not to hard-code codeigniter link in js file - javascript

i wrote the routine below to retrieve city based on selected country for my codeigniter application.
$(document).ready(function() {
$("select#cbo_country").change(function() {
$.post("http://localhost/main/index.php/city/get_data_by_country", {
int_country_id : $(this).val()
},
function(data) {
// some code here
},'json');
})
});
as you can see, i hard-coded the url (http://localhost/main/index.php/city/get_data_by_country) and i know it's a bad practice but i can't help it.
is there a nice clean way to not hard-code the url? i used to use codeigniter's base_url(), but since i move the routine to a js file, i am no longer able to use the function.

Taken (mostly) from my answer on How to get relative path in Javascript?.
You've got two options:
Build a configuration/ preferences object in JavaScript which contains all your environment specific settings:
var config = {
base: "<?php echo base_url(); ?>",
someOtherPref: 4
};
and then prefix the AJAX url with config.base.
You have to place the config object in a place which is parsed by PHP; the standard choice is inside the <head> HTML element. Don't worry its a small config object, whose contents can change on each page, so it's perfectly warrented to stick it in there.
Use the <base /> HTML tag to set the URL prefix for all relative URL's. This affects all relative URL's: image's, links etc.
Personally, I'd go for option 1. You'll most likely find that config object coming in handy elsewhere.

Change "http://localhost/main/index.php/city/get_data_by_country" to "/main/index.php/city/get_data_by_country" and it will work no matter what your base url is.
This works because the / before main/index.php says "start at the root and go the the index.php file in the main folder".
This is unless your document root folder is set to the main folder, if so, take out the main

One thing you can do is add a data-baseurl attribute to an element on the page (the body element works). Then you can grab that from the JavaScript file.
<body data-baseurl="<?=base_url()?>">
Then in JavaScript:
$("select#cbo_country").change(function() {
var baseURL = $('body').data('baseurl')
$.post(baseURL+"city/get_data_by_country", {
int_country_id : $(this).val()
},
function(data) {
// some code here
},'json');
})

Related

How to write path to files in Magento? File is not found, even when I set the absolute path

everyone!
I try to create custom application sending (to emails) form the site on Magento.
For doing it, I call post.php file in this way:
$('form#send-profile').submit(function(event) {
event.preventDefault();
var output = true,
array = $(this).serialize();
if (output) {
$.post('post.php', array, function(data) {
$('input[type="text"], textarea').val('');
});
};
});
I`ve placed post.php into the root folder (and tried it with different folders too).
But I had this result in any conditions:
POST http://vescorte.com/post.php 404 (Not Found)
Maybe Magento has some special way to set paths? Tell me please, if you know how to cope with this problem.
First of all , which version of magento do you use ?
Next, if you want to development any new function , you need create a module
try this link magento-2-module-development
In the template file in which you mentioned JS code, you can mention the Magento base URL function to get full base URL like below:
$.post('<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB); ?>post.php', array, function(data) {
$('input[type="text"], textarea').val('');
});
Still if you face issue then try to remove all the code from post.php and run with simple text to check file request complete or not.

One main JS varibles file for multiple HTML files

So I am wanting to create one file where I can list and edit links without opening every file.
So I am wanting to have a page like http://example.com/links.js and in there I want to have all my information where I can information.
I will have around 20 http://example.com/link1.html etc. So instead of opening every HTML file to edit it, I would like to have just one main file where I can set for example links and titles.
I am not perfect at JS but I do understand the most parts. So in the jar file I will have like "var link1 = www.google.com" and inside link1.html, it will turn out as <a href="www.google.com></a> Something like that.
Sorry if you do not understand this as I am tired and cannot explain correctly. Thanks.
I managed to find a way to do this by using :)
link3 = function() {
location.href = "http://google.com";
}
Though it is a broad topic but hopefully this will help you in designing your application.
You can have one js file will a json object. Example
links.js
var Links = {}; // namespacing
Links.linkObject = {
linkOne:"someLink",
linkTwo:"someLinkTwo",
//Rest of links
}
Links.linkContains() {
return Links.linkObject;
}
Import this file using script tag
<script src="links.js"></script>
Now in your main js file or any other file you can call this inside some function
function customFunction() {
var getLinks = Links.linkContains() // will return the json array of links
}
Once you get the getLinks you can use dot or bracket notation to get the value.
For example getLinks.linkOne will return someLink.
You can use this object to retrieve value anywhere in your application and when you will change the relevant value in link.js it will reflect everywhere

how to load a file and parse tags using jquery

I have a file which contains lots of tags like follows
<script type="text/template" id="template-1">
</script>
<script type="text/template" id="template-2">
</script>
I want to load the file and than load all the content inside the script tags in memory.
I am trying the below code but its not working.
tpl = {
// Hash of preloaded templates for the app
templates : {},
loadTemplates : function(name) {
var that = this;
$.get(name, function(data) {
$(data).find('script').each(function (_, entry) {
that.templates[$(this).attr('id')] = $(this).text();
});
});
},
// Get template by name from hash of preloaded templates
get : function(name) {
return this.templates[name];
}
};
any help?
call is made like this
tpl.loadTemplates('/templates/templates-home.html');
In general you seem like you're on the right track. The browser will load (but ignore) script tags marked with type=text/template and you can later select the contents of those tags and process them with javascript.
I think your problem is likely with the order of your procedure.
You haven't posted the javascript that uses your templates so I can only assume. I suspect your trying to load the templates before the document is ready, thus, the script tags aren't actually on the page when you load them. To fix, your can move your javascripts below the templates in the document OR execute your code in a window.onLoad handler.
EDIT
Okay, now I have a better idea of what you're trying to do. You still haven't told me what part of this is broken, but my gut tells me that this bit is the problem: $(data).find('script'). jQuery expects to be traversing the DOM. At this point in time, data is just a string returned from the server, it's not actually loaded in the DOM. So jQuery won't actually find ANY script tags. Try appending your result to the body before querying the DOM for script elements. Maybe something like this:
$('body').append(data);
$('script[type="text/template"]').each ...
I'm not really thrilled about that though. Can you just inject them into the page on the server side? Why do you need to delay the loading?
EDIT 2
If you don't want your script tags to be visible in the html document, then I suggest you don't use them. Instead you can have your template endpoint just return a bundle of javascript and evaluate it directly. Something like:
$.get(name, function(data) {
// data is a string that sets up your window.template variable
eval(data);
});

how to change url for javascript in opencart

i have been working on the opencart frontend. And i want to make a frontend structure such that products uploaded by a particular vendor is shown. For that i use the url 'user/vendor_name'. And i have made changes in htaccess file for such url and after that i have changed the link function in url.php file for such cases. So now if a user clicks anywhere in the website the url will show 'user/vendor_name/index.php......'. But the url in javascript doesnt use $this->link function and those changes of url.php file doesnot take effect and thus it redirects to the original url.
Please help me out on this.
You would have to modify the controllers for each template containing such URLs and make sure You are setting a vendor name to a PHP variable accessible by the template:
$this->data['vendor'] = $vendor_information['name'];
supposing the vendor name is stored in a variable $vendor_name under the index name. This is only an example. Now in each template identify such URL with the JS part:
$.ajax({
url: 'index.php?route=checkout/cart/add' // + ...
// ...
});
and change it to:
$.ajax({
url: 'vendor/<?php echo $vendor; ?>/index.php?route=checkout/cart/add' // + ...
// ...
});
This should solve your problem.

Calling Django `reverse` in client-side Javascript

I'm using Django on Appengine. I'm using the django reverse() function everywhere, keeping everything as DRY as possible.
However, I'm having trouble applying this to my client-side javascript. There is a JS class that loads some data depending on a passed-in ID. Is there a standard way to not-hardcode the URL that this data should come from?
var rq = new Request.HTML({
'update':this.element,
}).get('/template/'+template_id+'/preview'); //The part that bothers me.
There is another method, which doesn't require exposing the entire url structure or ajax requests for resolving each url. While it's not really beautiful, it beats the others with simplicity:
var url = '{% url blog_view_post 999 %}'.replace (999, post_id);
(blog_view_post urls must not contain the magic 999 number themselves of course.)
Having just struggled with this, I came up with a slightly different solution.
In my case, I wanted an external JS script to invoke an AJAX call on a button click (after doing some other processing).
In the HTML, I used an HTML-5 custom attribute thus
<button ... id="test-button" data-ajax-target="{% url 'named-url' %}">
Then, in the javascript, simply did
$.post($("#test-button").attr("data-ajax-target"), ... );
Which meant Django's template system did all the reverse() logic for me.
The most reasonable solution seems to be passing a list of URLs in a JavaScript file, and having a JavaScript equivalent of reverse() available on the client. The only objection might be that the entire URL structure is exposed.
Here is such a function (from this question).
Good thing is to assume that all parameters from JavaScript to Django will be passed as request.GET or request.POST. You can do that in most cases, because you don't need nice formatted urls for JavaScript queries.
Then only problem is to pass url from Django to JavaScript. I have published library for that. Example code:
urls.py
def javascript_settings():
return {
'template_preview_url': reverse('template-preview'),
}
javascript
$.ajax({
type: 'POST',
url: configuration['my_rendering_app']['template_preview_url'],
data: { template: 'foo.html' },
});
Similar to Anatoly's answer, but a little more flexible. Put at the top of the page:
<script type="text/javascript">
window.myviewURL = '{% url myview foobar %}';
</script>
Then you can do something like
url = window.myviewURL.replace('foobar','my_id');
or whatever. If your url contains multiple variables just run the replace method multiple times.
I like Anatoly's idea, but I think using a specific integer is dangerous. I typically want to specify an say an object id, which are always required to be positive, so I just use negative integers as placeholders. This means adding -? to the the url definition, like so:
url(r'^events/(?P<event_id>-?\d+)/$', events.views.event_details),
Then I can get the reverse url in a template by writing
{% url 'events.views.event_details' event_id=-1 %}
And use replace in javascript to replace the placeholder -1, so that in the template I would write something like
<script type="text/javascript">
var actual_event_id = 123;
var url = "{% url 'events.views.event_details' event_id=-1 %}".replace('-1', actual_event_id);
</script>
This easily extends to multiple arguments too, and the mapping for a particular argument is visible directly in the template.
I've found a simple trick for this. If your url is a pattern like:
"xyz/(?P<stuff>.*)$"
and you want to reverse in the JS without actually providing stuff (deferring to the JS run time to provide this) - you can do the following:
Alter the view to give the parameter a default value - of none, and handle that by responding with an error if its not set:
views.py
def xzy(stuff=None):
if not stuff:
raise Http404
... < rest of the view code> ...
Alter the URL match to make the parameter optional: "xyz/(?P<stuff>.*)?$"
And in the template js code:
.ajax({
url: "{{ url views.xyz }}" + js_stuff,
... ...
})
The generated template should then have the URL without the parameter in the JS, and in the JS you can simply concatenate on the parameter(s).
Use this package: https://github.com/ierror/django-js-reverse
You'll have an object in your JS with all the urls defined in django. It's the best approach I found so far.
The only thing you need to do is add the generated js in the head of your base template and run a management command to update the generated js everytime you add a url
One of the solutions I came with is to generate urls on backend and pass them to browser somehow.
It may not be suitable in every case, but I have a table (populated with AJAX) and clicking on a row should take the user to the single entry from this table.
(I am using django-restframework and Datatables).
Each entry from AJAX has the url attached:
class MyObjectSerializer(serializers.ModelSerializer):
url = SerializerMethodField()
# other elements
def get_url(self, obj):
return reverse("get_my_object", args=(obj.id,))
on loading ajax each url is attached as data attribute to row:
var table = $('#my-table').DataTable({
createdRow: function ( row, data, index ) {
$(row).data("url", data["url"])
}
});
and on click we use this data attribute for url:
table.on( 'click', 'tbody tr', function () {
window.location.href = $(this).data("url");
} );
I always use strings as opposed to integers in configuring urls, i.e.
instead of something like
... r'^something/(?P<first_integer_parameter>\d+)/something_else/(?P<second_integer_parameter>\d+)/' ...
e.g: something/911/something_else/8/
I would replace 'd' for integers with 'w' for strings like so ...
... r'^something/(?P<first_integer_parameter>\w+)/something_else/(?P<second_integer_parameter>\w+)/' ...
Then, in javascript I can put strings as placeholders and the django template engine will not complain either:
...
var url = `{% url 'myapiname:urlname' 'xxz' 'xxy' %}?first_kwarg=${first_kwarg_value}&second_kwarg=${second_kwarg_value}`.replace('xxz',first_integer_paramater_value).replace('xxy', second_integer_parameter_value);
var x = new L.GeoJSON.AJAX(url, {
style: function(feature){
...
and the url will remain the same, i.e something/911/something_else/8/.
This way you avoid the integer parameters replacement issue as string placeholders (a,b,c,d,...z) are not expected in as parameters

Categories

Resources