Run PHP on button click - php

I am learning jQuery and PHP. I am making a simple yes or no oracle. Its working but I need to refresh the page if i want to ask something new. I would like to fire the PHP when someone clicks the button. My code is pretty simple. <div class="ask"> Is the button. I know i could do it with jQuery but i would like to learn a little PHP.
My Code:
PHP:
$answer = array("Yes", "No", "I could not decide ask again later");
$randKey = array_rand($answer);
jQuery:
$(document).ready(function() {
$( ".ask" ).click(function( event ) {
event.preventDefault();
});
$('input').bind("enterKey",function(e){
$('.ask a').click();
});
$('input').keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterKey");
}
});
$('.ask a').click(function(){
if($('input').val() == ''){
$('h2 span').remove();
$('h2').append("<span>It's a secret? You need to ask someting.</span>");
}
else{
$('.answer span').fadeIn(2000);
$('h2').css({'border-bottom' : '1px solid black', 'padding-bottom' : '20px'});
var kysymys = $('input').val();
$( "h2" ).html( "<b>You asked: </b> " + "<span>" + kysymys + "?</span>");
// $('input').val("");
}
});
});
HTML:
<body>
<?php require_once("inc/yes-or-no.php"); ?>
<h2></h2>
<h1 class="answer"> Your answer: <span><?php echo $answer[$randKey]; ?></span></h1>
<p class="input"><input type="text" autofocus> <span>?</span></p>
<div class="ask"> Ask your question!</div>
</body>

You would need to use AJAX to send a request to the web server. You can't just run PHP in javascript (unless someone built a interpreter): javascript generally runs on the client side, while PHP runs on the server side. To get PHP to do stuff, you must ask the server the right questions (i.e. HTTP requests).
EDIT: oh, I misread and missed the require_once(). Just make PHP echo a javascript or hidden HTML section, then pull the relevant info out using javascript.
e.g.
echo <script>var foo = "bar"; </script>
Of course, you should then first make the server actually run the served pages using the PHP interpreter.

i think you need to understand php runs in server while jquery runs on client-side. so whenever someone clicks a button, you need to notify your server-side php code to do something. you can do this using ajax. this will not cause page-refresh.

PHP is a server-side language whereas JavaScript (which jQuery is built on) is a client-side language. This means that if you want execute a PHP file, you need to submit a request to the server, have the server execute it, then reply to the client with the result. You can do this (as you're doing it now) by refreshing the page. Alternatively, you can make an AJAX (JavaScript) call.
You cannot have the client execute PHP code — the client only executes JavaScript.

HTML:
<body>
<h2></h2>
<h1 class="answer"> Your answer: <span><?php echo $answer[$arrayKeys[0]]; ?></span></h1>
<p class="input"><input type="text" autofocus> <span>?</span></p>
<div class="ask"> <a type="submit" href="#"> Ask your question!</a></div>
</body>
jQuery:
$('.ask a').click(function(){
if($('input').val() == ''){
$('h2 span').remove();
$('h2').append("<span>It's a secret? You need to ask someting.</span>");
}
else{
$(".answer span").load("inc/yes-or-no.php");
}
});
PHP:
header("Cache-Control: no-cache");
// Ideally, you'd put these in a text file or a database.
// Put an entry on each line of 'a.txt' and use $prefixes = file("a.txt");
// You can do the same with a separate file for $suffixes.
$prefixes = array("Yes", "No", "I couldn't decide, ask again later.");
// This selects a random element of each array on the fly
echo $prefixes[rand(0,count($prefixes)-1)];
// Example output: Tagging is the new Media
You can read more on Sitepoint
Thanks To http://www.sitepoint.com/ajax-jquery/

Related

jquery hasClass does't work when checking dynamically added class

I have a problam that I dynalically add a class to div through php, and then checking if id "checkLang" has spacific class, but it desn't work :(
Maybe someone knows the problem?
My html:
<div id="checkLang" class ="<?php echo $valoda ?>"><div>
and that div I check with
if ($('#checkLang').hasClass('RU')){
<?php include("lan/ru.php"); ?>
};
if ($('#checkLang').hasClass('LV')){
<?php include("lan/lv.php"); ?>
};
I don't know why, but both ifs include language php file.
But maybe the reason is because this script is in php file with header <?php header('Content-type: text/javascript'); ?> I attach file like javascript file in index page like <script type="text/javascript" src="php/FormuValidacija.php" /></script>
I tried
if($_GET['lang']=="latviesu"){
include("php/lan/lv.php");
}
else($_GET['lang']=="krievu"){
include("php/lan/ru.php");
}
But doesn't work as well :(
P.S. Sorry if this is stupid question, i'm new whit this stuff, but willing to learn! :)
Looks like your script is not added in a dom ready handler like
jQuery(function($){
alert($('#checkLang').length)//it should alert 1 not 0
if ($('#checkLang').hasClass('RU')){
<?php include("lan/ru.php"); ?>
};
})
Current language:
<div id="checkLang" class ="<?php echo $valoda ?>"><div>
Including your localization files:
<div class="ru" style="display:none;">
<?php include("lan/ru.php"); ?>
</div>
<div class="lv" style="display:none;">
<?php include("lan/lv.php"); ?>
</div>
Getting current language and showing corresponding div
<script type="text/javascript">
$(document).ready(function(){
var currLng = $('#checkLang').attr('class'); // get current language, i.e class of #checkLang
$('div.' + currLng).show(); // show div with corresponding class, i.e lang
});
</script>
However, its better to get language at server side and not to load unused files to client(i.e HTML)
P.S un labāk visus variablus, script failus etc saukt anglū valodā :)
Given my jsfiddle example here, you can clearly see that javascript is able to check that the given class is set on the div.
http://jsfiddle.net/n5e9a/
Both of the php files will be rendered no matter what, because the if check here is done on the client side javascript. if you wish to only render data from the php files once the check has been done on the client side. Then you have to fetch the data from the client side instead of serving it from the server side.
One way of doing this is through ajax. for example. you could create a php script that returns html contents based on a query, something like:
checklang.php?lang=RU
and in the javascript code you would have a request set up like this:
$.get('checklang.php?lang=RU', function(data) { //switch RU with a js variable so you can change between RU and LV programatically
$('#some-content-div').html(data);
});
it includes your content because its generated server side already, so when the html site is transfered the php script is already rendnered while the javascript is handled client side, you would have need to adapt your try
you see this would work
<div id="checkLang" class ="<?php echo $valoda ?>"><div>
<div class="ru" style="display:none;">
<?php include("lan/ru.php"); ?>
</div>
<div class="lv" style="display:none;">
<?php include("lan/lv.php"); ?>
</div>
$(document).ready(function()
{
if ($('#checkLang').hasClass('RU')){
$('.ru').show();
}
if ($('#checkLang').hasClass('LV')){
$('.lv').show();
};
});
example here:
http://jsfiddle.net/yVpf4/
tough it would rendner all language content; you should consider doing the language selection within the php code to avoid extra traffic unless you want to switch language via javascript only without any server interaction.
regards jan
also as Arun P Johny stated
...your script is not added in a dom ready handler...
regards jan

