Using Ajax in a PHP class - php

I am building a simple website using php in a mvc fomat and I'm trying to use ajax to call a simple clock but having trouble. Right now im just tyring to get a "hello world" example in my code to get started and go from there. An example format of my php class is : (the hello.php just echos hello world, and a Run() is being called at an index.php). For the life of me I can not get the script to work , any help would be appreciated.
Thank you.
<?php
class MyFile{
public static function Run(){
MyFile::show();
}
public static function show(){
echo 'html stuff';
?>
//run this sample ajax script i found //
<body>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$.get("hello.php", function(data){
alert(data);
});
});
</script>
</body>
<?php
}
}
?>

If we disregard the fact that your provided example code is a mess of PHP + HTML.
The provided code works just fine if you know how to call it via php, e.g.:
$obj = new MyFile(); // instantiate obj/class
$obj::Run(); // execute static method
Advice in general: try to avoid writing mixed "view (html)" + "logic (php)" code especially like the example you provided where it's a class no less.
If you can't help it at least you can make it look cleaner by using include or similar in php.
Here is a bit of longer explanation why you should try to avoid mixing:
Should I Include PHP code in HTML or HTML in PHP?

Related

Calling a PHP function through an HTML Link (no form)

I have a PHP Function that I would like to integrate into my (existing) web page. Further, I would like it to execute when the user clicks a link on the page. The function needs to accept the text of the link as an input argument.
Everything I've researched for sending data to a PHP script seems to involve using forms to obtain user input. The page needs to accept no user input, just send the link-text to the function and execute that function.
So I guess the question is two-part. First, how to execute a PHP script on link click. And second, how to pass page information to this function without the use of forms. I am open to the use of other technologies such as AJAX or JavaScript if necessary.
EDIT:: Specifically what I am trying to do. I have an HTML output representing documentation of some source code. On this output is a series of links (referring to code constructs in the source code) that, upon being clicked, will call some python function installed on the web server (which leads me to think it needs called via PHP). The python function, however, needs the name present on the link as an input argument.
Is there some sort of interaction I could achieve by having JavaScript gather the input and call the PHP function?
Sorry for the vagueness, I am INCREDIBLY new to web development. If anything is unclear let me know.
You'll need to have a JS function which is triggered by an onclick event which then sends an AJAX request and returns false (so it won't be redirected to a new page in the browser). You can do the following in jQuery:
jQuery:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("myfile.php");
return false;
}
</script>
And in your page body:
Click Me!
In myfile.php:
You can add whatever function you want to execute when the visitor clicks the link. Example:
<?php
echo "Hey, this is some text!";
?>
That's a basic example. I hope this helps.
You will need to use AJAX to accomplish this without leaving the page. Here is an example using jQuery and AJAX (this assumes you have already included the jQuery library):
First File:
<script language="javascript">
$(function(){
$('#mylink').click(function(){
$.get('/ajax/someurl', {linkText: $(this).text()}, function(resp){
// handle response here
}, 'json');
});
});
</script>
This text will be passed along
PHP File:
$text = $_REQUEST['linkText'];
// do something with $text here
If you are familiar with jQuery, you could do the following, if you don't want the site to redirect but execute your function:
in your html head:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
the link:
Execute function
in ajax.php you put in your function to be executed.
Maybe something like this:
....
<script>
function sendText(e)
{
$.ajax({
url: '/your/url/',
data: {text: $(e).html()},
type: 'POST'
});
}
</script>
You can use query strings for this. For example if you link to this page:
example.php?text=hello
(Instead of putting a direct link, you can also send a ajax GET request to that URL)
Inside example.php, you can get the value 'hello' like this:
<?php
$text = $_GET['hello'];
Then call your function:
myfunction($text);
Please make sure you sanitize and validate the value before passing it to the function. Depending on what you're doing inside that function, the outcome could be fatal!
This links might help:
http://net.tutsplus.com/tutorials/php/sanitize-and-validate-data-with-php-filters/
http://phpmaster.com/input-validation-using-filter-functions/
Here's an overly simplistic example of what you're trying to do..
Your link:
Some Action
Your PHP file:
<?php
if (isset($_GET['action']))
{
// make sure to validate your input here!
some_function($_GET['action']);
}
PHP is a server side language i.e. it doesn't run in the web browser.
If you want a function in the browser to operate on clicking a link you are probably talking about doing some Javascript.
You can use the Javascript to find the text value contained in the link node and send that to the server, then have your PHP script process it.

Calling Javascript based on PHP conditional when libraries load in the footer

