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'
});
Related
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.
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
I have a situation where the HTML part is loaded with AJAX into a DIV with ID="dynamic content" using main.js script. This script is situated inside the HEAD part of main.php and it goes like this:
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
}
});
The Javascript file responsible for controlling that content is situated in another JS file named secondary.js. This file is placed just before the closing of BODY again inside main.php.
main.php Document Structure:
<html>
<head>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
....
<div id="dynamic-content"></div>
....
....
<script type="text/javascript" src="js/secondary.js"></script>
</body>
</html>
Sometimes the content of content.php is too large, and secondary.js file loads before the content is fully loaded. Hence some elements are not targeted and i have problems.
Is there a way for me to delay for 1-2 seconds the execution of secondary.js, just to make sure that the content is fully loaded?
ps: all above files are hosted on the same server
Thanks in advance.
What you're trying to achieve is async behaviour. Whatever secondary.js does, put it inside a function and call it inside the ajax callback. If you do so, you won't even need two JavaScript files.
Don't try to manage this by timeouts or loading order. This will not be failsafe. You cannot know the exact time the browser needs to load your content. For example, what if you are on very slow internet connection? Don't try to predict those things, that's what the callback is for :-)
Your code could look sth like this:
function doSthWithLoadedContent() {
// whatever secondary.js tries to do
}
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
doSthWithLoadedContent();
}
});
You could possibly load the script using $.getScript once the output has been applied to the html tag:
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
$.getScript('js/secondary.js');
}
});
https://api.jquery.com/jquery.getscript/
The best way to do this would actually be to hand a callback to the function that does your ajax call. I probably wouldn't put this in html but it demonstrates the method:
<html>
<head>
<script type="text/javascript" src="js/main.js"></script>
<script lang="javascript>
function doWhenLoaded(someCallback)
{
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
someCallback();
}
});
}
$(document).ready(function(){
doWhenLoaded(function(){
$.getScript('js/secondary.js');
});
})
</script>
</head>
...
</html>
Instead of using $.getScript you could also load in secondary.js with main.js and wrap it in a function call (i.e. doStuff = function() { /* your code here */ }). Then you could call doWhenLoaded(doStuff) in $(document).ready.
You have to add script after ajax call.
$.ajax({
url: 'url of ajax',
type: "POST",
data: data,
dataType: "html",
success: function (data) {
$('#instructions').html('<div>' + data + '</div>');
$.getScript("js/html5lightbox/html5lightbox.js", function() {
$('body').find('.html5lightbox').html5lightbox();
});
}
});
I need to call a PHP function with params from JavaScript when I click on some text in a html file; yeah, I know, it sounds like $##!$##
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() { /// Wait till page is loaded
$('#detailed').click(function(){
$('#main').load('parse.php?file=gz.xml', function() {
/// can add another function here
});
});
}); //// End of Wait till page is loaded
</script>
<a><div id="detailed">Stuff1</div></a>
<a><div id="detailed">Stuff2</div></a>
<div id="main">Hello - This is my main Div that will be reloaded using jQuery.</div>
What I want to make, is when I click Stuff1 on page, to call function parseLog('Stuff1'), and when I click Stuff2, to call function parseLog('Stuff2').
function parseLog(), is a PHP function, in functions.php
Anybody know a solution?
Thanks!
Javascript is client side script and PHP is server side script. So if you think, you need a call to that function over the network and get the response over the network. you should try using a coding method called AJAX. To make life easier and cross browser compatible use jQuery library and its ajax functionality.
Look at this post for a quick intro to jQuery and AJAX.
It helped me , hope this helps you too.
You should try something like this :
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
function myFunc (myData) {
$.ajax( {
type: "POST",
url: "parse.php?file=gz.xml",
dataType: 'json',
data: { param: myData},
success: function( result ) {
$("#main").append(result);
}
}
}
Stuff1</div>
Stuff2</div>
<div id="main"></div>
I had the following in the <head> of a GSP
<script type="text/javascript>
$("button.remove-item").click(function() {
$.ajax({
url: "${createLink(action: 'remove', controller: 'cart')}",
type: 'POST'
});
});
</script>
Notice that I'm using the Grails createLink tag to construct the URL that the AJAX request will post to. When I moved this code into checkout.js and replaced the block of code above with:
<script type="text/javascript" src="${resource(dir: 'js', file: 'checkout.js')}"></script>
the createLink tag is no longer evaluated by Grails. So it seems that Grails tags within <script> blocks are evaluated, but tags within .js files included by GSPs are not - is there a way to change this?
Check out the GSParse plugin to have css and js parsed as a gsp file:
http://nerderg.com/GSParse
http://grails.org/plugin/gsp-arse
You are right .js files are not evaluated by grails! but the GSP are! so thats why when u were setting a tag it was working.
I would suggest you to have a differente approach of how to grab that link! as u are using jquery I would do like this:
<input type="button" class="remove-item" data-url="${createLink(action: 'remove', controller: 'cart')}" value="GO" />
checkout.js:
$("button.remove-item").click(function() {
$.ajax({
url: $(this).data('url'),
type: 'POST'
});
});