PHP base URL in external js file - javascript

I have few JS in HTML page, if I use this in HTML view file then its working fine, my page submit form correctly without any issue.
But when I moved this JS codes to external JS file, then it shows error,
Below is my JS
$("#user_fm").submit(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/peoples/add_user",
data: $("#user_fm").serialize(),
-----
my problem is clear to me, that in view page this is easily get decoded to my url
"<?php echo base_url(); ?>index.php/admin/peoples/add_user"
but when i keep this in JS file it show like below in console,
POST http://localhost/center/index.php/admin/peoples/%3C?php%20echo%20base_url();%20?%3Eindex.php/admin/peoples/add_user
How can we put PHP codes in JS file?

To be able to embed PHP in html or javascript code, like <?php echo base_url();?>, the file must have .php extension, while your external javascript file certainly has .js extension.
Besides .js files are parsed by the browser, while PHP files must be executed on the server.
What you can do is to first define a variable in inline javascript, and then use it in code of external .js files. In index.php or whatever main file you use, place this before you use your external js code:
<script type="text/javascript">
var baseURL = "<?php echo base_url(); ?>";
</script>
And then in your external code:
$("#user_fm").submit(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: baseURL + "index.php/admin/peoples/add_user",
data: $("#user_fm").serialize(),
-----

clearly you cant access.
Run your script with XXAMP YOU need to turn apache service on so that php can read YOUR base URL

Related

Unable to add php within js file

I have a below script, which i need to add in a .js file.
jQuery( ".followlink" ).click(function(event){
event.preventDefault();
var $k = jQuery.noConflict();
$k.dialog({
title: ' ',
backgroundDismiss: true,
content : "<?php echo $this->getLayout()->createBlock('catalog/product_list')->setTemplate('catalog/product/list/followup-popup.phtml')->tohtml();?>"
});
$k('.jconfirm-scrollpane .container').addClass('follow-container');
});
I get error marked on this line <?php echo.., can anyone tell how to add this inside the JS file.
I have encloded the entire snippet inside the script tag.
You could do it in one way,
give element property like data-content and then in content label just put $(this).data("content"); so, Code should look like below:
jQuery( ".followlink" ).click(function(event){
event.preventDefault();
var $k = jQuery.noConflict();
$k.dialog({
title: ' ',
backgroundDismiss: true,
content: jQuery( ".followlink" ).data("content"),
});
$k('.jconfirm-scrollpane .container').addClass('follow-container');
});
Normally a javascript file is not interpreted by the PHP engine. You'll need to either modify your server's rules to process that file with PHP, or change the extension to .php. You'll also need to change the resulting content-type before outputting anything:
<?php
header('Content-Type: application/javascript');
?>
You need to serve the JS as PHP OR externalise the PHP:
Do this in your PHP file:
<script>var content = "<?php echo json_encode($this->getLayout()->createBlock('catalog/product_list')->setTemplate('catalog/product/list/followup-popup.phtml')->tohtml());?>"</script>
<script src="yourjsfile.js"></script>
and have content: content in the js file

How to describe an image file path which is inside javascript file through codeigniter

For code requirement and security purpose I am calling image using its path inside main.js file, but for normal php (without framework) it works in this way but problem is that I am using Codeigniter and in codeigniter you can call using base_url() in php file but here image is inside js file so my question is how to specify image path inside js with codeigniter.
var modifytop={
controlHTML: '<img src="assets/img/arrow.png" style="width:40px; height:40px" />',
anchorkeyword: '#top',
}
Since JS cannot identify the PHP, PHP code will not execute.
So declare the base_url() in your HTML file.
<html>
<body>
<script type="text/javascript">
var base_url = "<?php echo base_url(); ?>";
</script>
//your rest of js source links
</body>
</html>
Then use the base_url variable in the JS file.
var modifytop={
controlHTML: '<img src="'+base_url+'"assets/img/arrow.png" style="width:40px; height:40px" />',
anchorkeyword: '#top',
}
Set the base_url in config file as below
$config['base_url'] = "http://localhost/your-project-name/";

Jquery Variable with ajax

I am working on a project and I am trying to use jquery to send a variable to php. This a file called test2.php that I have been using to test out the code, can anyone tell me what I am doing wrong because it should be printing out the variable when you click on the button but nothing is happening.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var something="hello";
$("button").click(function(){
$.ajax({ url: 'test2.php',type: "GET", data: { q : something }});
});
});
</script>
</head>
<body>
<button>Get External Content</button>
</body>
</html>
<?php
if(isset($_GET['q']))
{
$q = $_GET["q"];
echo $q;
}
?>
Your code looks generally correct but you have to remember that an AJAX call sends the data "Asynchronously", which means when you click on the button this data is being sent to a separate instance of "test2.php" for processing. It is not reloading the current page with this new data.
The "test2.php" code you are viewing in browser is only run on the server side once when you first start up the page, and there is no 'q' in the '$_GET' variable at that time. The AJAX request is sending data to a separate instance of the same "test2.php" file and it is receiving some data back, but it is not using that information to load anything into your browser.
Depending on what you are trying to achieve there are many different solutions. You could use what you receive from your AJAX request to update information on the page like so:
$.ajax({
url: "test2.php",
type: "GET",
data: { q: something},
success: function (response) {
// do something with 'response' here
}
});
Or you could have the button instead be a simple <a> tag that reloads the current page in browser with information stored in '$_GET' like so:
Button
Then when your PHP code looks for 'q' it would actually find it in the $_GET variable because you reloaded the page.

