Passing js variable into php string - php

I need a little bit of help im trying to page a js variable into a url thats being parsed in php using file_get_contents. Im not sure where to start to do that.
<script type="text/javascript">
var js_variable = appl+goog+fb+mfst+nflx;
</script>
<?php
$ticker = js_varable_here;
$file = file_get_contents('http://finance.yahoo.com/d/quotes.csv?s=$ticker&f=soac1p2ghjkj1re');
?>
any advice is appreciated, like i said im in the dark on this one.

Here's an example using jquery.
Javascript:
<script type="text/javascript">
var js_variable = appl+goog+fb+mfst+nflx;
$.post("/somephp.php", {ticker: js_variable}, function(data) {
// returned from php
});
</script>
PHP:
<?php
$ticker = $_POST['ticker'];
$file = file_get_contents("http://finance.yahoo.com/d/quotes.csv?s=$ticker&f=soac1p2ghjkj1re");
?>

Expanding on what Jashwant says...
PHP is a server-sided language, which does work behind the scenes. Javascript is client-side, which runs and executes code on the local client's machine (ie through the browser).
You can however use AJAX (Asynchronous JavaScript and XML) so the local client sends HTTP requests to the server without reloading the current page. For instance, you can use AJAX to send the contents of the variable to the server.
For easier usage, you should check out jQuery's methods regarding ajax calls. See: http://api.jquery.com/jQuery.ajax/
Hope it works well.

Heres how you can do it with jquerys post() and then return json, you could build the result as you expect to output within the php part or you could use jquery to loop with each() through the result.
<?php
if($_SERVER['REQUEST_METHOD']=='POST'
&& isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){
if(!empty($_POST['s'])){
$ticker = $_POST['s'];
$file = file_get_contents('http://finance.yahoo.com/d/quotes.csv?s='.$ticker.'&f=soac1p2ghjkj1re');
header('Content-Type: application/json');
echo json_encode(array('result'=>$file));
}else{
echo 'Request not allowed!';
}
die;
}
?>
<!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>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" charset="utf-8"></script>
<script>
var js_variable = "appl+goog+fb+mfst+nflx";
$.post('this_script.php',{s: js_variable}, function(data) {
$('#divResult').replaceWith('<div id="divResult">'+ data.result +'<div>');
});
</script>
</head>
<body>
<div id="divResult"><div>
</body>
</html>

Related

jQuery Json response printing html tags

When I do:
<html>
<head>
</head>
<body>
<?php
$value = isset($_GET['send_request']) ? $_GET['send_request'] : false ;
if ($value) {
echo $value;
return;
}
?>
A
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function test() {
// data to send
var data = { send_request: 'Yes'}
request = $.ajax({
method: 'get',
data: data
});
request.done(function(response){
console.log(response);
});
}
</script>
</body>
</html>
In the console I am getting:
<html>
<head>
</head>
<body>
Yes
Why is this?
The error here is that your php code executes after you have already outputted this part:
<html>
<head>
</head>
<body>
Move the php code to the top of the page and it will fix this :)
Keep in mind that when you execute php script, php will not ommit html, but rather consider it output and just carry on :)
The best practice is to move your PHP codes to a separate PHP file and specify it's path in the url option of your ajax function. That new PHP file should of course not contain HTML before your PHP codes as already pointed out.

Alternatively load page via php if ajax fails

