print another page from the current page passing a value - php

hi i need to validate the next page before printing it ...
what i did is i used i frame in the first page and called the page i needed to print
but it fired the query in the first page which should have been fire in the second page after the submission or click of the button ...
so i need to fire the php function after the button click which calls a function in javascript how should i do this?
could anybody help me...

Okay, I am not familiar with your level of PHP knowledge, so I will start with some basics:
PHP is a server-side scripting language. It compiles in real-time when a page is requested. The server processes the HTML and PHP and serves an HTML only page to the browser. You cannot execute PHP code on the client side. There is no way to get PHP code running at the time of a button press without the use of AJAX. You could use AJAZ to make a request to the server at the press of the button and fill the iFrame with the output.
Hope that helps.

so i need to fire the php function after the button click which calls a
function in javascript how should i do
this?
I am not quite clear on why you would need to do this but here it goes...
In the button click handler you want to make an AJAX call. I use jQuery but you can use whatever framework or XMLHttpRequest function you wish.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
function ButtonClickHanlder( e ) {
// Prevent the button from doing something it's normal functions(ie submit form if it is a submit)
e.preventDefault();
// Make AJAX Call
$.post("test.php", { call: "callMe" },
function(data){
alert("Data Loaded: " + data);
}
);
}
$(function(){
$('#clicker').click(ButtonClickHanlder);
});
</script>
</head>
<body>
<a id="clicker" href="#">test</a>
</body>
</html>
Reference: http://docs.jquery.com/Ajax
The test.php page
<?php
if(isset($_POST['call']) && $_POST['call'] == 'callMe') {
callMe();
}
function callMe() {
echo "I am a php function. You rang?";
}
?>

Related

How to run a php function on page reload? [duplicate]

I have this simple function in javascript to refresh a page after a set time.
function AutoRefresh( t ) {
setTimeout("location.reload(true);", t);
}
Now after every refresh, I want it to call a PHP function, for example:
function writeName()
{
echo "Refresh me";
}
Is it possible to call the PHP function in JavaScript after every refresh?
Thanks
I'm afraid the answer is no. By the time JavaScript has been run on your page, the server side (PHP) has already finished processing. Your best bet is to accomplish what you need before the page load, or accomplish it with JavaScript alone.
If you are refreshing the page, you're effectively reloading it from the server, so any 'onload' events will fire again. The page will render again from scratch. You can call a PHP script using AJAX in some 'onload' Javascript listener if you like, though. e.g. with JQuery:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready( function () {
setTimeout("location.reload(true);", 2000);
$.get('home.html', function(ret){
$('body').html(ret);
});
});
</script>
</head>
<body>
<h1>Test</h1>
</body>
</html>
Beware of calling setTimeout() recursively though as it can make a page unresponsive over time. You may find this useful:
http://www.erichynds.com/javascript/a-recursive-settimeout-pattern/

Using jQuery AJAX to redirect user on button click

I am new to jQuery AJAX function. I want to redirect my user to a webpage when he clicks a button. Please do not tell me to target the button to the webpage as I have to do some working in the php file... My current code is :-
TEST.html file :-
<html>
<head>
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("test2.php");
});
});
</script>
</head>
<button>Get External Content</button>
<div id="div1"></div>
</html>
Now my test2.php file is the following :-
<?php header("Location:http://google.com"); ?>
I am a beginner in AJAX jQuery. So, please do not downvote my post although it may sound silly. My code, for obvious reasons is not working. Please help me. Thanks in advance. Any help will be appreciated.
You cant redirect with an AJAX call. You can either create a simple link or link to a PHP page which then redirects the user on. Using AJAX will only let you manipulate this page you are on.
Of course, you can always redirect with simple Javascript as well.
window.location = '/my_url.php';
EDIT: In response to your comment question, what I would do is use the .get() function with the data parameter, check what has been returned from the PHP page if server side validation is required and then if I am happy with the result, redirect.
If no server side validation is needed, there is no need for AJAX.
Look at it this way: AJAX is requesting and reading the .php file. When AJAX sees the header("Location: ...") line, it redirects the AJAX request. Put simply, AJAX can't be used for redirects.
You can use the complete callback to redirect the user after the AJAX query has completed like so:
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("test2.php",
complete: function(){
window.location = 'http://new_url';
}
);
});
});
That being said if you just want to redirect a user on a button click there are better ways to do that.
$("#div1").load("test2.php");
appends the contents which are
returned from test2.php , it will not redirect. The test2.php should return a link and populate the div with the link. Then write a callback on ajax success which will
redirect using window.location = target , the target being the link which was dynamically loaded in the div1