How to trigger php code, in Javascript if condition

Ok , so what I'm trying to do is trigger PHP code, only when the if condition is true (in javascript) , I understand that php is server side, and javascript is client side. The include of the php code works perfect except 1 thing , it gets triggered on page load actually , not when the if condition happens. If you can help me how to do this will be rly appreciated. I want the php file to be included ONLY when the if condition is true
thanks in advance
here's the code am using :
<html>
<script src="//cdnjs.cloudflare.com/ajax/libs/visibility.js/0.5/visibility.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script>
var seconds=20;
var flag=false;
$(document).ready(function(){
if (!flag)
Visibility.every(1000, tick);
function tick()
{
display();
if (seconds>0)
{
seconds--;
}
else
{
if (!flag){
document.getElementById('more').innerHTML +="<?php include_once('Code.php');
?>";
document.getElementById('more').style.visibility='visible';
flag=true;
}
}
}
function display()
{
$("#timer").html(seconds);
}
});
</script>
<div id="TrafficHeader" style="height:100px; background-color:grey; padding:20px;">
<div id="timer"></div>
<div id="more" style="visibility: hidden;">View Next Ad</div></div>
<iframe id="myframe" src="<?php echo ''.$URL;?>" height="100%" width="100%" frameborder="0">
</iframe>
</body>
</html>
This is not possible, at least not the way you are going about it.
The reason is that the if condition is evaluated on the client machine long after the server finish evaluating your php script.
First server has to finish procesing your php script, then imagine it has to pack it and then send the whole package to the client, which then unpacks it and renders the html and evaluates the javascript in html, or asks for external files like images, css or other script files.
If you are trying to include some extra javascript ,than you can add extra script tag in the head programatically. If you want to do something on the server, you can call a script on a server just as easily.
Here is how you can exeecute that script from javascript only if the if is true:
...
if (!flag){
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "http://link/to/your/code.php?and=special&parameters=sent", false );
xmlHttp.send( null );
document.getElementById('more').innerHTML += xmlHttp.responseText;
document.getElementById('more').style.visibility='visible';
flag=true;
}
...
The php code is server side so it's executed before the javascript so javascript CAN'T control what php does. You need to use an Ajax script to make javascript can request a php file from the server, and then it'll work.
You can't do it that way... you said it yourself, PHP is server-side. In order to run PHP, you have to have the browser query something against your web server. This will most definitely not work as you intended... it'll always be included:
innerHTML +="<?php include_once('../../Includez/Traffic/Traffic_Code.php'); ?>";
You can, however, cause the JavaScript to fetch something more from the server which can run some PHP code and return something new to your page...
Did you try solution with "load"?
<div id="special_block"></div>
<script>
var a = 1;
if (a == 1){
$('#special_block').load('code.php');
}
</script>

