Ajax call is inserting data on page in some other place - javascript

I am making use of ajax call to insert data in starting of my page. this is more like a wall post script. Whenever user posts something, the latest post is shown in the top of the posts page.
I am using JS, PHP and an HTML page.
here is my js code:
$(function() {
$("#tweet_submit").click(function()
{
var tweet = $("#tweet").val();
var x = $('.preview').attr('id');
if(x)
var z= x;
else
var z=0;
var dataString = 'tweet='+ tweet+ '&z=' +z;
if(tweet=='')
{
alert('Please type your tweet here');
}
else
{
alert('into post');
$.ajax({
type: "POST",
url: "WallPost/post_tweet1.php",
data: dataString,
cache: false,
success: function(html){
$("#tweet").val('');
$("#preview").hide();
$("#content").prepend(html);
}
});
}return false;
});
});
This is my PHP page:
post_tweet.php
<?php
include("includes/db.php");
include("session.php");
include_once 'includes/time_stamp.php';
//echo "request sent to post";
if($_POST)
{
$tweet=$_POST['tweet'];
$upload_id=$_POST['z'];
$time=time();
$query = "INSERT INTO tweets(tweet,time,upload_id,uid_fk) VALUES ('$tweet','$time','$upload_id','$uid')";
if (!mysqli_query($con,$query))
{
die('Error: ' . mysqli_error($con));
}
else
{
$msg ="<br> 1 record added";
}
echo "<br>".$msg;
$sql=mysqli_query($con,"select T.tid, T.tweet, T.time, T.upload_id, U.username, U.fullname, U.email FROM tweets T, users U WHERE T.uid_fk=U.uid and T.uid_fk='$uid' order by T.tid DESC LIMIT 1");
//$show_result=mysqli_query($sql);
while($row=mysqli_fetch_row($sql))
{
echo "data start here";
$tid= "$row[0]";
$tweet= "$row[1]";
$time = "$row[2]";
$img_id= "$row[3]";
$username="$row[4]";
$fullname = "$row[5]";
$email = "$row[6]";
$lowercase = strtolower($email);
$imagecode = md5( $lowercase );
$image_sql=mysqli_query($con,"select image_name from uploads where upload_id='$img_id'");
while($data=mysqli_fetch_row($image_sql))
{
$image_name="$data[0]";
$chars = 7;
$text = $image_name." ";
$text = substr($text,0,$chars);
$imgtext = "pic.twitter/".$text."...";
}
//echo "<div class='center'>";
echo "<div class='tweet_box' id='$tid'>";
echo "<div class='tweet_user'><img class='user_img' src='http://www.gravatar.com/avatar/$imagecode?s=50'></div>";
echo "<div class='tweet_body'>";
?>
<div class='tweet_time'><?php time_stamp($time);?></div>
<?php
echo "<div><b><a href='http://twitter.com/$username'>$fullname</a></b> <span class='uname'>#$username</span></div>";
echo "<div class='tweet_text'>$tweet ";
if($img_id!=0)
{
echo "<a href=''/>$imgtext</a></div>";
}
else
{
echo "</div>";
}
echo "<div class='tweet_options'><div class='first_option'><a href='#'>Expand</a> </div><div class='sub_options'> <a href='#'>Reply</a> <a href='#'>Retweet</a> <a href='#'>Favourite</a></div></div>";
if($img_id!=0)
{
?>
<div class="tweet_image" id="tweetimage<?php echo $tid; ?>">
<center><img src="uploads/<?php echo $image_name; ?>" class="image_show"/></center></div>
<?php
}
echo "</div></div>";
?>
<div class="tweet_reply_box" id="replybox<?php echo $tid;?>">
<div><textarea rel="<?php echo $tid;?>" id="replytext<?php echo $tid;?>" class="reply" name="reply"
maxlength="140">#<?php echo $username;?> </textarea></div>
<div class="reply_button_bar" id="replybutton<?php echo $tid;?>">
<div><input type="submit" value=" Reply " class="reply_btn" id="<?php echo $tid;?>"/></div>
</div>
</div>
<div id="reply_load<?php echo $tid;?>" class="reply_load">
</div>
<?php
}
}
else { }
?>
And this is my HTML page:
Wallpost.php
<!doctype html>
<html>
<head>
<title>Design Modo - Code-pal | eCommerce Website Template - Dead Stocker</title>
<link rel="shortcut icon" href="http://www.code-pal.com/wp-content/themes/codpeal-new/favicon.ico">
<link rel="stylesheet" type="text/css" href="css/check_style.css" />
<link rel="stylesheet" href="css/wallpost/wtfdiary.css">
<link rel="stylesheet" href="css/wallpost/tipsy_title.css">
<script type="text/javascript" src="WallPost/js/jquery.min.js"></script>
<script type="text/javascript" src="WallPost/js/jquery.tipsy.js"></script>
<script src="WallPost/js/twitter.js"></script>
<script type="text/javascript" src="WallPost/js/jquery.form.js"></script>
</head>
<body>
<div class="page-wrap">
<div class="clear"></div>
<?php include("header.php"); ?>
<div class="clear"></div>
<div class="body-contents">
<?php include("left-body1.php"); ?>
<div class="center">
<br>
<div class="txthead"><strong>Share thoughts here</strong></div>
<?php
include("WallPost/index.php");
?>
</div>
</div>
<?php include("right-body.php"); ?>
<div class="clear"></div>
</div>
<!-- eo .body-content -->
<?php include("footer.php"); ?>
</div><!-- eo .page-wrap-->
Here is the code where i post tweet:
index.php under WallPost folder:
<?php
include("includes/db.php");
include("session.php");
include("includes/time_stamp.php");
?>
<html>
<head>
<link rel="stylesheet" href="css/wtfdiary.css">
<link rel="stylesheet" href="css/tipsy_title.css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.tipsy.js"></script>
<script type="text/javascript" src="js/twitter.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
</head>
<body>
<div id="container">
<div id="sidebar_container">
<div id="sidebar">
<div id='logo'><img src='images/1.png'></div>
<div id="box">
<div><textarea id="tweet" name="tweet" placeholder="Compose new Tweet..."></textarea></div>
<div id='preview'></div>
<div id="button_bar">
<div id="icons">
<div class="filebutton" title="Image Upload">
<form id="imageform" method="post" enctype="multipart/form-data" action='ajax_image.php'>
<span><input type="file" name="photoimg" id="photoimg"/></span>
</form>
</div>
</div>
<div><input type="submit" value=" Tweet " class="btn" id="tweet_submit"/></div>
</div>
</div>
</div>
</div>
<!-- <div id="main"> -->
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div id='heading'>Tweets</div>
<div id='content'>
<?php include("loads_tweets1.php");?>
<!-- </div> -->
</div>
</div>
</body>
</html>
So after i make use of all these code, Post is shown in my page, but the way it is shown is not correct.
The post is inserted at some random place. (I couldn't attach image due to less reputation)
Can someone please tell what is going wrong, and i am not able to get this data in correct place where my other posts are listed.
Thanks in advance!!!

Your input helped me and i was able to solve it. Content was being called at two places, and ajax inserted the data on first location and i was not getting it placed where i needed it.
Thanks.

Related

ajax and php - my code is somehow duplicate the elements

i am new in ajax and i try to learn it.
i got this code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<script>
$(document).ready(function(){
/**Add Ajax**/
$("#add-car-form").submit(function (evt) {
evt.preventDefault();//prevent form to be submitted as null
var postData=$(this).serialize();//get all the data from the form
var url=$(this).attr('action');//the url is the action attribute
$.post(url, postData, function(php_table_data){//send back the data from the url
$("#car-result").html(php_table_data);
});
});
});//End Document Ready
</script>
</head>
<body>
<div id="container" class="col-xs-6 col-xs-offset-3">
<div class="row">
<h2>Search our Database</h2>
<input class="form-control" type="text" name="search" id="search" placeholder="search our inventory">
<br>
<br>
<h2 class="bg-success" id="result"></h2>
</div>
<div class="row">
<form method="post" id="add-car-form" action="add_cars.php" class="col-xs-6">
<div class="form-group">
<input type="text" name="car_name" class="form-control">
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="add car">
</div>
</form>
<div class="col-xs-6">
<div id="car-result">
</div>
</div>
</div>
</div>
</body>
</html>
and i got the add_car.php
<?php
include "../db.php";
if(isset($_POST['car_name'])){
$car_name=$_POST['car_name'];
$query="INSERT INTO cars(cars) VALUES('{$car_name}')";
$query_car_name=mysqli_query($connection,$query);
if(!$query_car_name){
die("QUERY FAILED".mysqli_error($connection));
}
header("Location: index.html");
}
?>
now, when i click submit in the form the sql statemant is working but some how i got a dublicate form as a result
here is a picture before insert data:
enter image description here
and here is a result after insterting data:
enter image description here
In add_car.php
Change your code like this
<?php
include "../db.php";
if(isset($_POST['car_name'])){
$car_name=$_POST['car_name'];
$query="INSERT INTO cars(cars) VALUES('{$car_name}')";
$query_car_name=mysqli_query($connection,$query);
if(!$query_car_name){
die("QUERY FAILED".mysqli_error($connection));
}
$table="<table><thead><tr><th>ID</th><th>Car Name</th></tr></thead><tbody>";
$query="Select * From cars ORDER BY id DESC";
$result=mysqli_query($connection,$query);
if($result){
while($row = $result->fetch_assoc()) {
$table.="<tr><td>" . $row["id"]. "</td><td>" . $row["cars"]."</td></tr>";
}
}
$table.="</tbody></table>";
echo $table;
}
?>

jQuery $.ajax is not triggering anything to happen

I am trying to create a text box and whenever a user enters a message and clicks on send, the ajax should be activated and what's on insertMessage.php should get triggered. However, whenever i click on send it doesn't work. here is my chatbox.php file
<?php
session_start();
$conn = new mysqli("localhost", "root", "", "events");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$user=$_SESSION['userid'];
$sql="SELECT * FROM `users` WHERE `Email`='$user'";
$res= mysqli_query($conn,$sql);
$user=mysqli_fetch_assoc($res);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<title></title>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-md-4">
<p>Hi <?php echo $user["FullName"]; ?></p>
<input type="text" id="fromUser" value=<?php echo $user["Email"]; ?> hidden />
<p>Send Message To:</p>
<ul>
<?php
$msgs=mysqli_query($conn,"SELECT * FROM users");
while($msg=mysqli_fetch_assoc($msgs))
{
echo '<li>'.$msg["FullName"].'</li>';
}
?>
</ul>
<--Back
</div>
<div class="col-md-4">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title"><?php
if(isset($_GET["toUser"]))
{
$user=$_GET["toUser"];
$email=mysqli_query($conn,"SELECT * FROM users WHERE Email='$user'");
$emails=mysqli_fetch_assoc($email);
echo '<input type="text" value='.$user.' id="toUser" hidden/>';
echo $emails["Email"];
}
else{
$email=mysqli_query($conn,"SELECT * FROM users");
$emails=mysqli_fetch_assoc($email);
$_SESSION['toUser']=$emails['Email'];
echo '<input type="text" value='.$_SESSION['toUser'].' id="toUser" hidden/>';
echo $emails["Email"];
}
?></h5>
</div>
<div class="model-body" id="msgBody" style="height:400px; overflow-y:scroll; overflow-x:hidden;">
<?php
if(isset($_GET["toUser"]))
{
$chats=mysqli_query($conn,"SELECT * FROM `message` WHERE (`Receiver`='".$_SESSION["userid"]."' AND `Sender`='".$_GET["toUser"]."') OR (`Receiver`='".$_GET["toUser"]."' AND `Sender`='".$_SESSION["userid"]."')");
}
else{
$chats=mysqli_query($conn,"SELECT * FROM `message` WHERE (`Sender`='".$_SESSION["userid"]."' AND `Receiver`='".$_GET["toUser"]."') OR (`Sender`='".$_GET["toUser"]."' AND `Receiver`='".$_SESSION["userid"]."')");
}
while($chat=mysqli_fetch_assoc($chats))
{
if($chat["Sender"]==$_SESSION["userid"])
{
echo "<div style='text-align:right;'>
<p style='background-color:lightblue; word-wrap:break-word; display:inline-block; padding:5px; border-radius:10px; max-width:70%;'>
".$chat["Message"]."</p>
</div>";
}
else{
echo "<div style='text-align:left;'>
<p style='background-color:yellow; word-wrap:break-word; display:inline-block; padding:5px; border-radius:10px; max-width:70%;'>
".$chat["Message"]."</p>
</div>";
}
}
?>
</div>
<div class="model-footer">
<textarea id="message" class="form-control" style="height:43px;max-width:80%;float:left;">
</textarea>
<button id="send" class="btn btn-primary" style="height:70%;float:left;">Send</button>
</div>
</div>
</div>
</div>
</div>
<div class="col-md-4">
</div>
</div>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#send').on('click', function(e) {
e.preventDefault();
$.ajax({
url:"insertMessage.php",
method:"POST",
data:{
fromUser: $("#fromUser").val();
toUser:$("#toUser").val();
message:$("#message").val();
},
dataType:"text",
success:function(data){
$("#message").val("");
}
});
e.preventDefault();
});
});
</script>
</html>
and here is my insertMessage.php file
<?php
session_start();
$conn = new mysqli("localhost", "root", "", "events");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$fromUser=$_POST["fromUser"];
$toUser=$_POST["toUser"];
$message=$_POST["message"];
$output="";
$sql="INSERT INTO `message`(`Sender`, `Receiver`, `Message`) VALUES ('$fromUser','$toUser','$message')";
if($connect->query($sql)){
$output.="";
}
else{
$output.="Error. Please Try Again.";
}
echo $output;
?>
I don't know what to do i tried to find the issue so much but I couldn't. I am new to ajax so I don't know..
I am not sure what your exact problem is but there is one issue in your jQuery code, it takes an object as a value of data, like below :
data: {
fromUser: $("#fromUser").val(),
toUser: $("#toUser").val(),
message: $("#message").val()
},
dataType: "text",
Replace your semicolon (;) with a comma(,)
Put all your form elements inside a <form> in order to receive a data from your $_POST.
<form method="post" action="insertMessage.php">
/* your form elements here */
</form>
Don't forget to include method="post" in your form element, put name="fieldName" on your input elements (text, button, textarea) and a submit button.
Your data seems to have issues:
So, please change:
data:{
fromUser: $("#fromUser").val();
toUser:$("#toUser").val();
message:$("#message").val();
},
To:
data:{
fromUser: $("#fromUser").val(),
toUser:$("#toUser").val(),
message:$("#message").val()
},
Explanation:
Semi colons(;)are for closing a statement.
And the fromUser and others are properties of object data. So, they should be comma separated and it is one statement.
Also, as a suggestion:
<input type="text" id="fromUser" value=<?php echo $user["Email"]; ?> hidden />
The above field definition should have double quotes("") around value.
It creates issues(without semi-colons) when there are spaces in our value.
And hidden makes no meaning at all with above, is it of type="hidden" or is it class="hidden"?