I have the following in the body of a php page:
<?php if($foo) : ?>
<script>
js_func();
</script>
<?php else: ?>
//Do Something else
<?php endif; ?>
Based on the PHP conditional I either do or do not want to run js_func().
However if I am loading all of my scripts (including the script the defines js_func()) at the bottom of my page this will results in an error.
One possible solution would be to load the external script BEFORE calling js_func() but I understand that for performance reasons I shouldn't do that.
I could use $(document).ready(function() {}); but this just moves the error as jQuery is also loaded in the footer.
The only other options I can think of is to use window.onload or never call a js function inline. How does everyone else solve this issue?
Many thanks.
EDIT:
#Nile - Im not sure what you mean. Why would I comment out code that I want to execute?
#haynar1658 - I don't want to execute JS in the else scenario.
#Matthew Blancarte - Understood. That leads to my question, what's the best way to make sure that the js I need loads before that function is instantiated? Include the script before it? Use window.onload? etc.
I think you are making a rod for your own back. Depend on the question you described, you want to put all the function definition script block after the place where them being called. It's Impossible!
If you indeed need to do this, does this can help? :
<script>
var fns = []; /* use fns to keep all the js code
which call the functions defined after. */
</script>
<script>
//wrapp your code in a function and then push it into fns.
fns.push(function(){
js_func();
})
</script>
//script tags for loading your function definition js script.
<script src="path/to/jquery-any-version.js"></script>
<script src="path/to/other-libraries.js"></script>
<script>
//after your definition js scripts are loaded , call all functions in fns
for(var i=0, len=fns.length; i<len; i++){
var fn = fns[i];
fn.apply(this, []/* arguments that provided as an array */);
}
</script>
Just move the script to the top.
The difference (if there is one) is very small.
The believe that putting the <script>s in the <head> slows down the page is not "accepted" by all developers.
Did you try to echo it in PHP?
<?php if($foo) {
echo "<script> js_func(); </script>";
}else{
echo "something else";
}

issue calling JavaScript function from PHP

basically I am trying to call a javascript function from my PHP and I am using code I know works in other situations however here is it not and I am at a loss as to why?
It may be something stupid as I have been staring at this screen for a long time :)
here is where I call the function:
if(isset($test_details['done_test'])){
echo "getting here";
echo "<SCRIPT LANGUAGE='javascript'>user_error();</SCRIPT>";
}
I successfully get 'getting here' printed however it does not call the JS function.
javascript function:
function user_error(){
document.write("working");
//alert("User has already taken this test. Your are being redirected...");
//setTimeout("window.location='home_student.php'",3000);
}
The commented it what I do eventually want it to do.
Could anyone please shed some light.
Many thanks,
#Crimson - Here is what I tried after your advice...still no luck.
javascript now:
$(document).ready(function () {
var done = "<?= $test_details['done_test'] ?>";
if(typeof done != 'undefined'){
$('WORKING').appendTo('#bodyArea'); // just to test
}
});
By echoing <script>...</script> with PHP, you are not going to get the browser run the JS function!
PHP only outputs the HTML file that you want to send to the browser. The browser then parses this HTML and does a multitude of things before the page is displayed to the user.
Next, the user interacts with the displayed page (or some other browser related event like 'onload' happens) and the attached JS gets called.
So, if there is some JS that you want to run at a certain time, say immediately after the browser has finished loading the page, you need to create JS in the HTML file such that there is a JS function which gets called at the page load event like this:
<body onload="/*do something here*/"> ... </body>
It is better to use JQuery or some other JS frmework to accomplish something like this though.
Are you sure the function is already defined? Perhaps you declared your function after making the function call.
Additionally, although it's not really going to matter here, the proper way to have a javascript script tag is.
<script type="text/javascript"></script>
i.e. not language="javascript"
Replace the line you call the JS function with this:
echo '<script type="text/javascript">window.onload = user_error </script>' ;
It should solve the problem. Because at the time you are calling user_error(), the function may not have been initialized by the browser. So you'll get an error since the function could not be found.
If the function is placed in an external .js file, it's very likely that you get this error, since the external file usually takes a while to be loaded. If the function deceleration is in the same file but after where you are calling it, same thing happens.

Cannot use php tag in javascript tag

I'm trying to use php tag in a javascript function. But unfortunately its not working. I even used <?php but still not working. I checked php.ini file and there the short tag is already enabled.
Any sort of suggestion will be appreciated.
You should be aware that a php tag inside javascript gets evaluated on the serverside before it gets sent to the client. Example: If the php variable $feeling holds the string "love" "I love cheese." gets alerted.
<script type="text/javascript">
var text = "I <?php echo $feeling;?> cheese";
alert(text);
</script>
In that case the javascript code that gets returned from the server will look like:
<script type="text/javascript">
var text = "I love cheese";
alert(text);
</script>
I hope this will be of help to you to solve your issue.
as you described here, your code should be working. you can use php code in JavaScript with PHP tags() if you are using core php.but its not working in smarty structure. so please mind it and check if you are using any framework or structures.
Thanks.

Problem calling a js function from php

I am using my php to call a js function like this:
<?php
$chk=1;
if($chk==1)
{
echo '<script>testing();</script>';
}
?>
and my js looks like:
function testing()
{
document.getElementById("mainbody").innerHTML="This is my first JavaScript!";
}
The js is an external js file.
My html looks like:
<html>
<head>
<script src="qotw.js"></script>
</head>
<body>
<div id="mainbody"></div>
</body>
</html>
but this is not working. What am i doing wrong over here?
Please tell me if you know.
Best
Zeeshan
You run the script before the div you are targeting exists, so the document.getElementById call returns a false value instead of an HTMLElementNode.
You either need to move the script element so it is after the div, or assign the function to an event handler (onload for instance) instead of calling it directly.
This has nothing to do with the use of PHP.
Incidentally, your HTML is invalid and triggers quirks mode.
Try testing the following in order:
first: Your script is being called
<script type="text/javascript">alert("hello");testing();</script>
second: The function is being called
function testing() {
alert('inside testing');
}
third: As suggested above,
if (document.getElementById("mainbody") == null) alert('yep, its null');
then let us know the results
Make sure that 'testing' isn't called above 'mainbody' in the code, because then the code would be run at a point during load, when the object doesn't exist.

Categories