Pass value from jQuery into PHP script in ONE file - php

The following is one file index.php GetWidth and GetHeight functions work. (They are not final functions so not important.) The important part is marked by /* IMPORTANT HERE */ What I am trying to accomplish is pass the variable I get using jQuery Window Portal Height / Width and pass it to a PHP script here In other words when I get value from GetWidth() it should go to w=120 or replace 120 value with whatever the width is at the moment and the same with height. If there is any syntax errors please ignore.
I only want to figure out how to pass value from jQuery to PHP scrip. Also in the future I want add on resize method so values will be dynamic when window is resized.
<html>
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(window).resize(function () {
$('#msg').text('Browser (Width : '
+ $(window).width()
+ ' , Height :' + $(window).height() + ' )');
});
$(document).ready(function() {
// DOCUMENT READY
function GetWidth() {
if (self.innerWidth) {
return self.innerWidth;
}
else if (document.documentElement &&
document.documentElement.clientHeight) {
return document.documentElement.clientWidth;
}
else if (document.body) {
return 0;
}
return x;
}
function GetHeight() {
if (self.innerHeight) {
y = self.innerHeight;
}
else if (document.documentElement &&
document.documentElement.clientHeight) {
return
document.documentElement.clientHeight;
}
else if (document.body) {
return 0;
}
return y;
}
// This is for when it first loads.
$('#TEXT').text('W: ' + $(window).width() + ' , H:' + $(window).height() + y);
// This is for when window gets resized.
$(window).resize(function () {
$('#TEXT').text('W: ' + $(window).width() + ' , H:' + $(window).height());
});
// DOCUMENT READY
});
</script>
</head>
<body>
Info Area:<br>
<div id="TEXT"></div>
/* IMPORTANT HERE */
<!-- img src="timthumb.php?src=URL...image.jpg&h=180&w=120" -->
/* IMPORTANT HERE */
</body>
</html>

wellcome to stackoverflow!
the problem is that the php is compiling in server and browser receive a html and javascript file from server
then your browser compiling your javascript and html code
so javascript unable to change phpcode
you can make your html whit javascript like this:
image = new Image();
image.src = "timthumb.php?src=URL...image.jpg&h="+ hgt + "&w=" + wth;
image.onLoad=function(){ $("img").attr({src: image.src}); }

You can not pass the jQuery or JS variables to the PHP script.
Basically the PHP scripts get executed at server level and only HTML, JS and CSS will be returned to the browser. Then browser will render it. So when browser executing your JS method, the PHP scripts are already executed.
you can use Ajax.

You can not pass values from jQuery to PHP becuase PHP is a server-side language and jQuery is a client-side language. But there is a way to pass data from client-side to server-side which is AJAX
https://softwareengineering.stackexchange.com/questions/171203/what-are-the-difference-between-server-side-and-client-side-programming
Why PHP script is not workig in a web browser?
http://www.scriptingok.com/tutorial/Server-side-vs-Client-side

Related

Load page while PHP is executing