how to restrict the user not to post again on the same page if already posted

I have the below code for User Rating & Comment system which is working fine, but user can post and rate again and again.
I want that if a user posted comment already he/she should not see the comment box but a message that " You have already posted comment on this page".
I tried by using the query in the Add-Comment.php but did not worked.
Need help to solve this issue. Thanks
URL: index.php?id=1
Add-Comment.php
<?php
session_start();
$ipaddress = $_SERVER["REMOTE_ADDR"];
$users = session_id();
if(!empty($_POST)){
extract($_POST);
if($_POST['act'] == 'add-com'):
$comment = htmlentities($comment);
$rating = htmlentities($rating);
// Connect to the database
require_once '../../inc/db.php';
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . "?d=" . $default . "&s=" . $size;
$sql = "INSERT INTO rest_rating (rate, comment, sr_id, ip, user)
VALUES ('$rating', '$comment', '$id_post', '$ipaddress', '$users')";
$sqls = "select user from rest_rating
where sr_id = '$id_post' and user ='$users' )";
$tt = $db->query($sqls);
if ( $tt['user'] == $users ) {
echo '<font size="3" color="red">You Have Already Rated For This Restaurant</font>';
}elseif ( $db->query($sql)==true) {
?>
<div class="cmt-cnt">
<img src="<?php echo $grav_url; ?>" alt="" />
<div class="thecom">
<!--<h5><?php echo $name; ?></h5>-->
<b>Rating : </b><?php echo $rating; ?>
<span class="com-dt"><?php echo date('d-m-Y H:i'); ?></span>
<br/>
<p><?php echo $comment; ?></p>
</div>
</div><!-- end "cmt-cnt" -->
<?php } ?>
<?php endif; ?>
<?php } ?>
index.php
<?php
require_once '../../inc/db.php';
$id=$_GET['id'];
?>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
<link type="text/css" rel="stylesheet" href="css/example.css">
<link href="css/star-rating.css" media="all" rel="stylesheet" type="text/css"/>
<script src="js/star-rating.js" type="text/javascript"></script>
<div class="container">
<h3>Comments</h3>
<?php
$id_post = $id;
?>
<div class="cmt-container" >
<?php
session_start();
$users = session_id();
$results = $db->query("SELECT * FROM rest_rating WHERE sr_id = $id_post");
foreach ($results as $affcom) {
$comment = $affcom['comment'];
$rating = $affcom['rate'];
$date = $affcom['date'];
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . "?d=" . $default . "&s=" . $size;
?>
<div class="cmt-cnt">
<div class="thecom">
<input id="input-5a" class="rating" value="<?php echo $rating; ?>" data-size="xs" data-show-clear="false" data-show-caption="false" data-readonly="true">
<span data-utime="1371248446" class="com-dt"><?php echo $date; ?></span>
<br/>
<p>
<?php echo $comment; ?>
</p>
</div>
</div><!-- end "cmt-cnt" -->
<?php } ?>
<div class="new-com-bt">
<span>Write a comment ...</span>
</div>
<div class="new-com-cnt">
<input name="starrating" id="starrating" value="1" type="number" class="rating" min=0 max=5 step=1 data-size="xs2" >
<textarea class="the-new-com"></textarea>
<div class="bt-add-com">Post comment</div>
<div class="bt-cancel-com">Cancel</div>
</div>
<div class="clear"></div>
</div><!-- end of comments container "cmt-container" -->
<?php
$sqls = "select user from rest_rating
where sr_id = '$id_post' and user ='$users' )";
$tt=$db->query($sqls);
$userT=$tt['user'];
?>
<script type="text/javascript">
$(function(){
//alert(event.timeStamp);
$('.new-com-bt').click(function(event){
$(this).hide();
$('.new-com-cnt').show();
$('#name-com').focus();
});
/* when start writing the comment activate the "add" button */
$('.the-new-com').bind('input propertychange', function() {
$(".bt-add-com").css({opacity:0.6});
var checklength = $(this).val().length;
if(checklength){ $(".bt-add-com").css({opacity:1}); }
});
/* on clic on the cancel button */
$('.bt-cancel-com').click(function(){
$('.the-new-com').val('');
$('.new-com-cnt').fadeOut('fast', function(){
$('.new-com-bt').fadeIn('fast');
});
});
// on post comment click
$('.bt-add-com').click(function(){
var theCom = $('.the-new-com');
var starrating = $('#starrating');
if( !theCom.val()){
alert('You need to write a comment!');
}else{
$.ajax({
type: "POST",
url: "add-comment.php",
data: 'act=add-com&id_post='+<?php echo $id_post; ?>+'&rating='+starrating.val()+'&comment='+theCom.val(),
success: function(html){
theCom.val('');
starrating.val('');
$('.new-com-cnt').hide('fast', function(){
$('.new-com-bt').show('fast');
$('.new-com-bt').before(html);
})
}
});
}
});
});
</script>
</div>
You can construct a query to check whether the user has already posted a comment on that particular page or not, and display the rating and comment box accordingly. Here's the code snippet,
// your code
$results = $db->query("SELECT * FROM rest_rating WHERE sr_id = '". $id_post . "' AND user ='". $users . "'");
if($results->num_rows){
// user has already posted a comment
echo '<p>You have already posted comment on this page</p>';
}else{
// user hasn't posted any comment on this page yet
// display rating and comment box
?>
<div class="new-com-bt">
<span>Write a comment ...</span>
</div>
<div class="new-com-cnt">
<input name="starrating" id="starrating" value="1" type="number" class="rating" min=0 max=5 step=1 data-size="xs2" >
<textarea class="the-new-com"></textarea>
<div class="bt-add-com">Post comment</div>
<div class="bt-cancel-com">Cancel</div>
</div>
<div class="clear"></div>
</div><!-- end of comments container "cmt-container" -->
<?php
}
// your code