I am trying to replace the contents of a div with an external file via ajax. the code I am using to do so is :
<!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" />
<title>Test</title>
<script type="text/javascript">
window.onload = function(){
document.getElementById("aside").innerHTML="<img src='loadingImage.gif'>";
var x = null;
if (window.XMLHttpRequest) {
var x = new XMLHttpRequest();
} else if (window.ActiveXObject) {
var x = new ActiveXObject('MSXML2.XMLHTTP.3.0');
} else {
// fallback
}
x.open("GET", "other_content_1.php", true);
x.send("");
x.onreadystatechange = function() {
if(x.readyState == 4) {
if(x.status==200)
document.getElementById("aside").innerHTML = x.responseText;
else
document.getElementById("aside").innerHTML = "Error loading document";
}
}
}
</script>
</head>
<body>
<div id="aside">This is other content</div>
</body>
</html>
My Questions:
If JavaScript is enabled, then the above code works fine but if JavaScript is disabled, then php should load that file. How d I do this?
If you are going to make your code backward compatible without JavaScript then you really have no reason to use AJAX at all. If you just want the string into your aside Element then do something like:
//first the PHP page 'other_content_1.php'
<?php
$resp = 'Whatever String Response You Want';
?>
//now your other page
<?php
include 'other_content_1.php';
?>
<!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' />
<title>Test</title>
</head>
<body>
<div id='aside'><?php echo $resp; ?></div>
<script type='text/javascript' src='should_be_external.js'></script>
<body>
</html>
Note, that if you want this to happen besides onload then you would submit a form using $_POST or $_GET to handle the PHP response.
Have you considered trying the noscript option?
See: What do I do if Javascript is disabled by a client?
However, if you have a lot of pages this might be a lot of work if you use jquery/ajax throughout your pages - which I am guessing you do or loading them in with jquery/ajax would be slightly pointless.
By the time the web page is displayed in the browser and found that JS is not supported, PHP/server already served the page. You can try this.
#aside element can have text & link informing user about not having JS support and take another page
PHP can load the file and serve the content in the new page.
If JS is supported, your above code will be anyway replacing the above link.

jquery ui button not appearing after ajax call

I have a jquery ui button in a main page (index.php) which appears and works fine. In the main page I have a div <div id="cardarea"> which I use as a placeholder for dynamic content. The dynamic content is stored in another file (cardarea.php) and elements from this file is displayed dependent on the $_GET['key']; variable it gets from input forms in the main page.
Now the problem is that when I try to include the same jquery ui button (<settingsbtn>) in a part of the contents in the file cardarea.php, this does not display.
The javascript code and definitions are included in the header of index.php. I guess the button in the file cardarea.php cannot reach this information, or that there is an error in my javascript definitions. I've tried including the same javascript code and definitions also in the file cardarea.php, but with no effect.
I'm really quite at a loss of what is the problem here. I will include the javascript definitions, but I'm not sure what other code may be relevant to decifer this problem. Please let me know what additional information may be useful to find the problem, if applicable. Thanks.
Javascript:
$(function() {
$( "settingsbtn" ).button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
});
});
</script>
INDEX.PHP
<?php
include 'functions.php';
include 'incl_ajax.php';
?>
<!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" />
<link href="css/amariffic.css" rel="stylesheet" type="text/css" />
<title>Test</title>
<link href="css/smoothness/jquery-ui-1.10.3.custom.css" rel="stylesheet">
<script src="js/jquery-1.9.1.js"></script>
<script src="js/jquery-ui-1.10.3.custom.js"></script>
<?php include 'snip_javascript.php'; // innholder både kode og css-link. ?>
</head>
<body class="body">
<settingsbtn></settingsbtn>
<a href="javascript:ajaxpage('_cardarea.php?key=5', '_cardarea');" class='nodecor'>Show</a>
<div id="_cardarea"></div>
</body>
</html>
CARDAREA.PHP
<?php
include 'functions.php';
$key = $_GET['key'];
if ($key == '5') {
echo '<div>';
echo 'Button: <settingsbtn> </settingsbtn>';
echo '</div>';
}
?>
You have to run the Javascript function you already wrote again after you complete the AJAX request.
Your function you have to run again:
$(function() {
$( "settingsbtn" ).button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
});
});
I actually ran that function in my Chrome console after the AJAX call, and the second button was correctly shown.
Just define in your javascript functions:
function initButtons(){
$( "settingsbtn" ).button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
});
}
Then overvrite your previously pasted javascript code with:
initButtons();
In the end, you have to add this function call to the end of your AJAX callback function:
initButtons();
put it just right after the instruction where you append the code you recieve from AJAX to the HTML.
EDIT: i looked at your code and i saw that you should put this function here:
function ajaxpage(url, containerid){
[...]
page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
initButtons();
}
[..]
}
Perhaps delegate() is what you are looking for.