What Im trying to do: Display a loading gif or text... at the very least show a black screen before and during the time the php is being executed.
What I have tried.
I have tested using flush () and I get nothing until the entire php process is finished. I dont particularly like this concept either but I'll take anything.
I am considering using two pages to accomplish this though the current project is nearly complete and would take some time to consolidate the scattered html/php code.
Currently I'm doing 3-simpleXML_load_file(), 1-include(), 1-file_get_contents()
I have javascript function plotting data from one of the simpleXML_Load_file()...
Im up for moving parts of the code to a different file but it's a big task. So id like some advise or suggestions on how to proceed.
If I need to elaborate more just ask!
Thanks,
JT
<html>
<head>
<?php
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
$weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');
?>
<script type="text/javascript">
<!--Plot function-->
$(function()
{
var d =
[
<?php
//Pulling in hourly data to plot temp vs time
$i=0;
$array=array();
while ($i<=100)
{
echo '['. (strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000) .','.$weather_hourly->data->parameters->temperature->value[$i] .'],';
$value = $weather_hourly->data->parameters->temperature->value[$i];
array_push($array,$value);
$i++;
}
foreach ($array as $key => $value)
{
$value = (string) $value;
$min_sec_array[] = $value;
}
?>
</script>
</head>
<body>
<div id=graph>
</div>
</body
The main way you can accomplish this is by using AJAX and multiple pages. To accomplish this, the first page should not do any of the processing, just put the loading image here. Next, make an AJAX request, and once the request is finished, you can show the results on the page or redirect to a different page.
Example:
File 1 (jQuery must be included also), put this in the body along with the loader animation:
<script language="javascript" type="text/javascript">
$(function(){
var mydata = {};
$.post('/myajaxfile.php', mydata, function(resp){
// process response here or redirect page
}, 'json');
});
</script>
Update: Here is a more complete example based on your code. This has not been tested and needs to have the jQuery library included, but this should give you a good idea:
File 1: file1.html
</head>
<body>
<?php
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
?>
<!-- Include jQuery here! Also have the loading animation here. -->
<script type="text/javascript">
$(function(){
$.get('/file2.php?Lat=<?php echo $lat; ?>&Lon=<?php echo $long; ?>', null, function(resp){
// resp will have the data from file2.php
console.log(resp);
console.log(resp['min_sec_array']);
console.log(resp['main']);
// here is where you will setup the graph
// with the data loaded
<!--Plot function-->
}, 'json');
});
</script>
<div id=graph>
</div>
</body
</html>
File 2: file2.php
I'm not sure if you needed the $min_sec_array, but I had this example return that as well as the main data you were using before.
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
$weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');
//Pulling in hourly data to plot temp vs time
$i=0;
$main = array();
$array=array();
while ($i<=100)
{
$main[] = array((strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000), $weather_hourly->data->parameters->temperature->value[$i]);
$value = $weather_hourly->data->parameters->temperature->value[$i];
array_push($array,$value);
$i++;
}
foreach ($array as $key => $value)
{
$min_sec_array[] = (string) $value;
}
echo json_encode(array(
'min_sec_array' =>$min_sec_array,
'main' => $main
));
exit();
?>
I would recommend not to do this with plain html and php if u expect it modify the page after it is loaded. Because php is server side processing, so it is executed before the page is send to the user. U need Javascript. Using Javascript will enable u to dynamically add or remove html elements to or from the DOM tree after the page was send to the user. It is executed by the users browser.
For easier start I would recommend jQuery, because there are lots of tutorials on such topics.
JQuery
JQuery learning center
A small example:
HTML
<head>
<meta charset="utf-8" />
<title> </title>
<script type="text/javascript" src="js/lib/jquery-1.9.1.js"></script>
</head>
<body>
<h1>Addition</h1>
<div id="error_msg"> </div>
<div id="content">
<!-- show loading image when opening the page -->
<img src="images/loading.gif"/>
</div>
<script type="text/javascript">
// your script to load content from php goes here
</script>
</body>
this will be nothing more then the following until now:
adding the following php file
<?php
$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
$result = $num1 + $num2;
echo '<p>Calculating '.$num1.' + '.$num2.' took a lot of time, but finally we were able to evaluate it to '.$result.'.</p>'
.'<p> '.$num1.' + '.$num2.' = '.$result.'</p>';
?>
wont change anything of the html, but adding javascript/ Jquery inside the HTML will be kind of connection between static html and server side php.
$(document).ready(function(){
$.ajax({ // call php script
url: 'php/script.php?num1=258&num2=121',
type:'GET',
timeout: 500,
contentType: 'html'
}).success(function(data){
// remove loading image and add content received from php
$('div#content').html(data);
}).error(function(jqXHR, textStatus, errorThrown){
// in case something went wrong, show error
$('div#error_msg').append('Sorry, something went wrong: ' + textStatus + ' (' + errorThrown + ')');
});
});
This will change your page to show the loading animation until the php script returns its data, like:
So you can setup the whole page in plain html, add some loading gifs, call several php scripts and change the content without reloading the page itself.
It is kind of nasty solution to your problem...
But this can work:
You work with those -
ob_start();
//printing done here...
ob_end_flush();
at the beginning you will create your rotating ajax gif...
Then you do all the processing and calculating you want...
At the end of the processing, just echo a small script that does a hide to your gif...
Depends on the exact need, maybe ajax can be more elegant solution.
In response to your conversation with David Constantine below, did you try using ob_flush()?
ob_start();
echo '<img src="pics/loading.gif">';
ob_flush();
// Do your processing here
ob_end_flush();
I think you don't have a problem with flushing your PHP output to the browser, but more likely with getting the browser to start rendering the partial html output. Unfortunately, browser behavior on partial html is browser-specific, so if you want something to work the same in any browser, the AJAX solution suggested in other answers is the better way to go.
But if you don't like that added complexity of a full AJAX solution, you can try to make your html output "nice" in the sense of providing some body output that can be formatted without needing the rest of the html output. This is were your sample code fails: It spends most of its time outputting data into a script tag inside the html header. The browser never even sees the start of the body until your PHP code has practically finished executing. If you first write your complete body, then add the script tag for the data there, you give the browser something to at least try to render whilst waiting for the final script to be completed.
I've found the same issue (albeit not in PHP) discussed here: Stack Overflow question "When do browsers start to render partially transmitted HTML?" In particular, the accepted answer there provides a fairly minimal non-AJAX example to display and hide a placeholder whilst the html file hasn't completely loaded yet.
I know this is an old question, but the answer provided in this page by rpnew is extremely clear and easy to adjust to your project's requirements.
It is a combination of AJAX and PHP.
The HTML page PHPAjax.html which calls the PHP script:
<html>
<head>
<script type="text/javascript">
document.write('<div id="loading">Loading...</div>');
//Ajax Function
function getHTTPObject()
{
var xmlhttp;
if (window.ActiveXObject)
{
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E)
{
xmlhttp = false;
}
}
}
else
{
xmlhttp = false;
}
if (window.XMLHttpRequest)
{
try
{
xmlhttp = new XMLHttpRequest();
}
catch (e)
{
xmlhttp = false;
}
}
return xmlhttp;
}
//HTTP Objects..
var http = getHTTPObject();
//Function which we are calling...
function AjaxFunction()
{
url='PHPScript.php';
http.open("GET",url, true);
http.onreadystatechange = function()
{
if (http.readyState == 4)
{
//Change the text when result comes.....
document.getElementById("content").innerHTML="http. responseText";
}
}
http.send(null);
}
</script>
</head>
<body onload="AjaxFunction()">
</body>
</html>
The Background PHP Script PHPScript.php:
<?php
sleep(10);
echo "I'm from PHP Script";
?>
Save both files in the same directory. From your browser open the HTML file. It will show 'Loading...' for 10 seconds and then you will see the message changing to "I'm from PHP Script".

Converting jquery function from form submit to php array result

I'm attempting to take the ImageResolver plugin and adapt it to work with a php array.
Stripping the code to this returns the image without a form:
$(function(){
var url = $('#url').val();
ImageResolver.resolve(url, function(image){
if (image) {
$('#result').html('<img src="' + image + '" alt="">');
} else {
$('#result').html('<h2>No image found</h2>');
}
});
});
I want to adapt it to work within a php foreach loop. results would be replaced on the next class='result' div. IE: after the page has loaded the urls from the query, the function will parse the url and return image link if one is found. I'm guessing I need to use (each) or this(), but I can't figure it out.
can someone point me in the right direction?
<script src="ImageResolver/URI.min.js"></script>
<script src="ImageResolver/ImageResolver.js"></script>
<?
$javascriptarray = 'var urls = [';
$counter=0;
foreach (array('http://www.apple.com/','http://github.com/','http://www.test.com/') as $url)
{
if ($counter++ > 0) $javascriptarray .= ',';
$javascriptarray .= '"'.$url.'"';
}
$javascriptarray .= '];';
?>
<script>
<?=$javascriptarray?>
//The ImageResolver will try all the resolvers one after the other
//in the order of their registration
//Resolvers that guess the image URL
ImageResolver.register(new FileExtensionResolver());
ImageResolver.register(new ImgurPageResolver());
ImageResolver.register(new NineGagResolver());
ImageResolver.register(new InstagramResolver());
//Resolvers that need extra ajax requests
ImageResolver.register(new ImgurAlbumResolver());
ImageResolver.register(new OpengraphResolver());
ImageResolver.register(new WebpageResolver());
//Some jQuery code to make the demo work
//Use a crossdomain proxy (required by some plugins)
$.ajaxPrefilter('text', function(options) {
options.url = "http://furious-stream-4406.herokuapp.com?src=" + encodeURIComponent(options.url);
});
$(function(){
var length = urls.length,
url = null;
for (var i = 0; i < length; i++) {
url = urls[i];
ImageResolver.resolve(url, function(image){
if (image) {
$('#result').append('<img src="' + image + '" alt=""><br>');
} else {
$('#result').append('<h2>No image</h2>');
//$('#result').append('<h2>No image found for ' + url + '</h2>');
}
});
}
});
</script>
Watch out cause ImageResolver.resolve() works asynchrone you can get unexpected results. Call ImageResolver.resolve() again before the previous call has finished will change url in $('#result').append('<h2>No image found for ' + url + '</h2>'); to the url of your last call by example. To prevent this you need to initialize a new Resolver in the for-loop. see: Javascript prototypes and instance creation

Jquery replaceWith:replace one php file with another php file based on screen resolution

I need to be able to replace a php file with another php file based on screen resolution. This is what I have so far:
<script type="text/javascript">
function adjustStyle(width) {
width = parseInt(width);
if (width = 1920) {
$('book.php').replaceWith('book2.php');
}
}
$(function() {
adjustStyle($(this).width());
$(window).resize(function() {
adjustStyle($(this).width());
});
});
</script>
which obviously isn't working-- any ideas? Thank you in advance for any help received.
UPDATE
Is this at all close (to replace the book.php line)?
{ $("a[href*='book.php']").replaceWith('href', 'book2.php'); };
Second Update to reflect input gathered here
function adjustStyle(width) {
width = parseInt(width);
if (width == 1920) {
$('#bookinfo').replaceWith(['book2.php']);
$.ajax({
url: "book2.php",
}).success(function ( data ) {
$('#bookinfo').replaceWith(data);
});
$(function() {
adjustStyle($(this).width());
$(window).resize(function() {
adjustStyle($(this).width());
});
});
}
}
I have not seen the use of replaceWith in the context you put it in. Interpreting that you want to exchange the content, you may want to do so my using the load() function of jQuery.
if(width == 1920){
$("#myDiv").load("book1.php");
} else {
$("#myDiv").load("book2.php");
}
Clicking on the button replaces the content of the div to book2.php.
The first problem is I don't think that you are using the correct selectors. If you have the following container:
<div id="bookContainer">Contents of book1.php</div>
The code to replace the contents of that container should be
$('#bookContainer').replaceWith([contents of book2.php]);
In order to get [contents of book2.php] you will need to pull it in by ajax using the following code I have also included the line above so that the data from book2.php will be placed into the container:
$.ajax({
url: "http://yoururl.com/book2.php",
}).success(function ( data ) {
$('#bookContainer').replaceWith(data);
});.
I haven't tested this so there might be an issue but this is the concept you need to accomplish this.
First off... using a conditional with a single = (equal sign) will cause the condition to always be true while setting the value of variable your checking to the value your checking against.
Your condition should look like the following...
if (width == 1920) { // do something }
Second, please refer to the jQuery documentation for how to replace the entire tag with a jquery object using replaceWith()... http://api.jquery.com/replaceWith/
I would use a shorthand POST with http://api.jquery.com/jQuery.post/ since you don't have the object loaded yet...
In short, my code would look like the following using $.post instead of $.ajax assuming I had a tag with the id of "book" that originally has the contents of book.php and I wanted to replace it with the contents of book2.php...
HTML
<div id="book">*Contents of book.php*</div>
jQuery
function onResize(width) {
if (parseInt(width) >= 1920) {
$.post('book2.php',function(html){
$('#book').html(html).width(width);
});
}
else {
$.post('book.php',function(html){
$('#book').html(html).width(width);
});
}
}
Hope this helps.

how to load a diferrent php file dynamically based on the browser window's width using jQuery or any other method

Hello friends a very novice question as I am very new to programming.
I was browsing the web and found a method to dynamically load a CSS file based on the browser width.
jQuery
function adjustStyle(width) {
width = parseInt(width);
if (width < 701) {
$("#size-stylesheet").attr("href", "css/narrow.css");
} else if ((width >= 701) && (width < 900)) {
$("#size-stylesheet").attr("href", "css/medium.css");
} else {
$("#size-stylesheet").attr("href", "css/wide.css");
}
}
$(function() {
adjustStyle($(this).width());
$(window).resize(function() {
adjustStyle($(this).width());
});
});
HTML
<link rel="stylesheet" type="text/css" href="main.css" />
<link id="size-stylesheet" rel="stylesheet" type="text/css" href="narrow.css" />
I want to know, can I use the same to load a php file?
If yes what will be the code look like?
I think we will be required to use something like <?php require_once('http://mysite.com/layouts/ipad.php'); ?> but how do I code it?
Kindly help.
Regards
I want to know, can I use the same to load a php file?
If by "load a php file" you mean load a different page where you'll define different pages for different conditions (widths, whatever), then you can load different pages by setting window.location equal to the desired page. This will replace the current page with the one you specify.
I don't think you should do this every time the window is resized though. If you must do it at least check whether the new size actually requires a change rather than repeatedly reloading it regardless.
Following is similar to your existing code:
function setLocation(url) {
if (window.location.href.indexOf(url) === -1)
window.location = url;
}
function reloadPage(width) {
width = parseInt(width);
if (width < 701) {
setLocation("yournarrowpage.php");
} else if (width < 900) {
setLocation("yourmediumpage.php");
} else {
setLocation("yourwidepage.php");
}
}
$(function() {
reloadPage($(this).width());
$(window).resize(function() {
reloadPage($(this).width());
});
});
You don't have to reload the entire page each time though, you can reload just certain sections using ajax. For that you could do something similar to the above except instead of setting window.location you'd use jQuery's .load() method:
function setLocation(url) {
$("selector for the element to reload").load(url);
}
I suspect what you're actually wanting to do is redirect the user to a different page based on browser or resolution.
$(document).load(function() {
var $width = $(window).width()
if($width < 701)
window.location = 'narrow.php'
else if($width < 900)
window.location = 'medium.php'
else
window.location = 'wide.php'
})
You could easily make the same function run on window resize, although it may not work as well as you hope in practice.
Edit: If you're just doing this for iPads specifically (which you shouldn't):
if(stristr($_SERVER['HTTP_USER_AGENT'], 'Mozilla/5.0(iPad;')) {
// probably an iPad
require('ipad.php');
//Or maybe the below might serve you better:
/*
header('Location:ipad.php');
die();
*/
}
This is a good starting place for the css question: http://topsecretproject.finitestatemachine.com/2009/09/how-to-load-javascript-and-css-dynamically-with-jquery/
And for loading php, see Including a php file dynamically with javascript and jquery
if (width < 701) {
$.get('yourlayoutfor701.php', function(data) {
$('#your_layout').html(data);
});
}
hope this might help you, but not a good practice

What comparable Javascript function can reference a file like PHP's include()?

What is the best way to reference or include a file using Javascript, looking for the closest functionality of PHP's include() ability.
I would check out Javascript equivalent for PHP's include:
This article is part of the 'Porting
PHP to Javascript' Project, which aims
to decrease the gap between developing
for PHP & Javascript.
There is no direct equivalent - you can either go with the function I linked above or use document.write to write out a new script tag with a src pointing to the file you wish to include.
Edit: Here is a rudimentary example of what I mean:
function include(path) {
document.write(
"<script type=\"text/javascript\" src=\"" + path + "\"></script>"
);
}
Edit 2: Ugh, what an ugly example - here is a better one:
function include(path) {
script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", path);
if (head = document.getElementsByTagName("head")[0]) {
head.appendChild(script);
}
}
document.write is a hackish way of doing things and I shouldn't have recommended it. If you go with one of my examples please use the second one.
I have a script that I wrote a while back (using Mootools) that allows for one to include javascript files on the fly (with a callback function after its loaded). You can modify it to work the library of your choice if you choose.
Note the gvi prefix is just my namespace and that gvi.scripts is an array containing all the javascript files currently included on the page, those can be removed if you want. Also, the filename function can be removed, that was just added to make my life easier [require('some-script') vs require('js/some-script.js')].
//if dom isn't loaded, add the function to the domready queue, otherwise call it immediately
gvi.smartcall = function(fn) {
return (Browser.loaded) ? fn() : window.addEvent('domready', fn);
}
//For dynamic javascript loading
gvi.require = function(files, callback, fullpath) {
callback = callback || $empty;
fullpath = fullpath || false;
var filename = function(file) {
if (fullpath == true) return file;
file = ( file.match( /^js\/./ ) ) ? file : "js/"+file;
return ( file.match( /\.js$/ ) ? file : file+".js" );
}
var exists = function(src) {
return gvi.scripts.contains(src);
}
if ($type(files) == "string") {
var src = filename(files);
if (exists(src)) {
gvi.smartcall(callback);
} else {
new Asset.javascript( src, {
'onload' : function() {
gvi.scripts.push(src);
gvi.smartcall(callback);
}
});
}
} else {
var total = files.length, loaded = 0;
files.each(function(file) {
var src = filename(file);
if (exists(src) && loaded == total) {
gvi.smartcall(callback);
} else if (exists(src)) {
loaded++;
} else {
new Asset.javascript( src, {
'onload' : function() {
gvi.scripts.push(src);
loaded++;
if (loaded == total) gvi.smartcall(callback);
}
});
}
});
}
}
And you call it like
gvi.require('my-file', function() {
doStuff();
});
//or
gvi.require(['file1', 'file2'], function() {
doStuff();
});
jQuery has a plugin for this: http://plugins.jquery.com/project/include
Instead of using javascript and making our work more complex, we have pretty easy way to include external file using the IFRAME tag in HTML.
**
<iframe src="....../path/filename.html" width="" height="">
**
We can also control iframe using CSS if even more customization required .

Categories