How Can I Select State According To Country In Cakephp Using Ajax?

How Can I Select State According To Country In Cakephp Using Ajax?
I want to add state list according to the selected country. For e.g if india
is selected then india States appears in states drop down etc.
Its not working.when i am going to select state according to country.
please help me.below is my coding
in controller
<?php
App::uses('AppController', 'Controller');
class VenuesController extends AppController {
public $uses = array('State','Country','Venue','Facility','User','Image');
public $components = array('Custom');
##################add state##############################
public function state()
{
if($this->RequestHandler->isAjax()) {
$this->layout = 'ajax';
$countryid=$this->request->data('country_id');
$selectstate = $this->State->find('list', array('fields' => array('state_name'), 'conditions' => array('State.country_id' => $countryid)));
$this->set('selectbox',$selectstate);
//pr($selectstate);
}
}
}
in ctp file
<script>
$.noConflict();
</script>
<link href="<?php echo HTTP_ROOT;?>css/jquery.validate.css" rel="stylesheet" type="text/css" />
<script src="<?php echo HTTP_ROOT;?>js/jquery.min.1.8.3.js" type="text/javascript"></script>
<script src="<?php echo HTTP_ROOT;?>js/jquery.validate.js" type="text/javascript"></script>
<script src="<?php echo HTTP_ROOT;?>js/jquery.validation.functions.js" type="text/javascript"></script>
<link href="<?php echo HTTP_ROOT;?>css/admin/AdminLTE.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function showFields(id)
{
alert(id);
//alert("hello");
dataString="country_id="+id;
alert(dataString);
$.ajax({
url: "venues/state",
type: "POST",
data: dataString,//alert(data);
success: function(data)
{
$('#result').html(data);
},
});
}
</script>
<section class="content-header">
<h1> Add Venue </h1>
<ol class="breadcrumb">
<li><i class="fa fa-dashboard"></i> Home</li>
<li class="active">Add Venue</li>
</ol>
</ section>
<!-- Main content -->
<section class="content">
<div class="row">
<!-- left column -->
<?php echo $this->Session->flash('success_message') ?>
<div class="col-md-61">
<!-- general form elements -->
<div class="box box-primary">
<div class="box-header">
<h3 class="box-title">Add Venue</h3>
</div>
<div style="width:49%; float:left;">
<?php echo $this->Form->create('Venue' ,array('id' =>'myform' ,'name' => 'myform','enctype'=>'multipart/form-data')); ?>
<div class="box-body">
<div class="form-group">
<?php echo $this->Form->input('country', array('onChange'=>'showFields(this.value)','class'=>'form-control','id' =>'country','type' => 'select','label'=>true,'label'=>'country:','options' => $country ,'empty' => 'Select A Country','required'=>'false')); ?>
</div>
<div class="form-group">
<div id="result">
<?php
echo $this->Form->input('state', array('class'=>'form-control','id' =>'state','type' => 'select','label'=>true,'label'=>'state:','options' => $state ,'empty' => 'Select A State','required'=>'false')); ?>
</div>
</div>
<!--<div id="state"></div>-->
</div>
</div>
<!-- /.box-body -->
</div>
</div>
</div>
</section>
In your action the list only and sent id to the view and generate the options like -
View file for state action
<option value="">Select One</option>
<?php
foreach($selectbox as $key => $value) {
echo "<option value='".$key."'>".$value."</option>";
}
?>
Generate the select field with an id -
echo $this->Form->input('state', array('class'=>'form-control','id' =>'state','type' => 'select','label'=>true,'label'=>'state:','options' => $state ,'empty' => 'Select A State','required'=>'false')); ?>
Now on the Ajax success part -
$.ajax({
url: "venues/state",
type: "POST",
data: dataString,//alert(data);
success: function(data)
{
$('#state').html(data);
},
});
Hope it will do the trick.
Please echo your result in controller or model where your getting state list..then try to alert data in success function.
format your code like select dropdown Means like this
<option value="<?php echo state_id;?>"><?php echo $state_name;?></option>
Make changes according to cake php.