Laravel site not using Ajax in external javascript file

I am trying to have my site use Ajax from another file but it never works unless the code is actually in the view.
The site successfully calls my other Javascript file but does not seem to recognize the one with Ajax in it.
The following is in my external Javascript file with Ajax in it (ajax.js):
$(document).ready(function(){
$("#idForm").submit(function(e) {
$.ajax({
type: "POST",
url: "{{ url('/auth/login') }}",
data: $("#idForm").serialize(),
success: function(data)
{
location.reload();
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
});
And the following is in my master layout file that successfully uses the form.js file but not ajax.js .
<html>
<body>
<!--Other Stuff-->
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript" src="http://localhost/sitename/public/js/forms.js"></script>
<script type="text/javascript" src="http://localhost/sitename/public/js/ajax.js"></script>
</body>
</html>
Any ideas?
By default, external js file don't support blade syntax. So, to send the ajax request from external js file need to do the followings:
create a global variable to ur template.blade.php file as follows:
var SITE_URL = "{{URL::to('/')}}";
then when to send the ajax request do:
$.ajax({
url: SITE_URL + '/route_name'
});

Is it possible to put a javascript function in a php file?

Non-programmer here, trying to figure something out.
I have a javascript function in the header of my document that upon page load it opens another page in an iframe and reveals an svg file on my server for minor online editing. I would like to place my javascript function in a php file, so that these folder locations of the svg files cannot be determined for anyone to download these svg files freely.
Currently I have this on my html header:
<script type="text/javascript">
function loaded()
{
document.getElementById("myiframe").src="http://www.mydomain.com/myfolder/mypage.html?url=myotherfolder/"+window.location.search.substr(1);
}
onload=loaded;
</script>
Since I have heard that php is a server side script and not viewable, I thought this would mask the location of these files on my server.
I want to remove this javascript code from my header and place it in a php file and replace the header code with either of these:
<script src="phpjavafile.php"></script>
or
<?php include ('phpjavafile.php'; ?>
and finally put the javascript into a php file like this:
<?php
<script type="text/javascript">
function loaded()
{
document.getElementById("myiframe").src="http://www.mydomain.com/myfolder/mypage.html?url=myotherfolder/"+window.location.search.substr(1);
}
onload=loaded;
</script>
?>
I have tried both of these methods and neither load properly.
I must be doing something wrong. Am I on the right track, or is there a better way of getting this to work.
Thank you ahead of time.
By using the echo() function
PHP
<?php
echo '<script>
some javascript
</script';
?>
However if you are just trying to load the php on page load without any php args then just write it out of the tags.
If you have the JavaScript is another file then using
PHP
<?php
include 'path/to/javascript/file.php';
?>
Should work.
You cannot hide javascript as it is interpreted browser side and not server side so the users browser has to have accesses to the code.
Here is the code I think you are asking for:
PHP HTML
<?php
$html = file_get_contents("path/to/data.html");
?>
<div>
<?php echo $html; ?>
</div>
doesn't use an iframe but should still work. However any relative links will not work unless both files are in the same dir and there will be no iframe functionality without additional css
You can just output it as text in your PHP file.
<?php
// Some PHP stuff here
?>
<script type="text/javascript">
function loaded(){
....
}
onload=loaded;
</script>
<?php
// Some more PHP stuff here
?>
Alternatively, you can just link to it in the usual way from within the same file:
<script src="path/to/your/file.js"></script>

Categories

Resources