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);
}
?>
Related
My problem is not being able to encode the image properly after retrieving it from the database otherwise all my work is fine. After I fetch the image I managed to display it at the same php file using "header('content-type: image/jpeg')".
<?php
header('content-type: image/jpeg');
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
$sql = "select image from images order by id desc limit 1";
require_once('connection.php');
$r = mysqli_query($con,$sql);
$result = mysqli_fetch_array($r);
echo base64_decode($result['image']);
mysqli_close($con);
}else{
echo "Error";
}
?>
The previous piece of code is for displaying directly but it was for testing only, I need to use it as a JSON source so I modified it in this way:
header('Content-type: application/json');
.
.
.
$r['a'] = base64_encode( $result['image']);
echo json_encode($r);
For the Jquery and Ajax part also worked fine and I tested it by making another json file and put an image encoded professionally by this website https://www.base64-image.de/.
And here is Jquery code:
$(document).ready(function(){
(function()
{
d='';
var poll=function()
{
$.ajax({
url: "getjson.php",
type :"get",
dataType: "JSON",
success: function(json)
{
d +='data:image/jpeg;base64,';
d +=json.a;
$("#myimg2").attr("src",d);
}
})
};
poll();
setInterval(function(){
poll();
}, 2000);
})();
});
What I need now is to encode the image just like what this website does https://www.base64-image.de/ because this line base64_encode( $result['image']) seems to be not enough, I have tried many solutions available online but no one worked for me!
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);
});
When sending the request from the jQuery Mobile script to the specified PHP file, nothing is returned, nothing is appended to the html file. Here's the URL of the page:
localhost/basket/newstext.html?url=http://www.basket-planet.com/ru/news/9235
newstext.html:
<head>
<script src="js/newstext.js"></script>
</head>
<body>
<div data-role="page" id="newstext">
<div data-role="content">
<div id="textcontent"></div>
</div>
</div>
</body>
newstext.js:
var serviceURL = "http://localhost/basket/services/";
$('#newstext').bind('pageshow', function(event) {
var url = getUrlVars()["url"];
$.getJSON(serviceURL + 'getnewstext.php?url='+url, displayNewsText);
});
function displayNewsText(data){
var newstext = data.item;
console.log(newstext);
$('#textcontent').text(newstext);
$('#textcontent').trigger('create');
}
function getUrlVars(){
//it displays in the alert perfectly, shortening the message here
}
getnewstext.php:
<?php
include_once ('simple_html_dom.php');
$url = $_GET['url'];
$html = file_get_html(''.$url.'');
$article = $html->find('div[class=newsItem]');
$a = str_get_html(implode("\n", (array)$article));
//parse the article
header("Content-type: application/json");
echo '{"item":'. json_encode($a) .'}';
?>
I think my problem is how I'm encoding the $a variable in the PHP script. The $a variable contains html tags of all kind...how can I append it in the html file?
Where you have this line:
$.getJSON(serviceURL + 'getnewstext.php?url='+url, displayNewsText);
Change it to be:
$.getJSON(serviceURL + 'getnewstext.php?url='+url, displayNewsText, function(response){
$('#elem').append(response);
});
Where #elem is the name of the element that you want to append the data, returned from the PHP file, to.
How do I pass a variable in a php file that is loaded into a page (DOM) to a jQuery function??
Iv'e tried various method's while searching online but I haven't figured out how to use them correctly.
I need the var navHeaderTitle to be passes to the jQuery load() callback function so it sets the HTML tag, #navHeaderTitle, to the variable called in the php file.
Thnx for you help.
php:
<?php
$con = mysql_connect("localhost","user","pw");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("SELECT * FROM some_list");
$navHeaderTitle = "MY NEW TITLE";//<--I NEED 2 INJECT THIS!!
while($row = mysql_fetch_array($result))
{
echo "<div id='navItem' title='$navHeaderTitle'>";
echo "<h1>" . $row['label'] . "</h1>";
echo "<h2>" . $row['title'] . "</h2>";
echo "<p>" . $row['description'] . "</p>";
echo "</div>";
}
mysql_close($con);
?>
JavaScript in the HTML Head:
<script type="text/javascript">
var navHeaderTitle = '';
$(document).ready(
function() {
$("#navContent").load('http://url/my_list.php', function() {
$('#navHeaderTitle').text($(html).find('div#navItem').attr('title'));//<--GET THE VAR FROM LOADED PHP FILE!!
});
});
</script>
<body>
<div id="navPanel">
<div id="navHeader">
<img src="images/ic_return.png" style="float: left;"/>
<img id="listSortBtn" src="images/ic_list_sort.png" style="float: right;"/>
<h4 id="navHeaderTitle"></h4>//THIS IS WHAT NEEDS THE VAR DATA!!
</div>
<div id="navScrollContainer" class="navContentPosition">
<div id="navContent">HTML CONTENT from PHP GETS DUMPED IN HERE</div>
</div>
</div>
</body>
Ive tried using this but not sure how to:
$.get('scripts/my_list.php', {}, function(data){
data = split(':');
})
I would have the php file return a json object that contains two parts, the html you want to echo and the title you want to use.
Then I would use jQuery's .ajax() function instead of .load() to get the return value from your php script in a javascript variable instead of dumping it directly as .load() does.
replace echo("$navHeaderTitle"); with
echo("<script> var navHeaderTitle = $navHeaderTitle </script>");
and remove var navHeaderTitle = ''; from the <head> script..
that will setup a JS variable like you're using, but you have to do that before the code in the <head> loads...
EDIT
ok don't echo("$navHeaderTitle"); you can put it into the HTML like:
echo "<div id='navItem' title='$navHeaderTitle'>";
then in the JS you can do:
<script type="text/javascript">
var navHeaderTitle = '';
$(document).ready(
function() {
$("#navContent").load('http://url/my_list.php', function(response) {
$('#navHeaderTitle').text($(response).attr('title'));
});
});
</script>
here's a jsfiddle demo: http://jsfiddle.net/JKirchartz/hdBzF/ (it's using fiddle's /echo/html/ so the load has some extra stuff to emulate the ajax)
It would be cleaner to pass the var in a custom attribute (data-var), then fetch it width JQuery
$(some_element).attr("data-var");
I hate to mess my JS code with php.
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.