PHP messages aren't being written to the log file - tutsplus.com tutorial

tutsplus, there you will find a tutorial which guides you through the steps on how to create a simple web chat. I tried to follow all that was said, yet I noticed a problem when testing. It seems that the usermsg is not being posted to the log.html file.
here is the index.php, which in this case is named chat.php:
<?php
function loginForm() {
echo '
<div id="loginform">
<form action="chat.php" method="post">
<p>Please enter your name to continue:</p>
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<input type="submit" name="enter" id="enter" value="enter">
</form>
</div>
';
}
if(isset($_POST['enter'])) {
if($_POST['name'] != "") {
$_SESSION['name'] = stripslashes(htmlspecialchars($_POST['name']));
}else {
echo '<span class="error">Please type in a name</span>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Basic Chat Service</title>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css" title="style" type="text/css" media="screen" charset="utf-8">
</head>
<body>
<?php
if(!isset($_SESSION['name'])) {
loginForm();
}else{
?>
<div id="wrapper">
<div id="menu">
<div class="welcome">Welcome, <?php echo $_SESSION["name"]; ?></div>
<div class="logout">Exit Chat</div>
<div style="clear:both;"></div>
</div>
<div id="chatbox"><?php
if(file_exists("log.html") && filesize("log.html") > 0) {
$handle = fopen("log.html", "r");
$contents = fread($handle, filesize("log.html"));
fclose($handle);
echo $contents;
}
?></div>
<form name="message" action="">
<input type="text" name="usermsg" id="usermsg" size="63">
<input type="submit" name="submitmsg" id="submitmsg" value="Send">
</form>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" charset="utf-8"></script>
<script type="text/javascript">
//jQuery Document
$(document).ready(function() {
$("#exit").click(function() {
var exit = confirm("Are you sure you want to logout?");
if(exit == true) {
window.location = 'chat.php?logout=true';
}
});
$("#submitmsg").click(function() {
var clientmsg = $("#usermsg").val();
console.log(clientmsg);
$.post("post.php", {text: clientmsg});
$("#usermsg").attr("value", "");
return false;
});
function loadLog() {
var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
$.ajax({
url:"log.html",
cache: false,
success: function(html){
$("#chatbox").html(html);
var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
if(newscrollHeight > oldscrollHeight) {
$("#chatbox").animate({scrollTop: newscrollHeight}, 'normal');
}
}
});
}
setInterval(loadLog, 2500);
});
</script>
<?php
}
if(isset($_GET['logout'])) {
$fp = fopen("log.html", 'a');
fwrite($fp, '<div class="msgln"><i>User '.$_SESSION['name'].' has left the chat session.</i><br></div>');
fclose($fp);
session_destroy();
header("Location: chat.php");
}
?>
</body>
</html>
Here is the post.php:
<?php
session_start();
if(isset($_SESSION['name'])) {
$text = $_POST['text'];
$fp = fopen("log.html", 'a');
fwrite($fp, "<div class='msgln'>(".date("g:i A").")<b>".$_SESSION['name']."</b>:".stripslashes(htmlspecialchars($text))."<br></div>");
fclose($fp);
}
?>
I am using MAMP, and the files are located in the htdocs folder, so that's not the problem.
Thanks in advance for any help you can give me, and let me know if you need more info.
You should call session_start() in index.php.
(from Marc B in the comments)

Categories