Mootools script corrupts php tags when sets html into document

I am developing module for Joomla 2.5. and I had one problem. I wanted to send data to same page and receive answer in it, without reloading. I found solution for it, but then I stuck again.
The problem is that when I want to insert into div tags code <?php echo $msg; ?> using javascript it turns into comment <!--php echo $msg; ?-->.
Here is full function
<script type="text/javascript">
window.addEvent('domready', function request() {
$('SNbutton').addEvent('click', function(event) {
event.stop();
var url = window.location.href;
var message = document.getElementById('message');
var msg = '<?php echo $msg; ?>';
var req = new Request.HTML({
method: 'post',
url: url,
data: {'artID' : $('artid').get('value')},
onComplete: function(response) { message.set('html', msg).setStyle('display','inline');
}
}).send();
});
});
</script>
and here is result html:
<form name="accept_form" action="#" ><br/>
<input type="hidden" id="artid" name="artID" value="4"/>
<input type="button" class="SNbutton" id="SNbutton" value="I take it!" title="Accept this job and bound it to your profile.">
</form>
<div id="message" style="display:inline;" ><!--php echo $msg ?--></div>
P.S. This script should take article id and send it to same page, where, depending on article, page will generate message which should be displayed in right place, but somehow its getting corrupt.
P.S.S. Don't worry about that server executes php code. As far as I know its not wotking if script is included trough src in head tags.
Could you try doing it this way?
var msg = <?php echo "'".$msg."'"; ?>;
I'm thinking that maybe the fact it's inside quotes is messing up the interpreter.
A chunk of PHP code inserted into a page that has already been loaded into a browser can't be interpreted by the server - it's just a string. To get the $msg value you want, you need another page that can respond to your Request.HTML call and get some code back.
The distinction here is between server-side and client-side code. I think to test this make your url something like provideMessage.php and then have THAT page respond to your Request.HTML.
It's possible I'm missing something about how Joomla modules work.

Issues since moving javascript to its own file

