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>
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 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'
});
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();
});
}
});
So, I've just read online about a fairly specialized HTTP method known as HEAD, which is basically supposed to only send metadata, without sending the actual document body. It seems that jQuery supports this, but when I attempted to create it for real, the body was still sent along with the headers. When I checked in the console, Chrome told me that a head request was actually sent. Huh?
Here's the code:
<!DOCTYPE html>
<html>
<head>
<meta charset = 'UTF-8'/>
<title>Headers</title>
</head>
<body>
<script language="Javascript" type="text/javascript"
src="2-jquery-1.11.0.min.js"></script>
<script language="Javascript" type="text/javascript"
src="jquery-ui-1.10.4.custom.min.js"></script>
<script language="Javascript" type="text/javascript">
$(function() {
$.ajaxSetup({ cache: false }); // not exactly necessary for head requests
// to be used for other ajax request types
//..is this interfering?
function reloader() {
$.ajax({ type: 'HEAD', url: "chatbox.txt" })
.done(function(data, status, xmlhttp) {
console.log(xmlhttp.getResponseHeader('Last-Modified')); })
.fail(function() { alert("error!"); })
.always( function() {} ); } // end reloader
var matrix = setInterval(reloader,3000);
$('#stop').click(function() { clearInterval(matrix); alert('stopped!');
}); // end click
}); // end $(document).ready()
</script>
<button id = 'stop'>Stop</button>
</body>
</html>
Everything works fine, except for the body being sent as well. What's the problem exactly? Am I accidentally sending the body along with the request? If so, where in the code is this?
P.S. I know I can do this with PHP, but I'm interested in js/jQ.
Thanks!
I am new in jQuery and I'm trying to develop a client for my web service. I've tried something simple, just for testing, but still it doesn't work, although it seems ok to me.
I have the jQuery library in my tomee/webapp folder, along with my html and javascript files. If I write some non-jQuery code in my javascript file, it works.
I have the following code:
index.html
<!DOCTYPE html SYSTEM "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="client.js"></script>
</head>
<body>
<input type="button" id="getAllButton" value="Get all books" onclick="return getAllBooks()"/>
<div id="messageBox"></div>
</body>
</html>
client.js
function getAllBooks() {
$.ajax({
dataType: 'application/xml',
type: 'GET',
url: rootURL + '/books',
success: function (data) {
alert(1);
},
error: function (data) {
alert(2);
}
});
}
The problem is that no alert will appear. If a write pure javascript (I mean without jQuery), alerts will do appear.
Why do alerts not appear? Any advice?
Thank you!
Sorin
Lets try to find out what works and what not; try changing your client.js to:
alert(1);
function getAllBooks() {
alert(2);
window.open(rootURL + '/books');
$.ajax({
dataType: 'application/xml',
type: 'GET',
url: rootURL + '/books',
success: function (data) {
alert(3);
},
error: function (data) {
alert(4);
}
});
}
If you see the alert #1 (when your html page loads) then your client.js path is OK. If you see alert #2 (when you click the button) then at least the function is being called.
Verify if window.open() shows what your web service is supposed to show you (even a error message will guide you throw the right path). And of course, if you see alert #3 or #4 then your problem was mysteriously solved by it self.... it sometimes happens :-)
NOTE: If you know how to use the javascript console of your browser use console.log() instead of alert() for debugging;
Thanks charlietfl for your tips! They helped me solve the problem.
The problem was that it didn't know who rootURL is. I found rootURL in an example and I thought that is something defined in jQuery. It seems it isn't.