pass query string variables without refresh page

My question is that how to pass query string variables on same page without refreshing the page in php? My code is given below:
<img src="a.jpg">
<?php
$a = $_GET['id'];
$b = $_GET['pid'];
?>
Please help me to resolve this issue
<html>
<head>
<title>Test</title>
<meta name="" content="">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#image_id").click(function(){
var dataString = 'a=10&b=20';
$.ajax({
type:'POST',
url:'foo.php',
data:dataString,
success:function(data) {
if(data=="Something") {
// Do Something
} else {
// Do Something
}
}
});
});
});
</script>
</head>
<body>
<img id="image_id" src="images/bg.jpg" />
</body>
</html>
Then in the 'foo.php' page do this
if(isset($_POST['a'])) {
// DO SOMETHING
}
Remember the things that you want to send to the 'data' of
success:function(data)
must be echoed out in the foo.php page
You can't.
PHP requires execution on the server and so you'd have to either use AJAX and update your page accordingly, or just refresh your page.
You can by sending an AJAX request to the server. Ajax is a way to send asynchronous request via Javascript. Notice that jQuery has a good library about it.
Use jquery to resolve this. By using the $.ajax in jquery you can do the stuff you need without page refresh.

Ajax call to a PHP page always returns nothing even though the PHP page echoes something

I am calling a very simple PHP page with some equally simple AJAX, but the call always returns nothing, even though the PHP is fine. That is, you can go to the URL of the PHP page and see that it echoes "Hello World" but when it is called with JS, it returns nothing.
Below is the HTML Page with the Javascript:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Title of the document</title>
</head>
<body>
The content of the document......<br />
Enter your email: <input id="email" type="text" />
<input type="button" onclick="setXMLHttpRequest()" value="Go!" />
<script type='text/javascript'/>
var http;
function setXMLHttpRequest()
{
if(window.XMLHttpRequest)
http = new XMLHttpRequest();
else if(window.ActiveXObject)
http = new ActiveXObject("Microsoft.XMLHTTP");
url = "http://www.convolutedconstruct.com /Ajax/checkemail.php?email=" +
document.getElementById('email').value;
http.onreadystatechange = display;
http.open("GET", url, true);
http.send(null);
}
function display()
{
if (http.readyState == 4)
{
infostr = http.responseText;
alert("From the PHP: " + infostr);
}
}
</script></body></html>
Here is the content of the PHP page
Click here for the live PHP page
<?php
$email = $_GET['email'];
echo "Hello World!";
?>
Why does this return nothing to the JS, even though the PHP page echoes the text correctly?
As has been suggested above, AJAX request will only work usually when both the caller and called are on same domain, You have to ensure that your html code, which contains the javascript, resides on same domain http://www.convolutedconstruct.com.
If that is not the case you can use CORS to allow your ajax to receive input from your php page by sending this header in your php output
<?php
header("Access-Control-Allow-Origin: *");
//rest of your code
?>
See: http://enable-cors.org/
i dont like using the XMLHTTP request. instead i use jQuery's method $.ajax({}); method. it always works for me!
$.ajax({
type: "POST", // or 'GET'
url: "your-url.php", // url that you are passing the data to
data: {
dataName: 'data to pass' // string, variable, object, array, etc
},
success: function(output) { // output is what the url is 'echoing' back to the jQuery
// do something when the ajax method is complete.
}
});
dont forget to import the jQuery source code - http://code.jquery.com/jquery-1.7.2.min.js
these are the most common of the components that are used in ajax.
I'll be glad to help you out some more if you would like it.
If you want to know more just check the documentation on it: http://api.jquery.com/jQuery.ajax/

Categories