Php echo content into div - javascript

I am trying to insert html and javascript which is generated in php into a div in the page.
a.php file:
function get_preset() {
return (bunch of html, javascript);
}
b.php:
<div id="preset_preview">
//<?php echo get_preset(); ?> //this works well, but I need to execute this every time I click a button in jquery.
</div>
I can use ajax to communicate between my jquery and a.php successfully, but how do I place returned content from get_preset function call in php into preset_preview div?
Is there a way to do this without sending data with ajax from get_preset function call into jquery, then use jquery to put this into preset_preview div?
Can php somehow do it alone each time on request from jquery like this?
So I use jquery ajax to call php to execute this:
<div id="preset_preview">
<?php echo get_preset(); ?>
</div>
What is confusing to me is that php can do it successfully (as example above demonstrates) without sending data with ajax to jquery first.

a.php file
function get_preset() {
return (bunch of html, javascript);
}
echo get_preset();
b.php file
<button type="button" id="preview">Preview Preset</button>
<div id="preset_preview">
<?php include "a.php"; ?>
</div>
<script>
$('#preview').on('click', function(e) {
e.preventDefault();
$("#preset_preview").load('a.php');
});
</script>
There are several methods of jQuery AJAX which you can actually use. Example above is using load() which wraps your request with get method (you can override its request method by calling ajaxSetup(), anyways) to relative URL of a.php.
You can see a.php echoing (string of?) get_preset() function which will then placed inside <div id="preset_preview"> in b.php file.
To expand the needs of AJAX in this case is because PHP only does something like
Getting a request, no matter what the method is (get, post, put, etc)
Returns a response. Usually after you do some logic related to request value.
It dies whenever your expected response rendered to client side. You can't do anything magic behind the wall right after response is returned. In the other word, a page load is needed.
And then AJAX comes to help you create another request to corresponding PHP file. It revives a PHP file to do (another) request -> do some logic -> then do returning it. Silently, without a page load.
And in respond of comment -- Can this be done with function calls somehow without including the actual php file in preset_preview?
It's all yes. As long as you serve whatever the caller needs.
a.php file
function get_preset() {
return (bunch of html, javascript);
}
echo get_preset();
The a.php is simply echoing get_preset().
b.php
<button type="button" id="preview">Preview Preset</button>
<div id="preset_preview"></div>
<script>
$('#preview').on('click', function(e) {
e.preventDefault();
$("#preset_preview").load('a.php');
});
</script>
The b.php file is simply doing a request to a.php file. Whenever the button with selector id #preview is clicked it will load whatever a.php content to #preset_preview.
You can also render the content of a.php just after the page ready. This is similar approach like my first snippet as written on above.
<script>
$(document).ready(function() {
$('#preset_preview').load('a.php');
});
$('#preview').on('click', function(e) {
e.preventDefault();
$("#preset_preview").load('a.php');
});
</script>
It simply tells you that you should load a.php right after the b.php page is ready and "reload" it once the button clicked.

Related

using ajax to pass string from php to javascript

So I have a piece of javascript code in an html document that responds to a button click. I want a new url to open, and if I specify the link in javascript as I've done below, everything works fine.
<input type="submit" id="submitbtn" value="Purchase Module"/>
<script type="text/javascript">
document.getElementById("submitbtn").addEventListener("click",handle_click);
function handle_click() {
var link;
link="http://www.google.com";
window.location.href=link;
}
</script>
Problem is I want to hide the real link on the server side as it includes a username:password. The php script below calls a function (not shown) that generates the link (a string). This also works fine.
<?php
$link=get_page_link();
?>
I want to pass the link string to the javascript and have tried various iterations of
link=<?php echo $link ;?> to no avail. As I understand it you can't pass strings this way and you need to use ajax. That's where I'm stuck. Seems like I need a $_POST on the php side and a $_GET on the java side, but not sure on the specifics. Any help would be appreciated. Thanks.

Pass Javascript variable to another page via PHP Post

