Ive been following phpacademy recently and their code simply doesn't work.Well it works fine to the point of displaying the articles but the like button doesn't work, it stops at '$.post' method,its job was to update the article_likes to '22', take a look:
index.php
<html>
<head>
<?php include 'core/db/connect.php'; ?>
</head>
<body>
<?php
$articles = get_articles();
if(count($articles) == 0)
echo "No art";
else{
//Displaying articles.
foreach($articles as $article){
echo $article['article_title']."<br>";
echo "<a onclick=\"like_add(".$article['article_id'].");\" href='#'>Like</a><br>";
echo "<span id='article_".$article['article_id']."_likes'>".$article['article_likes']. "</span>Likes<br> ";
}
}
?>
<script type="text/javascript" src="js/jquery-3.3.1.js"></script>
<script type="text/javascript" src="js/like.js"></script>
</body>
</html>
like.js
function like_add(article_id){
$.post('like_add.php',{article_id:article_id},function(data){
if(data[0] == 'success'){
like_get(article_id);
} else {
alert(data[0]);
}
});
}
function like_get(article_id){
$.post('like_get.php',{article_id:article_id},function(data){
$('#article_'+article_id+'_likes').text(data[0]);
});
}
like_add.php
<?php echo "success";?>
like_get.php
<?php echo "22";?>
Related
I want to write Jquery code inside PHP tag. I wanted to do this so that I can perform AJAX after that.
I have tried to echo it, but it doesn't work.
<?php
require("conn.php");
$rs = mysql_query("select * from food order by LENGTH(price), price");
if($rs!=false && mysql_num_rows($rs)>0){
$counter ++;
while($row = mysql_fetch_array($rs)){
echo '
<script src="jquery.js">
<script>
$(document).ready(function(){
$("#'.$row["code"].'").click(function(){
echo "clicked";
});
});
</script>
';
}
mysql_free_result($rs);
}else{
echo mysql_error();
}
mysql_close();
?>
Here's a small rearrangement of your code.
<?php
require("conn.php");
$rs = mysql_query("select * from food order by LENGTH(price), price");
if($rs!=false && mysql_num_rows($rs)>0){
$counter ++;
while($row = mysql_fetch_array($rs)){
echo '<a class="row_food">'. $row["code"] .'</a>';
}
mysql_free_result($rs);
}else{
echo mysql_error();
}
mysql_close();
?>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
$('.row_food').click(function(){
alert("clicked");
return false;
});
});
</script>
You don't have to echo the javascript code every time in the loop! You only need to echo the content from your db inside the loop.
In the javascript/jquery, you could bind the click event to the element and do whatever you needed.
Hope it helps.
Just put </script> after jquery.js.
Hi guys can i ask what is the problem on my code.
all i want is if there is someone already login then if i click back i don`t want to see the login form what is the problem in my code thank you for you help
//php for check if i login
<link rel="stylesheet" href="bootstrap.min.css" />
<?php
if (!isset($_SESSION["member_id"])) {
header("Location:index.php");
}
?>
//html
<?php
session_start();
require_once("check_login.php");
?>
<!DOCTYPE html>
<html>
<head>
<title>All Members</title>
<link rel="stylesheet" href="bootstrap.min.css" />
<script>
function confirmDelete() {
if (!confirm("Are you sure you want to delete this member?")) {
return false;
}
}
</script>
</head>
<body>
<?php require_once("top_nav.php"); ?>
<div class="container">
<h1>All Members</h1>
<table class="table table-striped">
<th>ID</th>
<th>Email</th>
<th>Name</th>
<th></th>
<?php
require_once("db_open.php");
$sql = "SELECT * FROM members";
$result = $conn->query($sql) or die($conn->error);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$delete_link = "delete_member_db.php?member_id=".$row["member_id"];
echo "<tr>";
echo "<td>".$row["member_id"]."</td>";
echo "<td>".$row["member_email"]."</td>";
echo "<td>".$row["member_full_name"]."</td>";
echo "<td><a href='".$delete_link."' onClick='return confirmDelete();' class='btn btn-danger btn-xs'>Delete</a></td>";
echo "</tr>";
}
} else {
echo "<p>No members to show...</p>";
}
require_once("db_close.php");
?>
</table>
</div>
</body>
</html>
My apologies, I didn't get your question exactly but as per my understanding, in order to avoid login page view if user is logged in, you have to check with another condition on login page that,
if (isset($_SESSION["member_id"])) {
header("Location:some_page_name.php");
}
I think, You have checked condition
if (!isset($_SESSION["member_id"])) {
header("Location:index.php");
}
which is useful for pages visible after logging in...
Im learning PHP, Html and twitter-bootstrap (v2.3.2). I'm trying to display a message depending on the value received by GET.
I have two alerts in different sections of the site and I want depending on the value received by GET display one or the other. not both.
i.e: http:localhost/test.php?load=lannister, should show the message: "A Lannister always pays his debts". however, the url: http:localhost/test.php?load=stark, should show the message: "you know nothing john snow". But I can not figure how to do this, I need a hand, I thought it could be done with an if-else, but I fail to understand how to do it at all. Any ideas?
Heres the code:
<?php session_start();?>
<!DOCTYPE html>
<html>
<head>
<title>Testing</title>
<!-- Obtain Bootstrap style sheet from CDN (online service) so it doesn't have to be on my machine -->
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css" rel="stylesheet" media="screen">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
window.setTimeout(function() {
$("#alert_message").fadeTo(500, 0).slideUp(500, function(){
$(this).remove();
});
}, 2000);
</script>
<script type="text/javascript">
window.setTimeout(function() {
$("#alert_message2").fadeTo(500, 0).slideUp(500, function(){
$(this).remove();
});
}, 2000);
</script>
</head>
<body>
<?php
$load = $_GET['load'];
switch ($load) {
case "stark":
$message="you know nothing john snow";
break;
case "lannister":
$message="A Lannister always pays his debts";
break;
}
?>
<?php
if ($load==='stark'){
echo "<div id=\"alert_message\" class=\"alert alert-error\">
<div id=\"alert_placeholder\" align=\"center\" style=\"color:#FFFFFF;font-size: 0.9em;\">".$message."</div>
</div>";
} else{
?>
<div class="container">
<div class="container">
<h1>Bootstrap CDN starter template using boostrapcdn.com</h1>
<p>Use this document as a way to quick start any new project.<br>
All you get is this message and a barebones HTML document.</p>
</div> <!-- /container -->
<?php
echo "<div id=\"alert_message2\" class=\"alert alert-error\">
<div align=\"center\" style=\"color:#FFFFFF;font-size: 0.85em;\" >".$message."</div>
</div>";
}?>
</div>
</body>
</html>
I know it's a silly question, but I've been thinking how to do it for hours without any success. Thanks in advance
You're correct in using a switch statement, but as #true stated in his comment, you should check to ensure the variable is set and not empty.
You could do that in long/short hand:
// long
if(isset($_GET['load']) && !empty($_GET['load'])) {
$load = $_GET['load'];
} else {
$load = null;
}
//short
$load = (isset($_GET['load']) && !empty($_GET['load'])) ? $_GET['load'] : null;
Since you set $load to null if it's not present/empty. You can test like this:
if($load == NULL) {
// message is error because neither stark/lannister selected
} else {
switch($load) {
case "stark":
//do start stuff here
break;
case "lannister":
// do lannister stuff here
break;
}
}
Now for the final part. This block of code:
if ($load==='stark'){
echo "<div id=\"alert_message\" class=\"alert alert-error\">
<div id=\"alert_placeholder\" align=\"center\" style=\"color:#FFFFFF;font-size: 0.9em;\">".$message."</div>
</div>";
}
Is not needed. (The if condition is not needed) As you already do the conditioning work in the switch statement to set the message that will be displayed in the alert box. Meaning you'd just have the echo somewhere in your markup!
echo "<div id=\"alert_message\" class=\"alert alert-error\">
<div id=\"alert_placeholder\" align=\"center\" style=\"color:#FFFFFF;font-size: 0.9em;\">".$message."</div>
</div>";
Try cleaning up the code a small amount to make life easier on you.
<?php if($_GET){
$load = isset($_GET['load']) ? $_GET['load'] : null;
}
if ($load == "stark") {
//ECHO
}
elseif ($load == "lannister") {
//echo
}
else {
//default
}
I am having a problem with how to echo javascript in php. I have a form which on submit will execute itself and echo some text and will redirect to a page in 5secs. I am currently echoing this:
header("Refresh: 5;url=index2.php?ID=".$objResult["ID"]."");
echo '<html>';
echo '<head>';
echo '<title>Klant toevoegen</title>';
echo '<link rel="stylesheet" href="style.css" type="text/css" media="screen" />';
echo '</head>';
echo '<body>';
echo '<fieldset>';
echo ''.$Naam.' is added to the database, u will be redirected in a couple of seconds.<br><br>';
echo '</fieldset>';
echo '</body>';
echo '</html>';
The javascript I have is a countdown which counts down from 5 to 1. The code is this:
<script>
var countdownFrom = 5; // number of seconds
var countdownwin;
var stp;
function CountDownStart() {
stp = setInterval("CountDownTimer('CountDownTime')",1000)
}
function CountDownTimer(id)
{
if (countdownFrom==0) {clearInterval(stp); window.close(); }
else {
var x
var cntText = "Closing in "+countdownFrom+" seconds";
if (document.getElementById)
{
x = document.getElementById(id);
x.innerHTML = cntText; }
else if (document.all)
{
x = document.all[id];
x.innerHTML = cntText; }
}
countdownFrom--
}
</script>
<title>Untitled</title>
</head>
<body onload="CountDownStart()">
<Div id="CountDownTime"></div>
</body>
Now I would like to echo this countdown script to replace the <fieldset> in the html. I have tried several things like just add the whole code in 1 echo ''; and I tried to echo all the lines seperately but with both it crashes my whole script. If anyone knows how to do this it would be great!
I Wouldn't write all those echo's, instead, leave all the HTML and JS outside the PHP block
<?php
some php code
?>
HTML AND JS
<?php
More php if required
?>
And use
<?=$Naam?>
To inject your values where required
Alternatively you should look into template engines
Try to use
echo <<<EOT
/* some text here */
EOT;
You can put the script in a separate .js file and echo the script tag:
<? echo "<script type='text/javascript' src='path/to/script.js' ></script> ?>
Don't forget to remove any HTML tags from the JS file, like <body>, <head>, etc.
I'm using a CKEditor along with a CKFinder. Both work fine. When I browse (or copy directly) an image (or flash) to CKEditor, it's displayed within it and inserted into the MySql database.
Aafter inserting it into MySql database, I'm trying to display it in an HTML table where it isn't displayed and the alternate text is displayed.
The image path after browsing an image through the CKFinder is something like the following.
<img alt="" src="/ckfinder/userfiles/images/1243_SS_2502.jpg" style="width: 490px; height: 618px;" />
The contents inserted into the database is as follows.
<img alt="\"\"" data-cke-saved-src="\"
src="\"/ckfinder/userfiles/images/1243_SS_2502.jpg\"" st yle=&
quot;\"width:" 490px;="" height:="" 618px;\"= quot;">
Tried with htmlentities() still it doesn't work. While dealing the same with JSP using JSTL/EL, I had to do the following.
<c:out value="${str}" default="No content found." escapeXml="false"/>
escapeXml="false", where str written in EL was a java.lang.String holding the Oracle clob data after conversion.
What is the way to get around the situation in PHP? Both CKEditor and CKFinder work fine for me.
$ckeditor = new CKEditor();
$ckeditor->basePath = 'ckeditor/';
$ckeditor->config['filebrowserBrowseUrl'] = 'ckfinder/ckfinder.html';
$ckeditor->config['filebrowserImageBrowseUrl'] = 'ckfinder/ckfinder.html?type=Images';
$ckeditor->config['filebrowserFlashBrowseUrl'] = 'ckfinder/ckfinder.html?type=Flash';
$ckeditor->config['filebrowserUploadUrl'] = 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files';
$ckeditor->config['filebrowserImageUploadUrl'] = 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images';
$ckeditor->config['filebrowserFlashUploadUrl'] = 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash';
$ckeditor->editor('description', $ed_about_us);
Edit:
<?php include_once("Lock.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>Wagafashion</title>
<link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css"/>
<link rel="stylesheet" href="css/template.css" type="text/css"/>
<!--<script type="text/javascript" language="javascript" src="ckeditor/ckeditor.js"></script>-->
<script src="js/jquery-1.6.min.js" type="text/javascript"></script>
<script src="js/languages/jquery.validationEngine-en.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery.validationEngine.js" type="text/javascript" charset="utf-8"></script><script>
jQuery(document).ready(function(){
// binds form submission and fields to the validation engine
jQuery("#dataForm").validationEngine();
});
</script>
<script language="javascript" type="text/javascript">
function deleteSingle(id)
{
var delId=confirm("About us with the id "+id+" is about to be deleted permanently.\n\nAttention : This action will never be undone!\n\nAre you sure...???");
return(delId==true?true:false);
}
</script>
</head>
<body>
<?php
include_once("Connection.php");
include_once("ckeditor/ckeditor.php");
$con=new Connection();
$con->get_connection();
$ed_about_us="";
$flag=-1;
$msg="";
if(isset($_POST['btnSubmit']))
{
$act=trim($_POST['param_action']);
$about_us=$_POST['cms_description'];
if($act=="add")
{
$res=$con->get_data("select count(*) as cnt from cms");
$cnt_cmt=mysql_result($res, 'cnt');
if($cnt_cmt==0)
{
$flag=$con->iud("insert into cms (about_us)values('".mysql_real_escape_string(urlencode($about_us))."')");
}
else
{
$flag=$con->iud("update cms set about_us='".mysql_real_escape_string(urlencode($about_us))."'");
}
if($flag==1)
{
$msg="Insertion done successfully.";
}
else if($flag==0)
{
$msg="Insertion failed - reason : ".mysql_errno()." : ".mysql_error();
}
}
else if($act=="edit")
{
$cms_id=$_POST['cms_id'];
$flag=$con->iud("update cms set about_us='".mysql_real_escape_string(urlencode($about_us))."' where id=".$cms_id."");
if($flag==1)
{
$msg="About us has been updated successfully.";
}
else if($flag==0)
{
$msg="Updation failed - reason : ".mysql_errno()." : ".mysql_error();
}
}
}
else if(isset($_GET['ed_id']))
{
$ed_res=$con->get_data("select about_us from cms where id=".$_GET['ed_id']."");
while($row=mysql_fetch_assoc($ed_res))
{
$ed_about_us=$row['about_us'];
}
}
else if(isset($_GET['del_id']))
{
$flag=$con->iud("update cms set about_us='' where id=".$_GET['del_id']);
if($flag==1)
{
$msg="About us been deleted successfully.";
}
else if($flag==0)
{
$msg="Can not delete - reason : ".mysql_errno()." : ".mysql_error();
}
}
else if(isset($_POST['btnDelete']))
{
$set_del=$_POST['setDel'];
$flag=$con->iud("update cms set about_us='' where id in($set_del)");
$size=sizeof(split(",", $set_del));
if($flag==1)
{
if($size==1)
{
$msg="1 row deleted.";
}
else
{
$msg=$size." rows deleted.";
}
}
else if($flag==0)
{
$msg="Can not perform deletion - reason : ".mysql_errno()." : ".mysql_error();
}
}
?>
<?php include("tamplate/Template1.php");?>
<h2>About Us</h2>
<?php include("tamplate/NewTemplate.php");?>
<?php
if($flag==1)
{
echo "<p>";
?>
<!--[if !IE]>start system messages<![endif]-->
<ul class="system_messages">
<li class="green"><span class="ico"></span><strong class="system_title"><?php echo $msg; ?></strong></li>
</ul>
<!--[if !IE]>end system messages<![endif]-->
<?php
echo "</p>";
}
else if($flag==0)
{
echo "<p>";
?>
<!--[if !IE]>start system messages<![endif]-->
<ul class="system_messages">
<li class="red"><span class="ico"></span><strong class="system_title"><?php echo $msg; ?></strong></li>
</ul>
<!--[if !IE]>end system messages<![endif]-->
<?php
echo "</p>";
}
?>
<img alt=\"\" src="/ckfinder/userfiles/images/1243_SS_2502.jpg" style=\"width: 490px; height: 618px;\" />
<!--[if !IE]>start forms<![endif]-->
<form action="<?php $_SERVER['PHP_SELF']; ?>" id="dataForm" name="dataForm" method="post" class="search_form general_form">
<!--[if !IE]>start fieldset<![endif]-->
<fieldset>
<!--[if !IE]>start forms<![endif]-->
<div class="forms">
<!--[if !IE]>start row<![endif]-->
<div class="row">
<?php
$ckeditor = new CKEditor();
$ckeditor->basePath = 'ckeditor/';
$ckeditor->config['filebrowserBrowseUrl'] = 'ckfinder/ckfinder.html';
$ckeditor->config['filebrowserImageBrowseUrl'] = 'ckfinder/ckfinder.html?type=Images';
$ckeditor->config['filebrowserFlashBrowseUrl'] = 'ckfinder/ckfinder.html?type=Flash';
$ckeditor->config['filebrowserUploadUrl'] = 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files';
$ckeditor->config['filebrowserImageUploadUrl'] = 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images';
$ckeditor->config['filebrowserFlashUploadUrl'] = 'ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash';
$ckeditor->editor('cms_description', urldecode($ed_about_us));
?>
<!--[if !IE]>start row<![endif]-->
<div class="row">
<div class="buttons">
<span class="button send_form_btn"><span><span>Submit</span></span><input type="submit" value="Submit" id="btnSubmit" name="btnSubmit" onclick="return validate();"></span>
</div>
</div>
<!--[if !IE]>end row<![endif]-->
</div>
</fieldset>
<!--[if !IE]>end fieldset<![endif]-->
<input type="hidden" id="param_action" name="param_action" value="
<?php
if(isset($_GET['ed_id']))
{
echo "edit";
}
else
{
echo "add";
}
?>
" />
<input type="hidden" id="cms_id" name="cms_id" value="<?php echo isset($_GET['ed_id'])?$_GET['ed_id']:"";?>" />
</form>
<?php include("tamplate/Template2.php");?>
<h2>About Us</h2>
<?php include("tamplate/NewTemplate1.php");?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" id="mainForm" name="mainForm" method="post">
<?php include("tamplate/ExtraTemplate.php");?>
<table cellpadding="0" cellspacing="0" width="100%">
<tbody>
<th style="width: 10px;">Check</th>
<th style="width: 450px;">About Us</th>
<th style="width: 10px;">Actions</th>
<?php
$get_data=$con->get_data("select id, about_us from cms order by id");
$cnt=1;$flag='';
while($data_row=mysql_fetch_assoc($get_data))
{
extract($data_row);
$cnt%2==0?$flag="second":$flag="first";
++$cnt;
echo "<tr class='$flag'>";
echo "<td><input type='checkbox' name='chk' value='$id'></td>";
echo "<td>".urldecode($about_us)."</td>";
echo "<td><div class='actions'><ul><li><a href='".$_SERVER['PHP_SELF']."?ed_id=$id' class='action2'></a></li>";
echo "<li><a href='".$_SERVER['PHP_SELF']."?del_id=$id&table_name=cms&pri=id' onclick='return deleteSingle($id);' class='action4'></a></li></ul></div></td>";
echo "</tr>";
}
?>
</tbody>
</table>
<input type='hidden' id='setDel' name='setDel'/>
<?php include("tamplate/Template3.php");?>
</form>
<?php include("tamplate/Template4.php");?>
</body>
</html>
Did you try to use html_entity_decode() to display the contents ? It will decode the encoded html for better output. Reference here
Edit
Change your query to the following
insert into cms (about_us) values ('".mysql_real_escape_string(urlecode(stripslashes($about_us)))."')
When you get it from database it use
urldecode($value)
Where $value is the block you got from database.