My PHP code is:
<?php
class Sample{
public $name = "N3mo";
public $answer = "";
}
if( isset( $_GET['request'] ) ){
echo "Starting to read ";
$req = $_GET[ 'request' ];
$result = json_decode($req);
if( $result->request == "Sample" ){
$ans = new Sample();
$ans->answer = " It Is Working !!! ";
echo json_encode($ans);
}else{
echo "Not Supported";
}
}
?>
Is there anything wrong
I want to send a JSON to this php and read the JSON that it returns using java script , I can't figure out how to use JavaScript in this , because php creates an html file how Can I use $_getJson and functions like that to make this happen ?!
I tried using
$.getJSON('server.php',request={'request': 'Sample'}) )
but php can't read this input or it's wrong somehow
thank you
try this out. It uses jQuery to load contents output from a server URL
<!DOCTYPE html>
<html>
<head>
<title>AJAX Load Test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function(event) {
$('#responce').load('php_code.php?request={"request":"Sample"}');
});
});
</script>
</head>
<body>
<p>Click on the button to load results from php_code.php:</p>
<div id="responce" style="background-color:yellow;padding:5px 15px">
Waiting...
</div>
<input type="button" id="button" value="Load Data" />
</body>
</html>
Code below is an amended version of your code. Store in a file called php_code.php, store in the same directory as the above and test away.
<?php
class Sample
{
public $name = "N3mo";
public $answer = "";
}
if( isset( $_GET['request'] ) )
{
echo "Starting to read ";
$req = $_GET['request'];
$result = json_decode($req);
if( isset($result->request) && $result->request == "Sample" )
{
$ans = new Sample();
$ans->answer = " It Is Working !!! ";
echo json_encode($ans);
}
else
{
echo "Not Supported";
}
}
Let me know how you get on
It would be as simple as:
$.getJSON('/path/to/php/server.php',
{request: JSON.stringify({request: 'Sample'})}).done(function (data) {
console.log(data);
});
You can either include this in <script> tags or in an included JavaScript file to use whenever you need it.
You're on the right path; PHP outputs a result and you use AJAX to get that result. When you view it in a browser, it'll naturally show you an HTML result due to your browser's interpretation of the JSON data.
To get that data into JavaScript, use jQuery.get():
$.get('output.html', function(data) {
var importedData = data;
console.log('Shiny daya: ' + importedData);
});
Related
I'm working with a CMS project.
Currently I want to build a rating system there but unfortunately that rating system require's JQUERY I'm # learning position on jQuery.
buy my knowledge in working with this rating system.
db ::tables ::columns = id,path,likes,dislikes..
Index.php
<?php
include 'db.php';
include 'conf.php';
$path = $home_path;
$q = "select * from likes where path='".$path."'";
$res = mysqli_fetch_assoc(mysqli_query($mysqli ,$q));
echo 'Likes('.$res["yes"].') ';
echo 'Unlikes('.$res["no"].')';
**Here I wanted to send my parameters with like() function and pass them via jQuery and contact the php page ..and I want the results back from that php page. Like I want to get the json reply **
Kindly please help me.
I meant I need that full jquery code.
And can you please explain me how is that working.
Like what I tried to say is:
index.php & #post_rating.php
<head>
<title>The jQuery Example</title>
<script type ="text/javascript"
src ="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type ="text/javascript" language="javascript">
$(document).ready(function() {
$("#like").click(function(path,type){ //i want to get the values
with this function here
$.ajax({
type: "POST",
url: "post_rating.php",
data: "path=" +path + "&type=" +type,
success: function(){alert('success');}
/////i want to show the the
reply which is producded by php-json page post_rating.php
});
});
});
</script>
</head>
<body>
<?php
include 'db.php';
include 'conf.php';
$path = $home_path;
$q = "select * from likes where path='".$path."'";
$res = mysqli_fetch_assoc(mysqli_query($mysqli ,$q));
echo 'Likes('.$res["yes"].') ';
echo 'Unlikes('.$res["no"].') ';
?>
#post_rating.php
<?php
if(isset($_REQUEST["path"]) && isset($_REQUEST["type"])){
$path = $_REQUEST["path"];
$type = $_REQUEST["type"];
if($type =="dislike"){
$reply = 'you disliked this page '.$path.'';
}
elseif($type =="like"){
$reply = echo 'you lick this page : '.$path.'';
}
json_encode($reply);
}
?>
This block of PHP code prints out some information from a file in the directory, but I want the information printed out by echo to be used inside the HTML below it. Any help how to do this? Am I even asking this question right? Thanks.
if(array_pop($words) == "fulltrajectory.xyz") {
$DIR = explode("/",htmlspecialchars($_GET["name"]));
$truncatedDIR = array_pop($DIR);
$truncatedDIR2 = ''.implode("/",$DIR);
$conffile = fopen("/var/www/scmods/fileviewer/".$truncatedDIR2."/conf.txt",'r');
$line = trim(fgets($conffile));
while(!feof($conffile)) {
$words = preg_split('/\s+/',$line);
if(strcmp($words[0],"FROZENATOMS") == 0) {
print_r($words);
$frozen = implode(",", array_slice(preg_split('/\s+/',$line), 1));
}
$line = trim(fgets($conffile));
}
echo $frozen . "<br>";
}
?>
The above code prints out some information using an echo. The information printed out in that echo I want in the HTML code below where it has $PRINTHERE. How do I get it to do that? Thanks.
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno=[$PRINTHERE]; halos on;", "frozen on")
You just need to make sure that your file is a php file..
Then you can use html tags with php scripts, no need to add it using JS.
It's as simple as this:
<div>
<?php echo $PRINTHERE; ?>
</div>
Do remember that PHP is server-side and JS is client-side. But if you really want to do that, you can pass a php variable like this:
<script>
var print = <?php echo $PRINTHERE; ?>;
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno="+print+"; halos on;", "frozen on"));
</script>
I'm trying to figure out how to update my live data, I found some examples on Google of Ajax but I can't seem to get them to work.
The part that contains and places the live data in a paragraph is :
$file = "Data.txt";
$data = file($file);
$line = $data[count($data)-1];
for($i=1;$i<6;$i++){
switch ($line) {
case $i:
echo "<p class ='bus".$i."'> <img id='bus' src = 'bus.png'> </p>";
break;
}
}
This is the full html file
<!DOCTYPE>
<html>
<head>
<title>Bus</title>
<link rel="stylesheet" href="stijlenbestand.css">
</head>
<body>
<?php
//aanmaken 5 bushaltes
echo '<figure>';
for($i=1;$i<6;$i++){
echo "<img src = 'bushalte.png'>";
}
echo '</figure>';
//laatste lijn van tekstbestand.
$file = "Data.txt";
$data = file($file);
$line = $data[count($data)-1];
for($i=1;$i<6;$i++){
switch ($line) {
case $i:
echo "<p class ='bus".$i."'> <img id='bus' src = 'bus.png'> </p>";
break;
}
}
?>
</body>
</html>
For a live update you need two parts.
First is the part where your page is and the second part is where your data comes from.
Php is a very static language. Once your script is finished it won't do anything anymore.
For a "live-website" you need Javascript.
if you want to use jQuery i would recommend you to use the jQuery.post() function.
jQuery Code in your Website:
$.post( "test.php", { name: "John", time: "2pm" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
Your test.php
if(isset($_POST['name'])) {
//Do Some Stuff
$a = 'var a';
echo json_encode($a);
}
This is not ajax. Ajax means having frontend code fetching new information on the background. This information then gets appended to the DOM. (Usually the information is transfered as JSON encoded data but lets keep that out of scope.)
For this you need two files:
A frontend file (for instance static index.html with some content)
A backend file providing the data
The frontend file would run some JavaScript then requests the backend file
The backend file responds and returns some output
The javascript adds output to the DOM.
There are many ways of doing this and I don't have the te time to explain all of it here but you might want to have a look at: http://www.w3schools.com/jquery/jquery_ajax_intro.asp
This provides a simple example based on jQuery.
I have a problem with some JSON data. I don't know how to take some data generated in PHP and turn that into something that I can use in my jQuery script. The functionality I need is this: I need to be able to click on images on the page, and depending on the selected element, I need to show results from my DB.
Here's the HTML page that I've got:
<html>
<head>
<title>pippo</title>
<script><!-- Link to the JS snippet below --></script>
</head>
<body>
Contact List:
<ul>
<li><a href="#">
<img src="contacts/pippo.png" onclick="javascript:change('pippo')"/>pippo
</a></li>
<li><a href="#">
<img src="contacts/pluto.png" onclick="javascript:change('pluto')"/>pluto
</a></li>
<li><a href="#">
<img src="contacts/topolino.png" onclick="javascript:change('topolino')"/>topolino
</a></li>
</ul>
</body>
</html>
Here's PHP code being called:
<?php
include('../dll/config.php');
$surname = $_POST['surname'];
$result = mysql_query("select * from profile Where surname='$surname'") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$_POST['name'] = ucfirst($row['name']);
$_POST['tel'] = $row['telephone'];
$_POST['companymail'] = $row['companymail'];
$_POST['mail'] = $row['email'];
$_POST['fbid'] = $row['facebook'];
}
?>
Here's the Ajax JavaScript code I'm using:
<script type="text/javascript">
function change(user) {
$.ajax({
type: "POST",
url: "chgcontact.php",
data: "surname="+user+"&name=&tel=&companymail=&mail=&fbid",
success: function(name,tel,companymail,mail,fbid){
alert(name);
}
});
return "";
}
</script>
Someone told me that this JS snippet would do what I want:
$.getJSON('chgcontact.php', function(user) {
var items = [name,surname,tel,companymail,email,facebook];
$.each(user, function(surname) {
items.push('surname="' + user + "'name='" + name + "'telephone='" + telephone + "'companymail='" + companymail + "'mail='" + mail + "'facebook='" + facebook);
});
/*
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
*/
});
But it is not clear to me - I don't understand how I need to use it or where I should include it in my code.
You will have to create a proper JSON string in your PHP script, and then echo that string at the end of the script.
A simple example:
$person = new stdClass;
$result = mysql_query("select * from profile Where surname='$surname'")
or die(mysql_error());
while ($row = mysql_fetch_array( $result )) {
$person->name = ucfirst($row['name']);
$person->tel = $row['telephone'];
$person->companymail = $row['companymail'];
$person->mail = $row['email'];
$person->fbid = $row['facebook'];
}
echo json_encode($person);
There are several problems with your code I have tried to explain via the corrected and commented code here:
HTML & JavaScript
<html>
<head><title>pippo</title>
<!-- added link to jQuery library -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<!-- javascript can go here -->
<script type="text/javascript">
$.ajax({
type: "POST",
url: "chgcontact.php",
// use javascript object instead of `get` string to represent data
data: {surname:user, name:'', tel:'', companymail:'', mail:'', fbid:''},
success: function(data){
// removed name,tel,companymail,mail,fbid
alert(JSON.parse(data));
}
});
return "";
}
</script>
</head>
<body>
Contact List:
<ul>
<!-- removed `javascript` form onclick handler -->
<li><img src="contacts/pippo.png" onclick="change('pippo')"/>pippo</li>
<li><img src="contacts/pluto.png" onclick="change('pluto')"/>pluto</li>
<li><img src="contacts/topolino.png" onclick="change('topolino')"/>topolino</li>
</ul>
</body>
</html>
PHP
<?php
$surname = $_POST['surname'];
$result = mysql_query("select * from profile Where surname='$surname'")
or die(mysql_error());
while ($row = mysql_fetch_array( $result )){
// create data object
$data = new stdClass();
// add values to data object
$data->name = ucfirst($row['name']);
$data->tel = $row['telephone'];
$data->companymail = $row['companymail'];
$data->mail = $row['email'];
$data->fbid = $row['facebook'];
// send header to ensure correct mime type
header("content-type: text/json");
// echo the json encoded data
echo json_encode($data);
}
?>
All code is untested, but you should be able to see what I have done at each step. Good luck.
And to expand on Brian Driscoll's answer. You will need to use the user.name format to access the name field from the returned $.getJSON("blah", function(user){});
so...
items.push('surname="'+user+"'name='"+user.name+"'telephone='"+user.telephone+"'companymail='"+user.companymail+"'email='"+user.email+"'facebook='"+user.facebook+);
In this format that you have created it will just push a long ugly looking string so you might want to spend some time making it look better. Good luck!
JSON that is POSTed to a PHP page generally isn't in the $_POST variable, rather it is in $HTTP_RAW_POST_DATA.
I like to get a dir listing in php
glob("*.jpg");
or
$dir = '.'; //requested directory to read
$notthat = array('.', '..'); //what not to include
$listedfiles = array_diff(scandir($dir), $notthat); // removed what not to include
so i like to send that array to a javascript like that (slides = $listedfiles)
function startSlideshow(slides) { .. do something..}
What is the best way to do that ?
json_encode is your friend for this. No looping is necessary. It will return a pure json object string that you can then just echo into your js file using PHP. Example:
var slides = <?php echo json_encode( $filelistarray );?>
function startSlideshow(slides) { .. do something..}
you can always just do an echo of it to a javascript :
echo ' <script type="text/javascript">
var filelist = [];
';
foreach($listedfiles as $file)
{
echo " filelist[] = $file; ";
}
echo "</script>";
PHP and Javascript cannot directly interact, however, you can output Javascript from PHP the same way you can output plain text or HTML:
<script type="text/javascript">
var slides = [];
<?php
foreach ($listedfiles as $file)
{
echo "slides[] = '" . addslashes($file) . "';\n";
}
?>
// ... do js stuff
</script>
Basically, after creating your array in PHP, you output the JS code to create the same array in javascript.