I am having two php pages:
page 1:
<form class="form-horizontal" role="form" method="post" action="Page2.php">
<button id="place-order" class="btn btn-lg btn-success">Place Order</button>
<div id="ajax-loader" style="display:none;"><img src="images/ajax-loader.gif" /></div>
</form>
<script>
var id = Math.random();
$(document).ready(function() {
$('#place-order').on('click', function() {
$(this).hide();
$('#ajax-loader').show();
});
});
</script>
As on form, it redirects to Page2.php, I want to pass the Javascript variable "id" from Page1 to receive it in Page2.
I have tried using cookies, but need an alternative approach.
I am not understanding the transistion from PHP to JS and vice-versa. Help is appreciated.
Thanks in advance
Dear you can do it very easily with ajax. Ajax has data attribute which helps you pass your data from javascript to another page.
This link will help you a lot
https://api.jquery.com/jquery.ajax/
You can use session storage or cookies.
Example for session storage:
// First web page:
sessionStorage.setItem("myVariable", "myValue");
// Second web page:
var favoriteMovie = sessionStorage.getItem('myVariable');
You could use a query string to pass the value to the next page.
Add an ID to the form
<form class="form-horizontal" role="form" method="post" action="Page2.php" id="order-form">
Update the action of the form to add this query string from our JS variable
var id = Math.random();
$('#order-form').attr('action', 'Page2.php?id=' + id);
Get this variable in PHP (obviously you might wanna do more checks on it)
<? $id = $_GET['id'] ?>
We can now use $id anywhere in our PHP and we'll be using the ID generated from JS. Neat, right? What if we want it in JS again though? Simply add another script tag and echo it there!
<script type="text/javascript">
var id = <? echo $id ?>;
</script>
EDIT: Updated to add a little about how it works as you said you're not too sure about the transition between PHP and JS.
PHP runs on the server. It doesn't know much about the browser, and certainly doesn't know about JS. It runs everything and finishes executing before the web page is displayed. We can pass PHP variables to JS by creating script tags and creating a new javascript variable, echoing the PHP value.
JS (JavaScript) runs in the browser. It doesn't know about anything that happens on the server; all it knows about is the HTML file it is running in (hit CTRL+U to see raw HTML). As JS runs at a completely separate time to PHP there is no easy way to transfer variables (e.g. $phpVar = myJSVar). So, we have to use server methods like POST or GET.
We can create a GET or POST request in 2 main ways:
Using a form
Using an AJAX request
Forms work in the way I've outlined, or you can create a hidden field, set the value you want and then check for that. This involves redirecting to another page.
AJAX (Asynchronous Javascript And Xml) works slightly differently in that the user doesn't have to leave the page for the request to take place. I'll leave it to you to research how to actually program it (jQuery has a nice easy API for it!), but it basically works as a background request - an example would be displaying a loading spinner whilst loading order details from another page.
Hope this helps, let me know if something's not clear!

how to call php function through hypertext link

