I have this form in a PHP file:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
function sendPushNotification(id){
var data = $('form#'+id).serialize();
// $('form#'+id).unbind('submit');
$.ajax({
url: "table_ready.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
//$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
<style type="text/css">
.bigcontainer{
width: auto;
margin: 0 auto;
padding: 0;
}
h1{
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 24px;
color: #777;
}
div.clear{
clear: both;
}
ul.devices{
margin: 0;
padding: 0;
list-style: none;
}
.smallcontainer {
border: 2px solid #ccc;
width: 300px;
height: 100px;
overflow-y: scroll;
}
ul.devices li{
float: left;
display: inline;
padding: 10px;
margin: 0 15px 25px 0;
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
color: #555;
}
ul.devices li label, ul.devices li span{
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 12px;
font-style: normal;
font-variant: normal;
font-weight: bold;
color: #393939;
display: block;
float: left;
}
ul.devices li label{
height: 25px;
width: 150px;
}
ul.devices li .send_btn{
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#0096FF), to(#005DFF));
background: -webkit-linear-gradient(0% 0%, 0% 100%, from(#0096FF), to(#005DFF));
background: -moz-linear-gradient(center top, #0096FF, #005DFF);
background: linear-gradient(#0096FF, #005DFF);
text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3);
border-radius: 3px;
color: #fff;
}
</style>
</head>
<body>
<div class="bigcontainer">
<?php
include_once 'include/DB_Functions.php';
$db = new DB_Functions();
$state = $db->checkTableState();
if ($state != false)
$no_of_state = mysql_num_rows($state);
else
$no_of_state = 0;
if ($no_of_state > 0) {
?>
<ul class="devices">
<?php
while ($staterow = mysql_fetch_array($state)) {
$items = $db -> displayTable($staterow["state"]);
?>
<li>
<form id="<?php echo $staterow["state"] ?>" name="" method="post" onsubmit="return sendPushNotification('<?php echo $staterow["state"] ?>')">
<h1>Τραπέζι: <?php echo $staterow["state"]; ?></h1>
<div class="smallcontainer">
<ul>
<?php
// $num_of_items = mysql_fetch_array($items);
while($row = mysql_fetch_array($items)){
$food = Array();
$quan = Array();
$food[] = $row['food'];
$quan[] = $row['uquantity'];
foreach( $food as $index => $f){
?>
<li>
<label>
<?php echo $f; ?> <?php echo $quan[$index]; }?>
</label>
</li>
<div class="clear"></div>
</form>
</li>
<?php
}
?>
</ul>
</div>
<div class="send_container">
<input type="hidden" name="table" value="<?php echo $staterow["state"] ?>"/>
<input type="submit" class="send_btn" value="Send" onclick=""/>
</div>
<?php
}
} else {
?>
<li>No Users Registered Yet!</li>
<?php
}
?>
</ul>
</div>
</body>
</html>
I am using this function to send the value with name table, to my table_ready.php file:
<script type="text/javascript">
function sendPushNotification(id){
var data = $('form#'+id).serialize();
// $('form#'+id).unbind('submit');
$.ajax({
url: "table_ready.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
//$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
For some reason it doesn't work. My knowledge of JavaScript is very bad, and I can not figure out what I am doing wrong. The table_ready.php works fine but it doesn't accept the value and so it doesn't work. Any hint on what I am doing wrong?
I'm supposing you omitted part of the script (connection and query itself) and that is working correctly.
The second thing is the usage of jQuery serialize() (http://api.jquery.com/serialize/) it will convert form elements (input, textarea, select) to be sent, and your data is just inside <label>, try using some hidden fields so serialize will find and encode it to be sent to the other script.
Related
I am very new to jquery and ajax. Trying to implement selectize plugin that would query the database and return the values as dropdown. In order to do that, here is my php code that brings back data from the table. If I type the url for this php page and pass parameters, it brings back data in json format. {"movies":"value1"}{"movies":"value2"} .....
$q = $_GET['query'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT column_name from table where segment_name like '%$q%'";
$result = $conn->query($sql);
error_reporting(0);
$name->movies = "";
if ($result->num_rows > 0) {
// output data of each row
while($segment_name = $result->fetch_assoc()) {
$name->movies = $segment_name["segment_name"];
$movies = json_encode($name);
echo $movies;
}
} else {
echo "0 results";
}
$conn->close();
And, here is the jQuery code from the selectize plugin.
<!DOCTYPE html>
<!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7"><![endif]-->
<!--[if IE 7]><html class="no-js lt-ie9 lt-ie8"><![endif]-->
<!--[if IE 8]><html class="no-js lt-ie9"><![endif]-->
<!--[if gt IE 8]><!--><html class="no-js"><!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Selectize.js Demo</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/stylesheet.css">
<!--[if IE 8]><script src="js/es5.js"></script><![endif]-->
<script src="js/jquery.min.js"></script>
<script src="../dist/js/standalone/selectize.js"></script>
<script src="js/index.js"></script>
<style type="text/css">
.selectize-control.movies .selectize-dropdown [data-selectable] {
border-bottom: 1px solid rgba(0,0,0,0.05);
height: 60px;
position: relative;
-webkit-box-sizing: content-box;
box-sizing: content-box;
padding: 10px 10px 10px 60px;
}
.selectize-control.movies .selectize-dropdown [data-selectable]:last-child {
border-bottom: 0 none;
}
.selectize-control.movies .selectize-dropdown .by {
font-size: 11px;
opacity: 0.8;
}
.selectize-control.movies .selectize-dropdown .by::before {
content: 'by ';
}
.selectize-control.movies .selectize-dropdown .name {
font-weight: bold;
margin-right: 5px;
}
.selectize-control.movies .selectize-dropdown .description {
font-size: 12px;
color: #a0a0a0;
}
.selectize-control.movies .selectize-dropdown .actors,
.selectize-control.movies .selectize-dropdown .description,
.selectize-control.movies .selectize-dropdown .movies {
display: block;
white-space: nowrap;
width: 100%;
overflow: hidden;
text-overflow: ellipsis;
}
.selectize-control.movies .selectize-dropdown .actors {
font-size: 10px;
color: #a0a0a0;
}
.selectize-control.movies .selectize-dropdown .actors span {
color: #606060;
}
.selectize-control.movies .selectize-dropdown img {
height: 60px;
left: 10px;
position: absolute;
border-radius: 3px;
background: rgba(0,0,0,0.04);
}
.selectize-control.movies .selectize-dropdown .meta {
list-style: none;
margin: 0;
padding: 0;
font-size: 10px;
}
.selectize-control.movies .selectize-dropdown .meta li {
margin: 0;
padding: 0;
display: inline;
margin-right: 10px;
}
.selectize-control.movies .selectize-dropdown .meta li span {
font-weight: bold;
}
.selectize-control.movies::before {
-moz-transition: opacity 0.2s;
-webkit-transition: opacity 0.2s;
transition: opacity 0.2s;
content: ' ';
z-index: 2;
position: absolute;
display: block;
top: 12px;
right: 34px;
width: 16px;
height: 16px;
background: url(images/spinner.gif);
background-size: 16px 16px;
opacity: 0;
}
.selectize-control.movies.loading::before {
opacity: 0.4;
}
</style>
</head>
<body>
<div id="wrapper">
<h1>Selectize.js</h1>
<div class="demo">
<h2>Loading from API</h2>
<p>This demo shows how to integrate third-party data, loaded asynchronously.</p>
<div class="control-group">
<label for="select-movie">Movie:</label>
<select id="select-movie" class="movies" placeholder="Find a movie..."></select>
</div>
<script>
// <select id="select-movie"></select>
$('#select-movie').selectize({
valueField: 'movies',
labelField: 'movies',
searchField: 'movies',
options: [],
create: false,
render: {
option: function(item, escape) {
return '<div>' +
'<span class="movies">' +
'<span class="name">' + escape(item.movies) + '</span>' +
'</span>' +
'</div>';
}
},
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
//url: 'http://api.rottentomatoes.com/api/public/v1.0/movies.json',
url:'http://localhost/selectize/examples/myphp.php?query='+ encodeURIComponent(query),
type: 'GET',
dataType: 'jsonp',
data: {
q: query,
//page_limit: 10,
//apikey: '3qqmdwbuswut94jv4eua3j85'
},
error: function() {
callback();
},
success: function(res) {
console.log(res);
callback(res);
alert(res);
}
});
}
});
</script>
</div>
</div>
</body>
</html>
But, now I am lost as to how to make this work. I know I am a newbie so, asking for help.
I have this code to push notification (GCM) but when i am trying to push notification i got null notification (the string of my message is missing)
index.php
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
});
function sendPushNotification(id){
var data = $('form#'+id).serialize();
$('form#'+id).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
<style type="text/css">
.container{
width: 950px;
margin: 0 auto;
padding: 0;
}
h1{
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 24px;
color: #777;
}
div.clear{
clear: both;
}
ul.devices{
margin: 0;
padding: 0;
}
ul.devices li{
float: left;
list-style: none;
border: 1px solid #dedede;
padding: 10px;
margin: 0 15px 25px 0;
border-radius: 3px;
-webkit-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.35);
-moz-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.35);
box-shadow: 0 1px 5px rgba(0, 0, 0, 0.35);
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
color: #555;
}
ul.devices li label, ul.devices li span{
font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
font-size: 12px;
font-style: normal;
font-variant: normal;
font-weight: bold;
color: #393939;
display: block;
float: left;
}
ul.devices li label{
height: 25px;
width: 50px;
}
ul.devices li textarea{
float: left;
resize: none;
}
ul.devices li .send_btn{
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#0096FF), to(#005DFF));
background: -webkit-linear-gradient(0% 0%, 0% 100%, from(#0096FF), to(#005DFF));
background: -moz-linear-gradient(center top, #0096FF, #005DFF);
background: linear-gradient(#0096FF, #005DFF);
text-shadow: 0 1px 0 rgba(0, 0, 0, 0.3);
border-radius: 3px;
color: #fff;
}
</style>
</head>
<body>
<?php
include_once 'db_functions.php';
$db = new DB_Functions();
$users = $db->getAllUsers();
if ($users != false)
$no_of_users = mysql_num_rows($users);
else
$no_of_users = 0;
?>
<div class="container">
<h1>No of Devices Registered: <?php echo $no_of_users; ?></h1>
<hr/>
<ul class="devices">
<?php
if ($no_of_users > 0) {
?>
<?php
while ($row = mysql_fetch_array($users)) {
?>
<li>
<form id="<?php echo $row["id"] ?>" name="" method="post" onsubmit="return sendPushNotification('<?php echo $row["id"] ?>')">
<label>Name: </label> <span><?php echo $row["name"] ?></span>
<div class="clear"></div>
<label>Email:</label> <span><?php echo $row["email"] ?></span>
<div class="clear"></div>
<div class="send_container">
<textarea rows="3" name="message" cols="25" class="txt_message" placeholder="Type message here"></textarea>
<input type="hidden" name="regId" value="<?php echo $row["gcm_regid"] ?>"/>
<input type="submit" class="send_btn" value="Send" onclick=""/>
</div>
</form>
</li>
<?php }
} else { ?>
<li>
No Users Registered Yet!
</li>
<?php } ?>
</ul>
</div>
</body>
</html>
send_message.php
<?php
if (isset($_GET["regId"]) && isset($_GET["message"])) {
$regId = $_GET["regId"];
$message = $_GET["message"];
include_once './GCM.php';
echo "in send message class";
$gcm = new GCM();
$registatoin_ids = array($regId);
$message = array("price" => $message);
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;
}
?>
GcmIntentService.java
package com.example.provenlogic1.myapplication;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.google.android.gms.gcm.GoogleCloudMessaging;
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
String TAG="pavan";
public GcmIntentService() {
super("GcmIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
Log.d("pavan","in gcm intent message "+messageType);
Log.d("pavan","in gcm intent message bundle "+extras);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM
* will be extended in the future with new message types, just ignore
* any message types you're not interested in, or that you don't
* recognize.
*/
if (GoogleCloudMessaging.
MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " +
extras.toString());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.
MESSAGE_TYPE_MESSAGE.equals(messageType)) {
String recieved_message=intent.getStringExtra("text_message");
sendNotification("message recieved :" +recieved_message);
Intent sendIntent =new Intent("message_recieved");
sendIntent.putExtra("message",recieved_message);
LocalBroadcastManager.getInstance(this).sendBroadcast(sendIntent);
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.common_signin_btn_text_disabled_dark)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
Any idea would be appreciated.
I'm having problems with this webcam plugin.
I can access the camera and thake the picture, however, cannot save it. When I click to record (Guardar Foto) it has no action
I'm going to show my code here.
My View
<html>
<head>
<title>WebCam</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<style type="text/css">
#content{
margin: 0 auto;
width: 1000px;
position: relative;
}
.fotografia{
width: 320px;
height: 240px;
border: 20px solid #333;
background: #eee;
-webkit-border-radius: 20px;
-moz-border-radius: 20px;
border-radius: 20px;
position: relative;
margin-top: 50px;
margin-bottom: 50px;
}
.marca {
z-index: 2;
position: absolute;
color: #eee;
font-size: 10px;
bottom: -16px;
left: 152px;
}
#obturador,#guardarFoto{
padding: 10px;
border: 1px solid;
background-color: #444;
color: #fff;
cursor: pointer;
margin-left: 50px;
}
</style>
</head>
<body>
<div id="content">
<div style="float:left;width:50%">
<div id="webcam" class="fotografia">
<span class="marca">tutoriales.com</span>
</div>
</div>
<div style="float:left;width:50%">
<div id="say-cheese-snapshots" class="fotografia">
<span class="marca">Snapshots</span>
</div>
</div>
<div style="clear:both"></div>
<div style="float:left;width:50%">
<span id="obturador">Tomar foto</span>
</div>
<div style="float:left;width:50%">
<span id="guardarFoto">Guardar Foto</span>
</div>
<div class="fotografia">
<img id="fotoGuardada" src="" style="display:none" />
<span class="marca">Foto Armazenada</span>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script src="<?php echo base_url() ?>assets/js/say-cheese.js"></script>
<script type="text/javascript">
var img=null;
var sayCheese = new SayCheese('#webcam',{snapshots: true});
sayCheese.start();
$('#obturador').bind('click', function(e){
sayCheese.takeSnapshot(320,240);
return false;
})
sayCheese.on('snapshot', function(snapshot){
img = document.createElement('img');
$(img).on('load', function(){
$('#say-cheese-snapshots').html(img);
});
img.src = snapshot.toDataURL('image/png');
});
$('#guardarFoto').bind('click', function(){
var src = img.src;
data = {
src: src
}
$.ajax({
url: '<?php echo base_url() ?>webcam/ajax',
data: data,
type: 'post',
sucess: function(respuesta) {
$('#fotoGuardada').attr('src', respuesta).show(500);
}
});
});
</script>
</body>
Now my Model
<?php
class Fotos_model extends CI_Model{
public function gravarFoto($foto) {
return $this->db->insert('fotos',array('foto'=>$foto));
}
public function getLastFoto() {
return $this->db->order_by('id','desc')->get('fotos')->row()->foto;
}
}
And my Controller
<?php
class Webcam extends CI_Controller{
public function __construct() {
parent::__construct();
$this->load->model(array('Fotos_model'));
}
public function index() {
$this->load->view('webcam/index_view');
}
public function ajax () {
$src = $this->input->post('src');
$this->Fotos_model->gravarFoto($src);
$foto = $this->Fotos_model->getLastFoto();
$this->output->set_output ($foto);
}
}
Syntax error: You are missing a semicolon at the end of
data = {src: src}
Should be
data = {src: src};
Your error is because field id must to be: key & autoincrement:
I am making a chat box in codeigniter, but after enter the name and message, pop up box is coming showing 'Forbidden'.
I am really confused what I put instead shout.php here(chatbox.php')
$.post('shout.php', load_data, function(data) {
instead of 'shout.php' I put http://localhost/myfoldername/application/views/shout.php
my controller
money_c
function chat(){
$this->load->view('chatbox');
}
chatbox.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Chat Box</title>
<style type="text/css">
<!--
.shout_box {
background: #627BAE;
width: 260px;
overflow: hidden;
position: fixed;
bottom: 0;
right: 20%;
z-index:9;
}
.shout_box .header .close_btn {
background: url(images/close_btn.png) no-repeat 0px 0px;
float: right;
width: 15px;
height: 15px;
}
.shout_box .header .close_btn:hover {
background: url(images/close_btn.png) no-repeat 0px -16px;
}
.shout_box .header .open_btn {
background: url(images/close_btn.png) no-repeat 0px -32px;
float: right;
width: 15px;
height: 15px;
}
.shout_box .header .open_btn:hover {
background: url(images/close_btn.png) no-repeat 0px -48px;
}
.shout_box .header{
padding: 5px 3px 5px 5px;
font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif;
font-weight: bold;
color:#fff;
border: 1px solid rgba(0, 39, 121, .76);
border-bottom:none;
cursor: pointer;
}
.shout_box .header:hover{
background-color: #627BAE;
}
.shout_box .message_box {
background: #FFFFFF;
height: 200px;
overflow:auto;
border: 1px solid #CCC;
}
.shout_msg{
margin-bottom: 10px;
display: block;
border-bottom: 1px solid #F3F3F3;
padding: 0px 5px 5px 5px;
font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif;
color:#7C7C7C;
}
.message_box:last-child {
border-bottom:none;
}
time{
font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif;
font-weight: normal;
float:right;
color: #D5D5D5;
}
.shout_msg .username{
margin-bottom: 10px;
margin-top: 10px;
}
.user_info input {
width: 98%;
height: 25px;
border: 1px solid #CCC;
border-top: none;
padding: 3px 0px 0px 3px;
font: 11px 'lucida grande', tahoma, verdana, arial, sans-serif;
}
.shout_msg .username{
font-weight: bold;
display: block;
}
-->
</style>
<script type="text/javascript" src="<?php echo base_url();?>assets/js/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// load messages every 1000 milliseconds from server.
load_data = {'fetch':1};
window.setInterval(function(){
$.post('shout.php', load_data, function(data) {
$('.message_box').html(data);
var scrolltoh = $('.message_box')[0].scrollHeight;
$('.message_box').scrollTop(scrolltoh);
});
}, 1000);
//method to trigger when user hits enter key
$("#shout_message").keypress(function(evt) {
if(evt.which == 13) {
var iusername = $('#shout_username').val();
var imessage = $('#shout_message').val();
post_data = {'username':iusername, 'message':imessage};
//send data to "shout.php" using jQuery $.post()
$.post('shout.php', post_data, function(data) {
//append data into messagebox with jQuery fade effect!
$(data).hide().appendTo('.message_box').fadeIn();
//keep scrolled to bottom of chat!
var scrolltoh = $('.message_box')[0].scrollHeight;
$('.message_box').scrollTop(scrolltoh);
//reset value of message box
$('#shout_message').val('');
}).fail(function(err) {
//alert HTTP server error
alert(err.statusText);
});
}
});
//toggle hide/show shout box
$(".close_btn").click(function (e) {
//get CSS display state of .toggle_chat element
var toggleState = $('.toggle_chat').css('display');
//toggle show/hide chat box
$('.toggle_chat').slideToggle();
//use toggleState var to change close/open icon image
if(toggleState == 'block')
{
$(".header div").attr('class', 'open_btn');
}else{
$(".header div").attr('class', 'close_btn');
}
});
});
</script>
</head>
<body>
<div class="shout_box">
<div class="header">chat box<div class="close_btn"> </div></div>
<div class="toggle_chat">
<div class="message_box">
</div>
<div class="user_info">
<input name="shout_username" id="shout_username" type="text" placeholder="Your Name" maxlength="15" />
<input name="shout_message" id="shout_message" type="text" placeholder="Type Message Hit Enter" maxlength="100" />
</div>
</div>
</div>
</body>
</html>
shout.php
<?php
####### db config ##########
$db_username = 'root';
$db_password = '';
$db_name = 'money1';
$db_host = 'localhost';
####### db config end ##########
if($_POST)
{
//connect to mysql db
$sql_con = mysqli_connect($db_host, $db_username, $db_password,$db_name)or die('could not connect to database');
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
die();
}
if(isset($_POST["message"]) && strlen($_POST["message"])>0)
{
//sanitize user name and message received from chat box
//You can replace username with registerd username, if only registered users are allowed.
$username = filter_var(trim($_POST["username"]),FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
$message = filter_var(trim($_POST["message"]),FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);
$user_ip = $_SERVER['REMOTE_ADDR'];
//insert new message in db
if(mysqli_query($sql_con,"INSERT INTO shout_box(user, message, ip_address) value('$username','$message','$user_ip')"))
{
$msg_time = date('h:i A M d',time()); // current time
echo '<div class="shout_msg"><time>'.$msg_time.'</time><span class="username">'.$username.'</span><span class="message">'.$message.'</span></div>';
}
// delete all records except last 10, if you don't want to grow your db size!
mysqli_query($sql_con,"DELETE FROM shout_box WHERE id NOT IN (SELECT * FROM (SELECT id FROM shout_box ORDER BY id DESC LIMIT 0, 10) as sb)");
}
elseif($_POST["fetch"]==1)
{
$results = mysqli_query($sql_con,"SELECT user, message, date_time FROM (select * from shout_box ORDER BY id DESC LIMIT 10) shout_box ORDER BY shout_box.id ASC");
while($row = mysqli_fetch_array($results))
{
$msg_time = date('h:i A M d',strtotime($row["date_time"])); //message posted time
echo '<div class="shout_msg"><time>'.$msg_time.'</time><span class="username">'.$row["user"].'</span> <span class="message">'.$row["message"].'</span></div>';
}
}
else
{
header('HTTP/1.1 500 Are you kiddin me?');
exit();
}
}
but after entering name and message alert box will pop up showing 'Forbidden'.
I don't think you fully grasp MVC architecture and this is not really the place to explain it.
I suggest you study it more but what may work for you here is to modify your controller function to this:
function chat(){
$this->load->view('chatbox');
}
function shout(){
$this->load->view('shout');
}
You would then need to ensure that the URL(route) works.
Assume you current URL is www.mysite.com/someController/chat/
then the new URL would be www.mysite.com/someController/shout/
If this URL does not work then you would need to sort out your route to make it work.
If this URL works, then you need to update your JQuery URL from
.post('shout.php', load_data, function(data) {
to
.post('/someController/shout/', load_data, function(data) {
TL;DR
The jquery post function accesses the fule via the URL like a real person. It cannot load the file directly.
I am made a instant search feature for my website as you can see here: harrisonbh.com/chatterr/instant_search/ but the search results just push down the content.
index.php
<html>
<head>
<title>Search Box</title>
<link rel="stylesheet" href="style.css"/>
<script src="../js/jquery-1.9.1.js"></script>
<script src="index.js"></script>
</head>
<body>
<?php
//include 'connect.php';
include '../core/database/connect.php';
?>
<span id="box">
<input type="text" id="search_box"><button id="search_button">Search</button>
</span>
<div id="search_result">
</div>
Rest of content
</body>
</html>
index.js
$(document).ready(function(){
var left = $('#box').position().left;
var top = $('#box').position().top;
var width = $('#box').width();
$('#search_result').css('left', left).css('top', top+32).css('width', width);
$('#search_box').keyup(function(){
var value = $(this).val();
if(value != ''){
$('#search_result').show();
$.post('search.php', {value: value}, function(data){
$('#search_result').html(data);
});
} else {
$('#search_result').hide();
}
});
});
search.php
<?php
//include 'connect.php';
include '../core/database/connect.php';
$value = $_POST['value'];
$search_query = mysql_query("SELECT username FROM users WHERE username LIKE '$value%'");
while ($run = mysql_fetch_array($search_query)){
$username = $run['username'];
echo '<a href=#>'.$username.'</a><br/>';
}
?>
body{
font-family: arial;
font-size: 12px;
color: #333;
background:#fff;
}
input{
padding: 5px;
border: 0px;
font-family: arial;
font-size: 12px;
color: #333;
background:#fff;
box-shadow: 0 0 5px rgba(210, 210, 210, 210);
}
button{
padding: 5px;
border: 0px;
font-family: arial;
font-size: 12px;
color: #fff;
background:#4aaee7;
/*box-shadow: 0 0 5px rgba(210, 210, 210, 210);*/
}
button:hover{
background:#fff;
color: #333;
box-shadow: 0 0 5px rgba(210, 210, 210, 210);
cursor: pointer;
}
#search_result{
}
/*#search_result {
font-size: 12px;
padding: 5px;
box-shadow: 0 0 5px rgba(210, 210, 210, 210);
background: #fff;
color: #333;
position: absolute;
display: none;
}*/
a {
background:#4aaee7;
color: #fff;
text-decoration: none;
padding: 5px;
margin-top: 5px;
margin-bottom: -14px;
display: block;
}
a:hover{
background: #fff;
color: #4aaee7;
}
ul {
margin: 0px;
padding: 0px;
list-style: none;
}
li {
padding: 5px;
}
I'm not sure if i should be using position: absolute; or what to fix this. What do you think that I should do? Thanks.
Just enclose you input text field and search button in <div style="float:left;">
I mean, like this:
<div style="float:left;">
<span id="box">
<input type="text" id="search_box"><button id="search_button">Search</button>
</span>
<div id="search_result">
</div>
</div>