PHP in JavaScript using document.write(); - javascript

I have quite a script that adds items into a table. I need to pull information from a MySQL database based on the UPC that is passed through the JavaScript.
I tried: document.write("<?php echo '375'; ?>"); just to see if it would work, and once the script got to that line, the page refreshed and displayed a blank white page.
The full JavaScript is below:
//setup before functions
var field = document.getElementById("UPC");
var typingTimer; //timer identifier
var doneTypingInterval = 1000; //time in ms, 1 seconds
//on keyup, start the countdown
$('#UPC').keyup(function(){
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
//on keydown, clear the countdown
$('#UPC').keydown(function(){
clearTimeout(typingTimer);
});
function doneTyping () {
//user is "finished typing," do something
if (field.value.length != 0) {
document.getElementById("noScan").className="hidden";
document.getElementById("checkout").className="";
document.getElementById("void").className="";
var upc=document.getElementById("UPC").value;
var price = document.write("<?php echo '375'; ?>");
var weight = parseInt(document.getElementById("weight").value);
var table=document.getElementById("ScannedItems");
var total = weight * price;
var row=table.insertRow(-1);
var cell1=row.insertCell(0);
var cell2=row.insertCell(1);
var cell3=row.insertCell(2);
var cell4=row.insertCell(3);
var cell5=row.insertCell(4);
var cell6=row.insertCell(5);
cell1.innerHTML=upc;
cell2.innerHTML="Example Description";
cell3.innerHTML = "$" + price.toFixed(2);
cell4.innerHTML = weight + " lbs";
cell5.innerHTML = "$" + total.toFixed(2);
cell5.setAttribute('data-total', total); // caches the total into data
cell6.innerHTML="<a class='add'><span class='glyphicon glyphicon-plus' style='padding-right:15px;'></span></a><a class='delete'><span class='glyphicon glyphicon-minus'></span></a>";
field.value ='';
var total = cell5.getAttribute('data-total');
var salesTax = Math.round(((total / 100) * 8.25)*100)/100;
var totalAmount = (total*1) + (salesTax * 1);
document.getElementById('displaysubtotal').innerHTML="$" + (Math.floor(total * 100) / 100).toFixed(2);
document.getElementById('displaytax').innerHTML="$" + salesTax;
document.getElementById('displaytotal').innerHTML="$" + totalAmount;
}
}
// Duplicate a scanned item
var $table = $('#ScannedItems');
$('#ScannedItems').on('click', '.add', function () {
var $tr = $(this).closest('tr').clone();
$table.append($tr);
});
// Remove a line item
var $table = $('#ScannedItems');
$('#ScannedItems').on('click', '.delete', function () {
var $tr = $(this).closest('tr').remove();
});
I must figure out how to get information from my database for this project or it is going to fail.

Javascript executes on the client side, PHP executes on the server side. So PHP is done executing before JS starts.
So in order to fetch new data, you'll need to initiate a call to your server. You can do this by either refreshing the page with the results you need or by creating an AJAX call.
To make it more clear, take a closer look at the example you gave. View the source code in your browser. It will come out as document.write("375");. That's because PHP echo'ed the string '375' into your JS code on the server side before sending the page to the browser (which is where the JS code executes).
PHP can generate JS code, but JS cannot generate PHP code (in the usual sense).

PHP is executed on the server before serving generate HTML to a clients browser. Any PHP code inserted by the javascript on the client will not run.
If you want to have code inserted dynamically from PHP, you might investigate how to use AJAX calls to run a separate PHP server-side script and insert the returned content.

You can perfectly use php inside javascript, because php executes before javascript reachs the browser. So the browser receives the page with the php result executed which builds the javascript sentence... the browser doesnt know that the javascript sentence was writen by you or by the php server.
document.write("<?php echo '375'; ?>");
try changing it to...
document.write("<?php echo("375"); ?>");
the "" are first seen by php server so the above should work.
or just in case you can escape the "
I also have this piece of code fully functional:
frameDoc.document.write sentence
<?php
echo("frameDoc.document.write(\"");
require('secciones/seccion_head2.html');
echo("\");");
?>
frameDoc.document.write sentence
BUT!!! inside the required html you cant use more than one line!!!!

Related

Why doesn't the 'infinite scroll' stop loading content?

I am using an 'infinite scroll' script that keeps sending requests to the database even when there are no more records. When that happens, it reloads the last set on the page. I would like for the function to stop running when it reaches the last record on the database. I'm new to JS so this is a bit difficult for me to troubleshoot, also, I'm not using jQuery. I am doing most of the work in the PHP script.
I've been reading a lot of posts in here about 'infinite scroll' and I am unable to get how other people check the limits in JS.
JavaScript
function loadPosts(){
var target = document.getElementById('PostsContainer');
var contentHeight = target.offsetHeight;
var yOffset = window.pageYOffset;
var y = yOffset + window.innerHeight;
if(y >= contentHeight){
var xhr = ajaxObj("POST", "loadContent.php");
xhr.onload = function(){
target.innerHTML += xhr.responseText;
}
xhr.send("action=loadMore");
}
}
window.onscroll = loadPosts;
PHP
$sql = "SELECT * FROM posts WHERE post_type = 'a' ORDER BY post_date DESC LIMIT 2" //Original content on page
$totalPosts = 12; (query to DB)
$max = 1;
$current = 2; //Start on record after initial content
while($current < $totalPosts){
$sql = "SELECT * FROM posts WHERE post_type = 'a' ORDER BY post_date DESC
LIMIT $current, $max";
$result = $db_link->query($sql);
$posts_list += ... //Collect the data from DB
$current++;
}
echo $posts_list;
No matter how many times I keep scrolling the new content keeps loading even after I run out of records in the DB. Output keeps repeating every single time I get to the bottom of the page. In this case I have 7 posts in the DB I start with 7, 6... then I keep getting posts 5-1.
So in this case what you can do,
just add one parameter in json, from php or server side which will tell, is data present or not, based on that, you can stop calling loadPosts function
so basically Algorithm be like,
...php
while($current < $totalPosts){
......................
......................
if($current >= $totalPosts)
{
$getNext = False;
}
else
{
$getNext = True;
}
}
...javasrcipt
function loadPosts(){
if(!getNext)
return false;
else
{
......................
......................
}
}
window.onscroll = loadPosts;
Hope this strategy will help you

jQuery.post() data returns entire PHP script as string?

I've already set up a basic SimpleCart.js web shop and am trying to implement realseanp's solution for adding a promo/discount code feature.
He uses the following JavaScript to post the user's entered promo code to discount.php:
jQuery("#promoSub").click(function Discount() {
//Interact with PHP file and check for valid Promo Code
jQuery.post("discount.php", { code: jQuery('#code').val() } , function(data) {
console.log(jQuery('#code').val());
if (data=="0" || data=='') {
console.log("Wrong Code");
}
else {
//create our cookie function if promo code is valid
//create cookie for 1 day
createCookie("promo","true",1);
var y = (data/100);
for(var i=0; i<simpleCart.items().length; i++){
var itemPrice = simpleCart.items()[i].price();
var theDiscount = itemPrice * y;
var newPrice = itemPrice - theDiscount;
simpleCart.items()[i].set("price", newPrice)
}
simpleCart.update();
//hides the promo box so people cannot add the same promo over and over
jQuery('#promoCodeDiv').hide();
}
});
});
...which echoes back a 0 or the discount percentage if the correct code has been passed:
<?php
$x = 0;
if ($_POST["code"]=="HOLIDAY") { $x = 5; };
echo $x;
?>
However, when I console.log(data) from within the success function, data appears to be the entirety of the PHP script as a string instead of the echo.
Why is this, and what modifications do I need to make to rectify it? I'm very new to PHP and having difficulty understanding why jQuery.post() isn't receiving the echo.

Sending multiple GET variables in URL with Javascript

I'm trying to retrieve multiple $_GET variables within PHP. Javascript is sending the URL and it seems to have an issue with the '&' between variables.
One variable works:
//JAVASCRIPT
var price = "http://<site>/realtime/bittrex-realtime.php?symbol=LTC";
//THE PHP END
$coinSymbol = $_GET['symbol'];
echo $coinSymbol
OUTPUT: LTC
With two variables:
//JAVASCRIPT
var price = "http://<site>/realtime/bittrex-realtime.php?type=price&symbol=LTC";
//THE PHP END
$coinSymbol = $_GET['symbol'];
$type = $_GET['type'];
echo $coinSymbol
echo $type
OUTPUT: price
It just seems to ignore everything after the '&'. I know that the PHP end works fine because if I manually type the address into the browser, it prints both variables.
http://<site>/realtime/bittrex-realtime.php?type=price&symbol=LTC
OUTPUT ON THE PAGE
priceLTC
Any ideas? It's driving me nuts - Thanks
UPDATE - JAVASCRIPT CODE
jQuery(document).ready(function() {
refresh();
jQuery('#bittrex-price').load(price);
});
function refresh() {
setTimeout( function() {
//document.write(mintpalUrl);
jQuery('#bittrex-price').fadeOut('slow').load(price).fadeIn('slow');
refresh();
}, 30000);
}
Separate the url and the data that you will be sending
var price = "http://<site>/realtime/bittrex-realtime.php";
function refresh() {
var params = {type:'price', symbol: 'LTC'};
setTimeout( function() {
//document.write(mintpalUrl);
jQuery('#bittrex-price').fadeOut('slow').load(price, params).fadeIn('slow');
refresh();
}, 30000);
}
And in your PHP use $_POST or you can do it like this
$coinSymbol = isset($_POST['symbol']) ? $_POST['symbol'] : $_GET['symbol'];
Refer to here for more information jquery .load()

How to send variable from javascript to PHP on azure websites?

To simplify the problem, all I want is passing 3 variable from javascript to PHP. So let say I have 4 varible : a,b,c,message.
I have tried the following ways:
1)The code below is in my javascript file
window.location.href="somewebsite.php?x=" + a + "&y=" + b + "&z=" + c + "&msg=" + message;
I saw that it actually passing the values to URL, it jump to the PHP website that specifies in the code above but somehow nothing is getting from $_POST['x'] ( I even try $_GET['x'] and $_REQUEST('x') but none of them works at all)
2) Then I tried with ajax
$.post("somewebsite.php",{x:a, y:b, z:c, msg:message})
And same as above nothing are passed to the PHP website.
3) I tried with form submit
I put everything into a form and submit it to the PHP website but what I get from $_POST is an empty array.
So I conclude that something is wrong with azurewebsites server. This is the first time I used window azure so I don't know how it even works. Any suggestion would be appreciated.
you can try out ajax function
$.ajax({
url:"url",
method:"post",
data:{x:a, y:b, z:c, msg:message},
success:function(data)
{
// success code
},
error:function(error)
{
// error code ;
}
});
Should work:
Your js file:
$(document).ready(function(){
var aval = "testas";
var bval = "testas2";
var cval = "testas3";
var msg = "testas4";
$.post('test.php',{a:aval,b:bval,c:cval,message:msg},function(resp){
alert(resp);
});
});
php file should look like:
<?php
$resp = "";
foreach($_POST as $key => $val){
$resp .= $key.":".$val." \n";
}
echo $resp;
?>
After post alert should give response of all sent post values.
I hope it helped you. If yes, don't forget resp. Thanks.
Try sending an array to your somewebsite.php write this inside a function on jquery code.
It must work if you place it on a good place on your code.
var x=new Array();
x[0]='field0';
x[1]='field1';
x[2]='fieldN';
$.post('somewebsite.php',x,function(x){
alert(x);
});
Your somewebsite.php could be like this.
<?php
if(!isset($_POST['x']))$x=array();else $x=#$_POST['x'];
for($i=0;$i<count($x);$i++)
echo "X ($i) = ".$x[$i];
?>
Happy codings!

