How to call a PHP function in an URL of ajax? - php

I have written a PHP code having single function with an echo statement and I wish to call that function as a url in ajax code.
I tired doing this.
<html>
<head>
<title>Writing PHP Function</title>
<script>
$.ajax(
{
url : localhost/practice.php/f=myFirst();
type: "GET",
data: dataString,
success: function(result)
{
alert(result);
}
});
</script>
</head>
<body>
<?php
function myFirst()
{
echo 'The First ran successfully.';
}
?>
</body>
</html>

There are a lot of things wrong with what you have. Here is just a simple example that should work for you.
practice.php
<?php
if(isset($_GET['f']))
echo strip_tags($_GET['f']);
?>
index.php
<?php function myFirst() {
echo 'The First ran successfully.';
} ?><html>
<head>
<title>Writing PHP Function</title>
<!-- You need to add the jQuery library -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
// You should activate it on an event like click (unless you want it to autoload)
$("#content").click(function() {
$.ajax({
// Your url is funky, and cannot be terminated with a semicolon
// but rather a comma
url : 'localhost/practice.php?f=<?php myFirst(); ?>',
type: "GET",
// You can do an alert, but I just made it populate a div instead
success: function(result) {
$("#place-to-load").html(result);
}
});
});
</script>
</head>
<body>
<!-- Your php function will not work as you intend because one -->
<!-- is a server-side function and the other is a client-side script -->
<!-- The functions are not interchangeable. That being said, you can -->
<!-- populate a javascript with a php variable but it would need to be -->
<!-- echoed like <?php myFirst(); ?> -->
<div id="place-to-load"></div>
<div id="content">Load</div>
</body>
</html>

I would try to call the functions based on the params from the URL.
Ajax part,
$.ajax({url:'localhost/practice.php?f=myFirst',type:'GET'}).done(function(response){
alert(response); // or you can write to your document
});
and PHP file
<?php
if(isset($_GET) && $_GET['f'] == 'myFirst'){
myFirst();
}else{
die('No GET params received');
}
function myFirst(){
echo 'The First ran successfully.';
}
?>

Related

jquery not displaying image from JSON array created with php

