I want some this type of coding for my user where if width is less than 1000 than I will show mobile design otherwise shows desktop design but cannot run HTML and PHP inside a Javascript if else loop
<script type="text/javascript">
if ($(window).width() > 1000) {
<html>
<head></head>
<body>
<?php echo $a ; ?>
</body>
</html>
} else {
<html>
<head></head>
<body>
<?php echo $b ; ?>
</body>
</html>
}
</script>
You need to use media queries if you want to apply some css that depends on browser size.
Your script won't work because you mix client and server side code if you still want to use javascript then check code below
if (window.innerWidth > 500) {
alert('above 500');
} else {
alert('below or equal to 500');
}
Some links you may want to read:
https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries
http://getbootstrap.com/2.3.2/scaffolding.html
Notice: if you want execute PHP code that depends on browser width you need to do AJAX call.
Related
This might go very basic, but I am not able to understand what is the best way to call AJAX on a button click event on page and get the data from the server to be displayed using php.
What I have is a simple webpage called div.php:
<html>
<head>
<title>
Test
</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js">
$(document).ready(function(){
$('#btn').click(function(){
$("#data").html('Loading...');
$.ajax({
url:'test.php',
type:'GET',
success:function(data){
$("#data").html(data);
}
});
});
});
</script>
</head>
<body>
<form method="get">
<button id="btn">
Get Data from PHP file
</button>
<div id="data">
</div>
</form>
</body>
</html>
And then a page behind it doing the database operation, test.php:
<?php
include ("config.php");
$sql = "SELECT * FROM userInfo;";
$result = mysql_query($sql);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$count = mysql_num_rows($result);
if ($count > 0) {
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo $row["userLogin"] . "<br>";
}
}
?>
It is pretty basic and I am supposed to get the query result on the button click, but it doesn't work. Is there something wrong in here?
Any help or ideas to understand PHP to AJAX to JS flow will be really appreciated.
You need to embed the JS separately, you can't do what you've done but need to split as below.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#btn').click(function(){
... etc
});
});
</script>
This is difficult to debug based on the limited info available, although I think this may be the issue. Your <button> element is inside a <form> element. This means that when you click the button, it is submitting the form and reloading the page. Your AJAX may have worked but the page has reloaded so you won't see the data. Solution:
Either remove your <form> from the page or look into e.preventDefault() for the button click function in jquery.
On another note, you should migrate your code to using another library such as PDO for accessing databases as the mysql_* functions should no longer be used.
I have a for loop in PHP and an Ajax call in JavaScript with Jquery library. My problem is that i want to update the page after each php loop. Now its waiting 10 seconds and after that, shows me the page. I want to display in real time line after line.
data.php
<?php
for($i=0;$i<10;$i++) {
echo "lorem ipsum" . "<br>";
sleep(1);
}
?>
And the index.php
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function ajaxCall(){
$.ajax({url:"data.php",success:function(result){
$("#div1").html(result);
}});
}
setTimeout(ajaxCall(), 1000);
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>
You essentially want to perform 10 page updates, each after one second based on each iteration of your loop on the server side php code. I suggest you redesign so that the looping occurs on the client side, and on the server side you simply respond to each request. I think this approach is easy to understand.
The below client side code is not tested and shows the approach (index.php)
//this is called 10 times, with i being the number of the call starting at 1
function ajaxCall(i){
//note the query string parameter being passed to the php script
$.ajax({url:"data.php?i="+i,success:function(result){
$("#div1").html(result);
if(i<10){ //if we have not reached 10 calls, delay and then call again while incrementing the count
setTimeout(ajaxCall(i+1), 1000);
}
}
});
//make the first ajax call
setTimeout(ajaxCall(1), 1000);
In data.php you need to check that query string parameter. Note there is no loop and no sleeping in your server side code any more.
<?php
$i = $_GET["i"];
//do something with $i which should be in the range 1-10 (you should check this)
echo "lorem ipsum " . $i . "<br>";
?>
In your data.php, there is no need for sleep and for loop. The loop will be done in Javascript (with setTimeout).
So data.php can look something like:
<?php
echo "lorem ipsum" . "<br>";
?>
And your index.php should append the data:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function ajaxCall(){
$.ajax({url:"data.php",success:function(result){
$("#div1").append(result);
}});
}
setTimeout(ajaxCall, 1000);
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>
i tried to do like this. i think its worthless
here my code..
<?php
$screen = '<script type="text/javascript">document.write(screen.width);</script>';
$echo $screen;
?>
this javascript code is work without php code..
<script type="text/javascript">
document.write(screen.width);
</script>
but i want to get only width from variable
i tried to like this get screen size from php.. but its not work.. someone can help me for do this one.. i want to variable for screen width.. if have another good method plz give me answer for this one.. thanks.
As mentioned in one of the comment, you need to differentiate client and server.
Though to make things simple, if you want to get screen width on server side, you can do the following :
Index.php
<?php
session_start();
if(!isset($_GET['width']) && !isset($_SESSION['screen.width'])){
?>
<html>
<head>
<script type="text/javascript">
location.replace('http://example.com/?width='+screen.width);
</script>
</head>
<body></body>
</html>
<?php
die();
}
if(isset($_GET['width'])){
$_SESSION['screen.width'] = (int) $_GET['width'];
}
echo "screen width : ".$_SESSION['screen.width'];
?>
I'm a college business student trying to build a website with a business model.
I'm building a website where I want to allow users to signup. Right now I'm using action: signup.php to store the user into the database. After the user is successfully inserted, I redirect the page back to the index.html where the form was submitted.
My question is, how can I reference JavaScript to change the login from display:block to display:none and sign up confirmation from display:none to display:block through my PHP tag?
I'm currently using $_GET to grab the success/fail status from signup.php and I want to use an IF statement to execute the correct JavaScript code.
UPDATE
I was advised to instead set all div's to block and use a PHP IF statement to display the login or signedup divs. However, after implementing the changes, the index.html still cannot distinguish the success/fail status. Here is my code below:
signup.php:
if (mysqli_num_rows($data) == 0)
{
$qry = "INSERT INTO logins (username, password, email) VALUES ('$username', SHA('$password1'), '$email')";
$result=mysqli_query($dbc, $qry);
if($result)
{
header('Location: index.html?signup=success');
}
}
else
{
header('Location: index.html?signup=fail');
}
index.html: Head
<html lang="en">
<head>
<meta charset="utf-8">
<title>My Site</title>
<link type="text/css" rel="stylesheet" href="home.css">
<script type="text/javascript">...</script>
<?php
if(!empty($_GET['signup']))
{
$signup = $_GET['signup'];
}
?>
</head>
index.html: Body
<body>
<div id="container">
<?php
if(!$signup)
{
?>
<div id="login">...</div>
<?php
}
?>
<?PHP
if($signup)
{
?>
<div id="signedup">...</div>
<?PHP
if($signup == 'success')
{
?>
<div id="confirmation">...</div>
<?php
}
?>
<?PHP
if($signup == 'fail')
{
?>
<div id="failure">...</div>
<?php
}
?>
<?php
}
?>
</div>
</body>
As of now, after the user submits the form they are inserted into the database. The problem is that once they are redirected to the index.html, the php does not recognize the success/fail status and consequently only displays the login form.
That PHP code needs to go in your <head> or <body> section. You have it before <html> right now.
And yeah, onload = function(); should probably be window.onload = function;
This code doesn't do what you think it does:
onload=signedup();
You need to attach to the onload handler correctly:
window.onload = signedup;
Now, this isn't the best way to do things (it waits for EVERYTHING to be loaded), so if you happen to have jQuery included in your page, it'll be more efficient:
$(function(){ signedup(); });
Also, move the PHP to inside the HEAD tag since it prints out a script - and scripts should generally be in the HEAD tag.
Now, to take a different direction - why don't you just do it with PHP by printing out the HTML only if it's needed:
<?php if(!$signedup) { ?>
<div id="login"> ... </div>
<?php } ?>
This is probably the way to go in this case!
I have a PHP code:
if($billing_total>$limit_to_send){
echo '<script type="text/javascript">
window.onload = function() {
alert("Sorry, you do not have enough credit");
}
</script>';
When I am printing this message, it is being printed at the beginning of the PHP page as below:
<script type="text/javascript">
window.onload = function() {
alert("Sorry, you do not have enough credit");
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-----------------------------------------------------------
This caused the header (logo) of my page in the browser to move down one line.
and the page will look very bad because all the items there will be moved down one line.
I hope it is clear to you. Please any solution ?
===========================================================================
Thanks for All ...
Solution:
$alert_message=<script type="text/javascript">
window.onload = function() {
alert("Sorry, you do not have enough credit");
}
</script>
Printing $alert_message somewhere in the HTML code before the body tag ^_^
Make sure you never output anything before the DTD (doctype declaration).
See this question for more information...
The doctype declaration must be the first element of your html page, it's from what the browser decides how to handle the rest of the html code. Outputting anything before that will probably put your browser in quirks mode so you can't be sure how the browser will render your page.
How to avoid this?
The echo command gets executed as its line is reached, and it seems that the rest of your html code follows after that.
You could either
move the html DTD and header to the top of your php (but sometimes that is not possible) OR
store the error html in a variable, so instead of echo '<script ... do $errorhtml = '<script ... and output that string, if not empty, at a specific place in the head or body generating code of your php.
If you have no control over the original source, you could consider redirecting to an error page with its own html DTD, header and body which you can design as fits you best.
Either append die() into the if codeblock or have your php print the script somewhere in the body or head.
This shows a bad design of your application. I would suggest you change it to something like:
$errors = array();
if($billing_total>$limit_to_send){
$errors[] = 'Sorry, you do not have enough credit';
}
Then on your HTML file, before the <body> tag closes, read your array and display any errors
<?php if(is_array($errors)): ?>
<script type="text/javascript">
<?php foreach($errors as $error): ?>
alert('<?php echo $error; ?>');
<?php endforeach; ?>
</script>
<?php endif; ?>