I want to call a PHP function passing an argument on clicking a hyperlink (text with <a> tag) on the same page, i.e. href='#' onclick='loadpic($id).
Where $id is the variable to be passed to PHP function.
You can do that by ajax easily. Create a loadpic function in javascript instead and then pass $id to the php file via ajax and do something when you get the result.
Your javascript file should look like this-
(make sure you've inserted a link for jquery in your index file)
function loadpic(id_param){
$.post("filename.php",
{
id: id_param
},
function(data){
alert("Data received:" + data);
});
};
The data parameter in function(data) would be the value that you've echoed in the php file.
If you want to use onclick() method in your HTML element then you have to write your method is javascript and make an AJAX call to PHP. THis is one simple way to do this using php and javascript. And for this please see javascript and ajax with PHP.
But if you dont want to use javascript then here is a simple way and very simple code.
<?php
if(isset($_GET['myMethod'])){
myMethod($_GET['id']);
}
function myMethod($id){
echo $id."<br>";
}
?>
<?php
$myId = 4;
?>
<a href="index.php?id=<?php echo $myId ?>&myMethod" >MyLink</a>
Note: Copy this code and paste into a file called index.php because notice the hyper link tag and its attribute href="index.php".
Also note that you can not directly call php method using js like onclick() from your HTML tag. You should use AJAX or something. But using above demo code you can easily call myMethod() which is a PHP method using the hyper link tag.
In your case:
<?php
if(isset($_GET['call_loadpic'])){
loadpic($_GET['id']);
}
function loadpic($id){
echo "My loadpic method has been called! and the id is".$id."<br />";
}
?>
<!-- your other codes -->
<?php
$id = 4;
?>
<a href="this-same-file-name.php?id=<?php echo $id ?>&call_loadpic" >MyLink</a>
This is because your php function is in the same page and you want to call that function using same file and hyperlink in the same file. (According to your question)
You still will have to make javascript handle the exception because php has no onclick.
onClick=\"loadpic("'.$id.'");"\
//this will only send a php variable javascript will still have to loadpic();

Temporarily changing HTML structure on the same page in PHP when submit button is clicked?

I have PHP page that have submit button to another URL.
I want to reload the current page after the submit button clicked, and add div to the HTML.
My page url is: /foo.php, and in the HTML I have:
<button onclick="$.get('/bar', function() { ... })">Submit</button>
As you can see the form sends request to /bar page.
I want to reload the /foo.php (the current page), and change the HTML to:
<button onclick="$.get('/bar', function() { ... })">Submit</button>
<div>Thank you!</div>
My problem is how can I know that the user click on the button and the refresh was because the click, and not because just navigating.
Another thing, if it possible, I want that the new div will disappear if the user refresh the page again.
Why don't you just append the div in the success callback of the get function? You wouldn't have to reload the page.
<div id="btn_area">
<button onclick="$.get('/bar', function() { $('#btn_area').append($('<div>').html('Thank You');)})">Submit</button>
</div>
By the way, i hardly recommend to separate the javascript from the html and not put it directli in the DOM.
Another Method would be, to fire an additional form with a hidden parameter to the same side. After that, you check on the serverside the hidden parameter and display the div.
A third method is, to set a cookie in the Callback, reload the side, check the cookie, display the div and remove the cookie again.
In my opinion, the first mentioned option (add the div directly in the callback without reloading) would be by far the 'prettiest', but of course i don't know what else is going on on your site
Alternatively, you could simulate a flash session (one time use session) if you opt to do this in PHP. Consider this example:
foo.php
<?php session_start(); ?>
<form method="POST" action="bar.php">
<button type="submit" name="thank_you">Submit</button>
</form>
<?php if(isset($_SESSION['thank_you'])): ?>
<?php unset($_SESSION['thank_you']); ?>
<h1>Thank You!</h1>
<?php endif; ?>
bar.php
<?php
session_start();
if(isset($_POST['thank_you'])) {
$_SESSION['thank_you'] = true;
// processes
header('Location: foo.php');
}
?>
Demo
You can handle that in js side. Just make your request, and in callback, you can manipulate dom. You can see below;
<button>Submit</button>
$("button").on("click", function() {
var $button = $(this);
$.get("/echo/html", function() {
$button.after("<div>Thank you!</div>");
});
});

Delays/inconsistencies in AJAX refresh

I've been working on a web app that allows users to submit content and have that content, and today I've been seeing some unexpected results without making any significant changes.
The basic functionality of the app is that the user submits some POST data from a form on a web page index.php, whereupon a PHP script submit.php is run to add the data to a table in a database. Meanwhile, a Jquery function on index.php is refreshing the contents of a div with rows selected from the table by means of a script load.php, and the function is called once per second.
The problem is that today, suddenly, I'm seeing long (10-20 minute) delays between when the data is added to the table and when it shows up in the Jquery-refreshed div. Moreover, the div flickers back and forth between its existing contents and the new data set with the added values, as if it were alternating between the realtime results of load.php and a previous call to the same script.
I've checked the MySQL database before and after submit.php is called and I've verified that the data is being added instantaneously once it's submitted, so the problem has something to do with how the load.php script is called from Jquery.
This just started today. Strangely, I've been seeing this same behavior with another AJAX app that I built earlier to test the same I/O mechanism, and I haven't touched that app's code in over a week. My system administrator says there haven't been any changes to the server that would account for this.
I've posted all the code to provide all necessary information, but I think the problem is either in load.php or the javascript updateMyContent() in index.php.
index.php
<script language="JavaScript">
setInterval("updateMyContent();",1000);
$(function(){
updateMyContent=function(){
$('#refreshData').load("./module/load.php").fadeIn("slow");
}
});
</script>
<script language="JavaScript">
$(document).ready(function(){
$('#submitForm').on('submit',function(e){
$.ajax({
url:'./module/submit.php',
data:$('#submitForm').serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
$('#textID').val('');
},
error:function(data){
$("#error").show().fadeOut(5000);
}
});
e.preventDefault();
});
});
</script>
<div style="float: right;
top: 0;
" id="submitDiv">
<form id="submitForm" action="" method="post">
<textarea id="textID" type="text" name="content" rows=5></textarea>
<input type="submit" value="send" name="submit"/>
</form>
<br>
<span id="error" style="display: none; color:#F00">error</span>
<span id="success" style="display:none; color:#0C0">success</span>
</div>
<div style="float: center;" id="refreshData"></div>
submit.php
<?php
if(isset($_POST['content']))
{
$content=$_POST['content'];
$dsn="mysql:host=someserver.net;dbname=thisdb;charset=utf8";
$db=new PDO($dsn,'thisdb','password');
$insertSQL="insert into submission (content) values (?)";
$stmt=$db->prepare($insertSQL);
$stmt->execute(array($content));
}
else
{
echo "FAIL!";
}
?>
load.php
<?php
try
{
$dsn="mysql:host=someserver.net;dbname=thisdb;charset=utf8";
$db=new PDO($dsn,'thisdb','password');
$PDOsql="select * from submission order by id desc";
$stmt=$db->query($PDOsql);
foreach($stmt->fetchAll(PDO::FETCH_ASSOC) as $resultRow)
{
printf("%s<br>",$resultRow["ID"]);
printf("%s<br>",htmlspecialchars($resultRow["content"]));
$stmt->closeCursor();
}
}
catch(PDOException $ex)
{
echo "an error occurred! ".$ex->getMessage();
}
?>
The issue with it taking so long to return the Ajax response is probably that the table submissions has grown. Rather than each second loading all the submissions, append only new submissions to the div. I.e. keep track of the last id received and use this in the query so the where clause is limited.
Moreover, the div flickers back and forth between its existing contents and the new data set with the added values, as if it were alternating between the realtime results of load.php and a previous call to the same script.
Ajax response can be cached by the browser just like anything else. To prevent that, you can:
Put no-cache headers in the page that processes the request to prevent browser caching of the Ajax responses. IE is particularly stubborn and will require the most forceful headers.
Add a parameter to your Ajax request that is a random number, to make every request unique.
Tell JQuery to prevent caching (it just does #2 for you). Use $.ajaxSetup ({ cache: false }); or add the cache: false, attribute to each call to $.ajax

Categories