I want to create an array of image file names in php, then display the images one at a time in the browser.
The code:
getpics.php:
<?php
$photo_array = [];
$handle = opendir(dirname(realpath(__FILE__)).'/spades50/');
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
array_push($photo_array, "$file");
}
}
echo json_encode($photo_array);
?>
html / query:
<!DOCTYPE html>
<html>
<head>
<script src="getpics.php"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<script>
$.ajax({
url: "getpics.php",
dataType: "json",
success: function(data) {
$.each(data, function(i,filename) {
$('#imageDiv').prepend('<img src="spades50/'+ filename +'"><br>');
//console.log(filename); // shows the file names in the console log
});
}
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<img class="#imageDiv" src="loading2.gif" />
</body>
</html>
Result:
The page only shows the initial image loading2.gif, if I uncomment this line: //console.log(filename); I can see the files being loaded in the console window but they are not displayed.
I am new to jquery so any tips will be greatly appreciated.
Regards,
John ......
You have several problems in your code: try this (untested):
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$.ajax({
url: "getpics.php",
dataType: "json",
success: function(data) {
$.each(data, function(i,filename) {
$('#imageDiv').prepend('<img src="spades50/' + filename + '"/><br>');
});
$('#loader').hide();
}
});
</script>
</head>
<body>
<h2>This is a heading</h2>
<div id="imageDiv">
<img id="loader" src="loading2.gif" />
</div>
</body>
</html>
First: you don't have to insert getpics.php as script in your header.
Second: class="#imageDiv" is wrong. A class is prepended by a dot ( . ) and an ID is prepended by a #. So if you want to use an ID use id="imageDiv"
Third: prepend is to add html nodes as first element into a container. You told jQuery to prepend the new images to an image tag which is not a container element. (documentation) So to prepend you have to use a div e.g.
Or you use insertBefore(); (documentation)
I assume that you want to hide the loader when all images are loaded. I made this by adding the line $('#loader').hide();.

AJAX in PHP function is applying to every next instance of the function

Here I have an .ajax function within a PHP function, like this:
function phpFunction($ID) {
print "<script>
$('.uparrow').click(function(){
request = $.ajax({
etc... the rest isn't important.
Anyway, the class .uparrow is an html element that runs this .ajax function when clicked. The other thing you should know is that this function: phpFunction() is called a few times in the document, like this:
phpFunction(1)
phpFunction(2)
phpFunction(3)
However, the problem is that when I load phpFunction(), and I click on the .uparrow element, the .ajax call is made on behalf of each instance of phpFunction() that follows the one whose element I clicked on.
So if I clicked on the .uparrow of phpFunction(1), I would also be virtually clicking on the .uparrows of phpFunction(2) and phpFunction(3). Essentially, I need .uparrow to just be a local class that only applies to the instance of phpFunction() that is currently being called.
The only solution I could think of is to replace .uparrow's class name with something unique to each call of this function. The only difference between each instance of phpFunction() is their input $ID and I was thinking I could redefine .uparrow as:
class = '$ID.uparrow'
or
class = $ID + 'uparrow'
But that doesn't work. So how do I make sure that when I click on .uparrow within phpFunction(1), that the .ajax function only gets called that one time?
This is pretty confusing to explain and probably to understand, so please tell me if there's something that needs elaboration.
Let's say you have a list of elements, and when you click one of them, you want to do an ajax call.
click me
click me
<script>
$(function(){ //on DOM ready
$('.uparrow').on('click', function(){
//do ajax call
$.ajax({
url: 'url here'
type: 'post|get'
data: $(this).attr('data-id'), // you only send the ID of the clicked element
... callbacks, etc
})
});
})
</script>
Now you only have a function that makes an ajax call and takes the parameter to send from the element you clicked.
I hope this is what you wanted to achieve
Try something like this
$('[class="uparrow"]').click( function () {
var request = $.ajax({
// Your ajax call
});
});
this will execute ajax on the clicked element with .uparrow class
HTML
<a class="uparrow" href="#" data-ajax="I'm the first element">Click Me</a>
<a class="uparrow" href="#" data-ajax="I'm the second element">Click Me</a>
<a class="uparrow" href="#" data-ajax="I'm the third element">Click Me</a>
JS:
$('[class="uparrow"]').click(function () {
var currentAjax = $(this).data('ajax')
console.log(currentAjax);
});
And the DEMO
Do not call your php function multiple times. Just one time is sufficient.
Modify the markup of your .uparrow element to include the id like so:
<a class="uparrow" data-id="<?php echo $id; ?>" href="#">TextM/a>
Then re-write your php function like so:
function phpFunction() { /* no need to pass the ID */ ?>
<script>
$(function(){
$(document).on('click', '.uparrow', function(){
$.ajax({
url: 'URL',
type: 'POST'.
data: $(this).attr('data-id')
})
});
})
</script>
<?php } ?>
Call your phpFunction like so:
phpFunction();
UPDATE
<!doctype html>
<html>
<head>
<title>trop</title>
<meta charset='utf-8'>
<link rel='stylesheet' href='css/postStyle.css' />
<link href='http://fonts.googleapis.com/css?family=Exo+2:400,300,200|Homenaje&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
<link rel='shortcut icon' href='http://icons.iconarchive.com/icons/visualpharm/icons8-metro-style/256/Music-Note-icon.png'>
<script src='../jquery.js'></script>
<script type='text/javascript' src='../script.js'></script>
</head>
<body>
<?php
$ids = array(1,2,3); // IDs of the posts you want
$result = mysql_query("SELECT * FROM all_posts WHERE ID IN($ids)");
while ($data = mysql_fetch_array($result)){
?>
<div class='post' style='width:470px'>
<h3><?php echo $data['Title']; ?></h3>
<div class='date'><?php echo $data['DateTime']; ?></div>
<iframe width='470' height='300' src='http://www.youtube.com/embed/WF34N4gJAKE' frameborder='0' allowfullscreen></iframe>
<p><?php echo $data['Body']; ?></p>
<div class='postmeta1'>
<p><a href='<?php echo $data['DownloadLink']; ?>' target='_blank'>DOWNLOAD</a></p>
</div>
<div class='verticalLine' style='height:39px'></div>
<div class='postmeta2'>
<p class='uparrow' data-id="<?php echo $data['id']; ?>">▲</p>
<div class='votes'>3</div>
<p class='downarrow'>▼</p>
</div>
<div class='verticalLine' style='height:39px'></div>
<div class='postmeta3'>
<div class='tags'>
<p><?php echo $data['Tags']; ?></p>
</div>
</div>
</div>
<?php } ?>
<script>
var request;
$('.uparrow').click(function(){
request = $.ajax({
url: 'votesHandler.php',
type: 'post',
data: { add : '1', ID : $(this).attr('data-id') }
});
request.done(function (response, textStatus, jqXHR){
alert('Voted!');
});
request.fail(function (jqXHR, textStatus, errorThrown){
alert(
'Oops, something went wrong'
);
});
request.always(function () {
alert('Done.');
});
});
</script>
</body>
</html>

jQuery .post callback includes the .php- file where the jQuery is called from

I have a hello.php file that has some basic html in it. I am using ajax to retrieve data from another.php file. jQuery script posts data to another.php and put the callback data to div.
The problem is that the callback data from .post contains everything in the hello.php plus the actual callback data (check below). I've shortened the files (containing DB-connections for instance) from the actual ones, but the effect is the same whether I use the actual ones or these stubs. This was working just fine before, but was broken when I created a login action to the site. Only includes are objects of different classes that dont work with the posting and there is no reference to include the hello.php file.
Has anyone encounter a problem similar to this?
hello.php
<html>
<head>scripts etc..</head>
<body>
<h1>Hello</h1>
<button id="dataButton" value="GetData">Get Data</button>
<div id="cb">Callback data here</div>
</body>
</html>
another.php
<?php
echo "world!";
?>
jQuery script
<script>
function getWorld() {
$.post("another.php", function(data) {
$("#cb").html(data);
// alert(data); this also contains all of the data in This page
});
}
</script>
js function
<script>
$(document).ready(function() {
$("#dataButton").click(function() {
getWorld();
});
});
</script>
This will output the following html page source:
<html>
<head>scripts etc..</head>
<body>
<h1>Hello</h1>
<button id="dataButton" value="GetData">Get Data</button>
<div id="cb">
<html>
<head>scripts etc..</head>
<body>
<h1>Hello</h1>
<button id="dataButton" value="GetData">Get Data</button>
<div id="cb">Callback data here</div>
</body>
</html>
<script>
$(document).ready(function() {
$("#dataButton").click(function() {
getWorld();
});
});
</script>
<script>
function getWorld() {
$.post("another.php", function(data) {
$("#cb").html(data);
// alert(data); this also contains all of the data in This page
});
}
</script>
world! // <-- This gets back from server.
<script>
$(document).ready(function() {
$("#dataButton").click(function() {
getWorld();
});
});
</script>
<script>
function getWorld() {
$.post("another.php", function(data) {
$("#cb").html(data);
// alert(data); this also contains all of the data in This page
});
}
</script>

Jquery Not Loading PHP File

I have not been able to use JQuery/Ajax to load the content of my PHP file into a div tag.
Here is my page that is loading the file:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
function init() {
reloadChat();
setInterval (reloadChat, 5000);
}
function reloadChat() {
$.ajax({
url: "chat.php",
cache: false,
success: function(){
$("#chatmenu").load("chat.php");
},
});
}
</script>
<body onLoad='init()'></body>
<div id='chatmenu'></div>
The PHP file I am loading (chat.php) is in the same folder, and is just an echo statement:
<?php echo "test"; ?>
To make sure it was not a problem with my Javascript functions, I added an alert under the success function, and it did alert me every 5 seconds, so I think it is something with the load statement.
Use .load() straight away, no need to make an Ajax request first:
function reloadChat() {
$("#chatmenu").load("chat.php");
}
Update:
I notice that in your example code, you close your body-tag before your div element.
<body onLoad='init()'></body> <!-- This ain't right -->
<div id='chatmenu'></div>
Try this instead:
<body onLoad='init()'>
<div id='chatmenu'></div>
</body>
Try this:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
function init() {
reloadChat();
setInterval (reloadChat, 5000);
}
function reloadChat() {
$.ajax({
url: "chat.php",
cache: false,
success: function(response){
$("#chatmenu").text(response);
},
});
}
</script>
<body onLoad='init()'></body>
<div id='chatmenu'>
</div>
Also, for the love of god, please use an up-to-date version of jQuery
It looks your first request from $.ajax will return 'test', and then you're using that as the URL for $("#chatmenu").load.
Try this:
function reloadChat() {
$.ajax({
url: "chat.php",
cache: false,
success: function(data){
$("#chatmenu").append(data);
},
});
}
Or, if you want to replace the contents of #chatmenu the method posted by Christofer Eliasson where you just call $("#chatmenu").load("chat.php") in reloadChat will work.
Putting it all together:
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="chatmenu"></div>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(function() {
setInterval (function() {
$("#chatmenu").load("chat.php");
}, 5000);
});
</script>
</body>
</html>

Load Tracking Script on Form Submit

I'm trying to load a StatCounter tracking script after the form has been successfully sent. Here's the code:
$.ajax({
type: "POST",
url: "css/sendmail.php",
data: dataString,
success: function(data) {
$('#script').load('css/script.html', function() ({
$('#overlay').css('visibility','hidden');
clearForm();
$('#alert').slideDown().delay(5000).slideUp();
});
}
});
This is the tracking script:
<!-- Start of StatCounter Code -->
<script type="text/javascript">
var sc_project=3886809;
var sc_invisible=1;
var sc_security="05496a3d";
</script>
<script type="text/javascript" src="http://www.statcounter.com/counter/counter.js"></script><noscript><div class="statcounter">
<a title="visit tracker on tumblr" href="http://www.statcounter.com/tumblr/" target="_blank">
<img class="statcounter" src="http://c.statcounter.com/3886809/0/05496a3d/1/" alt="visit tracker on tumblr" ></a></div></noscript>
<!-- End of StatCounter Code -->
I checked my stats and it works. The only problem is that the code is being executed twice. The first one shows up as "http://example.com/index.html" and the second one as "http://example.com/index.html#".
Couldnt it be just as simple doing it like
<div style="display:none" id="tracker">
<!-- PUT STATCOUNTERHERE -->
</div>
and in the success function do the following
$('#tracker').show();
The other way would to store the code as a var
var statcode = "<script> blahblahblah.....";
and then on success
$('#whereuwanttoshowit').html(statcode);

Categories