Alright, if you look at the code below, I am trying to make it more "flexible", moving the JavaScript code to its own file, instead of keeping it in the php file.
The code below is not gonna work anymore, since i cant transfer $yadayada['id'] to the JS file, well okay I dont know how to, and thats where my problem lies.
How can I use the code below, or some variant of it thats gonna work?
Whats gonna happen is that when you press a specific image(button), a modal will open for the specific post in the while statement.
I have skipped out the post part, since thats not the problem here, it is opening a modal window for the correct post.
Thanks in advance!
$yadaya = mysql_query("blablabal")
while($yadayada = mysql_fetch_assoc($yadaya)
{
<div id="kommentera<?=$yadayada['id']?>" class="settingsBox" style="display: none; width:500px; font-size: 14px;">
<textarea id="text<?=$yadayada['id']?>" class="textarea" style="width: 493px; height:80px;"></textarea><br />
<span class="buttons" style="float:left;">
<button id="kommenteraFilm" id1="<?=$yadayada['id']?>" uid1="<?=$yadayada['guid']?>" uid2="<?=$acc_info['id']?>" class="positive" type="submit" name="kommentera"><img src="<?=$static?>/img/bullet_go.png" alt="" />Kommentera</button>
</span>
<?php
?>
</div>
echo '
<div id="se-kommentera'.$yadayada['id'].'" class="testing" style="float:right; margin-top:-2px; cursor:pointer;">
<img src="'.$static.'/img/icon_kommentera.png" height="15px" width="15px" alt="" title="Kommentera" />
</div>'
;
}
footer:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="<?=$static?>/js/mylibs/dependency.js"></script
dependency.js:
$(function() {
$('#se-kommentera<?=$yadayada['id']?>').click(function (e) {
$('#kommentera<?=$yadayada['id']?>').modal();
return false;
});
});
UPDATE
To answer some of the responses, I think you are forgetting that I cannot access the while statement outside the statement itself, so making the js file a php file is kind of useless.
The JS file must be below the jQuery library file, which is in the footer.
You can generate Javascript through PHP (but it's not a good idea)
To directly answer your question: you can "generate" Javascript dynamically through PHP code. For example:
<!-- note that the source is .php so that the server processes it as such -->
<script type="text/javascript" src="dependency.php"></script
And dependency.php would look like:
<?php
// tell the browser how to interpret what we 'll be sending
header('Content-Type: text/javascript');
// get reference to any variables we need
$yadayada = /* ... */
?>
$(function() {
$('#se-kommentera<?=$yadayada['id']?>').click(function (e) {
$('#kommentera<?=$yadayada['id']?>').modal();
return false;
});
});
All of this is really the same thing you are doing when outputting HTML with PHP, only now you are outputting Javascript. But the problem is that you are doing the same work (what is required to get to $yadayada) two times once for your HTML, and once for your JS.
So what is a good idea?
Simply change your markup so that you do not need to know anything inside $yadayada when you write your JS; this way, the code can remain static. For example:
HTML:
<div class="se-kommentera testing">
<img src="..." height="15px" width="15px" alt="" title="Kommentera" />
<div class="settingsBox kommentera">
</div>
</div>
JS:
$(function() {
$('.se-kommentera').click(function (e) {
$(this).find(".kommentera").modal();
return false;
});
});
What I did here is provide a way of finding the appropriate .kommentera div not with an absolute identifier (the id) but in a manner relative to the .se-kommentera that was clicked.
For convenience, I chose to put one div inside the other and get a hold of it with .find; but this is not binding and you could really make dozens of different choices here. For example, you can give both divs an id like you did before and then do something like this:
$(function() {
$('.se-kommentera').click(function (e) {
var id = this.id.replace("se-", "");
$("#" + id).modal();
return false;
});
});
One simple way to do it would be to give the JavaScript-file a .php extension, instead of the regular .js. That way the PHP-code will be executed on the server, before the JavaScript is sent to the client. As you specify the type="text/javascript" on the script tag the browser won't mind the .php extension on your JS-file.
have you tried to echo $yadayada inside the js file?
This thread might help you Passing a PHP Variable in external JS file
If you want your javascript files to be able to output PHP variables, the best way I can think of is to add a mimetype to your htaccess file.
Something like the following would work for Apache...
AddType application/x-httpd-php .js

Calling JavaScript within Php block and vice-versa

echo "<a href=#> Delete </a>";
Whenever a user hits Delete, a javascript function should be called for confirmation. Somewhere in the Javascript function, php code should be used for delete operation. How do I do that? Use something like "some php code goes here" and "some javascript function();" for me to know where to put what. Thanks.
This assumes that you are using jQuery...
<a href='javascript:delete();'>Delete</a>
<script type="text/javascript">
function delete()
{
$.post("/your_script.php", {}, function(result) {
});
}
</script>
JavaScript functions execute on the client (in the browser) and PHP executes on a server. So, the JavaScript must send a message - via HTTP - to the server to be handled by PHP. The PHP would perform the delete. Make sense?
The message sent to the server might be sent via AJAX.
Maybe you should use Ajax: http://en.wikipedia.org/wiki/Ajax_%28programming%29
PHP is a server-side technology, while JS is a client-side. They cannot interact with each other - in other words: they're completely independent.
PHP can only output code that is a JS code:
echo 'document.getElementById("test").appendChild(document.createTextNode("' . $myVar . '");';
It's all PHP can do. JavaScript cannot direct interact with PHP as well. You'll have to use AJAX to send a new HTTP request and process returned data.
PHP is a server-side language, thus you can not output PHP script to the browser and expect that it will parse it with the PHP engine.
What you're looking for is probably AJAX, or simply redirecting the user to another page (with different URL parameters) or submitting a form.
AJAX doesn't require from the browser to reload the page, while the two other methods does.
Anyway, you can execute a JS script with the "onclick" method, that's executed when the user clicks on the element: Delete
But the following approach looks better and considered as an ideal one:
Delete
<script type="text/javascript">
document.getElementById("myId").onclick = myFunc;
</script>
Since this involves Ajax, let's assume you can use jQuery to handle the XHR an so on.
<script>
$('#del').click(function(ev){
ev.preventDefault();
var del_conf=confirm('Are you sure you want to delete this item?');
if(del_conf){ $.post('delete.php',{'del':1,'id':123123},function(data){
alert(data.result);},'json');
}
});
</script>
<a id='del'>Delete</a>
Okay, so that's some JS and HTML. Now, you need a separate PHP script to handle the post. To go with the example, this would be saved in the same directory, named 'delete.php'.
<?php
$del=(int)$_POST['del'];
$id=(int)$_POST['id']
if($del<1 || $id<1){ exit; }
else{
//do your DB stuff
}
if($db_success){
echo json_encode(array('result'=>'success'));
}
else{
echo json_encode(array('result'=>'error'));
}
here is another example using jQuery:
<div id="message"></div>
<a class="action" type="delete" rel="1234567">delete</a>
<script type="text/javascript">
$('a.action').click(function(){
var $this = $(this);
var processResponse = function(data){
//optionaly we can display server response
$('#message').html(data);
return;
};
var postPparams = {
module:'my_module_name',
action:$this.attr('type'),
record_id: $this.attr('rel')
};
$.post('/server.php',postPparams, processResponse);
});
</script>

Categories