How to use file_get_contents and json_decode in Javascript

I am trying to use this PHP API in Javascript. How can I use file_get_contents and json_decode in Javascript?
PHP API Code
$content=#file_get_contents("http://doma.in/api/?url=http://www.google.com&api=APIKEY");
$url=json_decode($content,TRUE);//Decodes json into an array
if(!$url["error"]){ // If there is no error
echo $url["short"]; //Outputs the short url
}else{
echo $url["msg"]; //Outputs the error message
}
Javascript
(function( $ ) {
$(document).ready(function() {
var url = window.location.href;
var host = window.location.hostname;
var title = $('title').text();
title = escape(title);
var twitter = 'http://twitter.com/home?status='+title+'%20'+url;
var facebook = 'http://www.facebook.com/sharer.php?u='+url;
var tbar = '<div id="sicons">';
tbar += 'Twitter';
tbar += 'Facebook';
tbar += '</div>';
});
})(jQuery);
Edit: Thanks to the replies
data.php
$content = #file_get_contents('http://doma.in/api.php?api=asd4sdf5634d&url=' . urlencode('http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']));
echo $content;
I have added this to the Top of the Javascript
$.getJSON('data.php', function(data) {
if(!data.error){ // If there is no error
alert(data.short) //Outputs the short url
}else{
alert(data.msg)
}
});
The Javascript is now looking like this
(function( $ ) {
$(document).ready(function() {
var shorturl = data.short;
var title = $('title').text();
title = escape(title);
var twitter = 'http://twitter.com/home?status='+title+'%20'+url;
var facebook = 'http://www.facebook.com/sharer.php?u='+url;
var tbar = '<div id="sicons">';
tbar += 'Twitter';
tbar += 'Facebook';
tbar += '</div>';
});
})(jQuery);
I am sure I am doing something wrong. Sorry but I am beginner in Coding (C, C++)
Loading data via AJAX is asynchronous. Your first call ($.getJSON) is executed as soon as the page is loaded, but the callback function that you pass as a parameter, is executed only as soon as the underlying HTTP request is finished. This means that your program does not block to wait for the HTTP request; after calling $.getJSON(...) your program runs on, and the callback method is called at some time when the HTTP request finished.
You evaluate your data (in your second function) as soon as the page is loaded. But, since your data is loaded asynchronously, it is not yet loaded when the document is rendered and your function is executed.
The solution for your problem would be to move the code that evaluates your data into the callback function of $.getJSON(...):
$.getJSON('data.php', function(data) {
if (!data.error) {
// Process your data here!
} else {
alert(data.msg)
}
});

Categories

Resources