running a php code from a link without redirection

I want to execute a php code when a user click on a given link , i've tried the following code
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("up.php");
return false;
}
</script>
</head>
<body>
<center>
Click Me!
</center>
</body>
</html>
where up.php is a php code that implement android GCM mechanism similer to the one in the link : GCM with PHP (Google Cloud Messaging)
but unfortunately when the link is clicked nothing happens , the php code not executed ,and only the url of the page change form *****.com/test.html to *****.com/test.html# , and by the way I've tested the php code and its works fine so it is not a problem in php code , so what i have missed here? why the code is not executed?
i found the solution , the problem that the jquery library is not included probably in my code
you are using jquery. $.get() will be something like below.
$.get('ajax/test.html', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
for further help check http://api.jquery.com/jQuery.get/
Sometimes, you may need to call some JavaScript from within a link. Normally, when user click on a link, the browser loads a new page (or refreshes the same page).
This might not always be desirable. For example, you might only want to dynamically update a form field when the user clicks a link.
To prevent the load from refreshing, you could use the JavaScript void() function and pass a parameter of 0 (zero) as below.
<a href="JavaScript:void(0);" onclick="return doSomething(); " />Click Me!</a>
Now if you want to use href="#", make sure onclick always contains return false; at the end.
OR
Use href="javascript:void(0)"
You can also use jQuery Load
function doSomething() {
$('#result').load('up.php', function() {
alert('Load was performed.');
});
}
When you are using Jquery should be :
function doSomething(){
$.get('up.php', function(data) {
$('.data').html(data);
});
}
Link
To stop page refreshing, you can use the javascript void() function and pass parameter of 0.
Click Me!
<div class="data"></div>
This div is used to display up.php result.
Ok start of by using fire bug and watch the console and network panels
Ensure the browser is trying to get something and not returning a 404 or a php error on the get
Look into prevent default http://api.jquery.com/event.preventDefault/
To stop the original link functionality working
If you still want them to move to the link use a window location or...
Look into bootstrap link buttons
http://twitter.github.com/bootstrap/base-css.html#buttons
( the link button )

jQuery: How do I POST on CLICK?

I'm trying to figure out how I can pass data from page-list.php to page.php using jQuery .post() and .click().
Code in <head> of page-list.php:
<script type="text/javascript">
$(document).ready(function(){
$('button.link').click(function () {
$.post("page.php", {pageID: "1"} );
}
});
</script>
Code in <body> of page-list.php:
<button class="btn link">LINK</button>
When I click LINK, nothing happens.
I'm also not sure how to call the posted data on page.php. Should I create a variable in PHP like this?
$pageID = ($_POST['pageID']);
And then call it in the body like this?
echo $pageID;
If I understand correctly what you are trying to do is $.post() a variable to "page.php" and then redirecting to "page.php".
If that is what you are trying to do it just won't work. $_POST requests are independent of each other, i.e. using $.post, accessing $_POST['pageID'] will result in whatever value you sent but won't display anything because the browser was not sent to the new page with the variables; but redirecting and trying to access the same variable will result in "null".
It is that same reason that when you use a log in system and refresh the page right afterwards the browser confirms that you want to send the information again.
Using $_GET might be more of what you need. Another option would be to use and form to post the variables.
I hope that helps.
For one thing you are missing a couple of characters.
<script type="text/javascript">
$(document).ready(function(){
$('button.link').click(function () {
$.post("page.php", {pageID: "1"} );
}); // missing end of statement.
});
</script>

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