Input sends empty message - php

I'm making live chatter for my project, and I need this script to recognize this:
If clientmsg is empty, it will call out an error and won't post the
message.
If clientmsg has more than 3 or 4 chars (letters) - it will post the message.
The code:
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
$.post("post3.php", {text: clientmsg});
$("#usermsg").attr("value", "");
return false;
});
I can't find out how this works.
Here you can see the whole code for it.
index.php
<?php
/*****************************
File: index.php
Written by: exZerry development crew
******************************/
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
echo "";
} else {
header ("Location: login.php");
}
require('includes/config.php');
echo $sOutput;
if(isset($_POST['enter'])){
if($_POST['username'] != ""){
$_SESSION['username'] = stripslashes(htmlspecialchars($_POST['username']));
}
else{
echo '<span class="error">Please type in a name</span>';
}
}
?>
<style type="text/css">
input {
font: 12px;
}
.loginbox {
background-image: url(bar.png);
width: 100%;
height: 100%;
margin-top: -38;
}
#loginform {
font:16px dinpro;
color: #ffffff;
margin-top: 100;
}
#hedthe {
background-image: url(spacer.png);
font-family: bank-gt, sans-serif;
font-size: 34;
width: 830;
height: 34;
font-weight: normal;
}
#thereis {
magrin-top: -20;
}
#chatbox {
text-align: justify;
height: 70%;
width: 100%;
overflow: auto;
opacity: 0.91;
}
#usermsg {
width: 100%;
font-family: Play, sans-serif;
font-size: 14;
font-weight: normal;
color: #ffffff;
border: 0px solid black;
text-indent: 5px;
height: 32;
margin-top: 5px;
border: 0px solid black;
color: #ffffff;
background-image: url(chatinp.png);
}
input {
opacity: 0.7;
}
#submitmsg {
background-color: #48513e;
width: 0;
height: 0;
font-size: 20;
font-weight: normal;
color: #ffffff;
text-align: left;
border: 0px solid black;
}
.error {
color: #000000;
}
#menu {
margin-right: 0;
}
.welcome {
float:left;
}
.logout {
float:right;
}
.msgln {
margin-right: 0;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="modules/chatbox.js"></script>
<!-- Actual chat -->
<div id="chatbox">
<?php
if(file_exists("tmp/log.html") && filesize("tmp/log.html") > 0){
$handle = fopen("tmp/log.html", "r");
$contents = fread($handle, filesize("tmp/log.html"));
fclose($handle);
echo $contents;
}
?>
</div>
<form name="message" action="" id="sender" class="sender">
<input name="usermsg" id="usermsg" class="required" type="text" placeholder="Your message here" maxlength="60"/>
<input name="submitmsg" type="submit" id="submitmsg" width="0" height="0"/>
</form>
chatbox.js file
// jQuery Document
$(document).ready(function(){
//If user submits the form
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
$.post("post3.php", {text: clientmsg});
$("#usermsg").attr("value", "");
return false;
});
//Load the file containing the chat log
function loadLog(){
var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
$.ajax({
url: "tmp/log.html",
cache: false,
success: function(html){
$("#chatbox").html(html); //Insert chat log into the #chatbox div
var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
if(newscrollHeight > oldscrollHeight){
$("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
}
},
});
}
setInterval (loadLog, 2000); //Reload file every 3 seconds
});
post3.php file
<?
session_start();
if(isset($_SESSION['username'])){
$text = $_POST['text'];
$fp = fopen("tmp/log.html", 'a');
fwrite($fp, "<div class='msgln'> <b>".$_SESSION['username']."</b>: ".stripslashes(htmlspecialchars($text))."<br></div>");
fclose($fp);
}
?>
This is full js + php chatter.

Like this?
$("#submitmsg").click(function(){
var clientmsg = $.trim($("#usermsg").val());
if(clientmsg.length >= 3){
$.post("post3.php", {text: clientmsg});
$("#usermsg").val("");
}else{
alert('error');
}
return false;
});

$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
// check if the length of the string is greater than 3 letters
if(clientmsg.length > 3)
$.post("post3.php", {text: clientmsg});
else
alert("Error");
$("#usermsg").attr("value", "");
return false;
});

Related

Updating SQL 'WHERE' based on JSON AJAX checkbox selection

I have an AJAX HTML page and a submit PHP page, which sends data from SQL to update HTML on page.
I have a list of films within a PHPMyAdmin MariaDB table. One of the columns is "channel". Channel will either say "NOWTV", "BBC", or "SKYTV". I want the user to be able to select the channel and for this to update.
If I check the array for 1 string - for example: skytv, the SQL pulls the data. However, if I want to change the WHERE clause, based on selection - the filtering does not work.
I've tried ".=where OR" to change the channel selection.
ajax.html
<html>
<style>
body {
padding: 10px;
}
h2 {
margin: 1em 0 0.3em 0;
color: #343434;
font-weight: normal;
font-size: 30px;
line-height: 40px;
font-fnuamily: 'Orienta', sans-serif;
}
#employees {
font-family: "Lucida Sans Unicode","Lucida Grande",Sans-Serif;
font-size: 12px;
background: #fff;
margin: 10px 10px 0 0;
border-collapse: collapse;
text-align: center;
float: left;
width: 100%;
}
#employees th {
font-size: 14px;
font-weight: normal;
color: #039;
padding: 4px 4px;
border-bottom: 1px solid #6678b1;
}
#employees td {
border-bottom: 1px solid #ccc;
color: #669;
padding: 8px 10px;
}
#employees tbody tr:hover td {
color: #009;
}
.slidecontainer {
width: 50%; /* Width of the outside container */
}
/* The slider itself */
.slider {
-webkit-appearance: none; /* Override default CSS styles */
appearance: none;
width: 50%; /* Full-width */
height: 25px; /* Specified height */
background: #d3d3d3; /* Grey background */
outline: none; /* Remove outline */
opacity: 0.7; /* Set transparency (for mouse-over effects on hover) */
-webkit-transition: .2s; /* 0.2 seconds transition on hover */
transition: opacity .2s;
}
/* Mouse-over effects */
.slider:hover {
opacity: 1; /* Fully shown on mouse-over */
}
.slider::-webkit-slider-thumb {
-webkit-appearance: none; /* Override default look */
appearance: none;
width: 25px; /* Set a specific slider handle width */
height: 25px; /* Slider handle height */
background: #000000; /* Square background */
cursor: pointer; /* Cursor on hover */
}
.slider::-moz-range-thumb {
width: 25px; /* Set a specific slider handle width */
height: 25px; /* Slider handle height */
background: #4CAF50; /* Green background */
cursor: pointer; /* Cursor on hover */
}
</style>
</head>
<body>
<input type="checkbox" id="nowtv" name="nowtv" >
<label for="nowtv">Now TV</label>
</div>
<div>
<input type="checkbox" id="skytv" name="skytv" >
<label for="skytv">Sky Movies</label>
</div>
<div>
<input type="checkbox" id="iplayer" name="iplayer" >
<label for="iplayer">BBC iPlayer</label>
</div>
<h2>Max Run-Time:</h2>
<div class="slidecontainer">
<input type="range" min="0" max="200" value="0" class="slider" id="runtime">
<p>Runtime: <span id="runtime_"></span></p>
</div>
<table id="employees">
<tbody>
</tbody>
</table>
<script>
var slider = document.getElementById("runtime");
var output = document.getElementById("runtime_");
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = this.value;
}
/script>
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<p id="record_count"></p>
<script>
function makeTable(data){
var tbl_body = "";
for (var i = 0; i < data.length; i++)
{
var tbl_row = "";
var t = i;
for (var j=0; j<4; j++)
{
//tbl_row +=("<td>" + data[i].tmdbid + "</td>");
tbl_row +=("<td><a href='new/" + data[i].tmdbid + "'><IMG SRC='webaddress"+ data[i].poster +"'></a></td>");
i++;
}
tbl_body += "<tr>"+tbl_row+"</tr>"
}
return tbl_body;
}
function getEmployeeFilterOptions(){
var opts = {
checkboxes: [],
sliderValue: null
};
$checkboxes.each(function(){
if(this.checked){
opts.checkboxes.push(this.name);
}
});
var slider = document.getElementById("runtime");
opts.sliderValue = slider.value;
return opts;
}
function updateEmployees(opts){
$.ajax({
type: "POST",
url: "submit.php",
dataType : 'json',
cache: false,
data: opts,
success: function(records){
console.log(records);
$('#employees tbody').html(makeTable(records));
}
});
}
var $checkboxes = $("input");
$checkboxes.on("change", function(){
var opts = getEmployeeFilterOptions();
updateEmployees(opts);
});
</script>
</body>
</html>
submit.php
<?php
$pdo = new PDO(
'mysql:host=xxxxxxxx;dbname=xxxxxxxx', 'xxxxxxxx', 'xxxxxxxx'
);
$checkboxes = $_POST["checkboxes"];
$slider_value = $_POST["sliderValue"];
$select = 'SELECT *';
$from = ' FROM streaming';
$where = ' WHERE poster <>"" AND runtime <' . $slider_value . ' AND channel = "X" ';
if (in_array("nowtv", $checkboxes))
{
$where .= ' OR channel = "NOWTV" ';
}
if (in_array("skytv", $checkboxes))
{
$where .= ' OR channel = "SKYTV" ';
}
if (in_array("iplayer", $checkboxes))
{
$where .= ' OR channel = "BBC" ';
}
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
>
The output I am expecting is for the user to be able to select the checkboxes and runtime - to then update the films available.
The current output shows nothing. :(

how to open multiple modal click on id?

code:
<style>
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
</style>
<script>
var modal = document.getElementById('myModal');
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
<?php
$sql = "select * from enquires2";
$result = mysqli_query($link,$sql);
while ($row = mysqli_fetch_array($result))
{
?>
<tr>
<td>
<span><img src='gridview/view.png' alt='View' id='myBtn<?php echo $row['id']; ?>'></span>
</td>
</tr>
<div id='myModal' class='modal'>
<div class='modal-content'>
<span class='close'>×</span>
<p>Some text in the Modal..</p>
</div>
</div>
<?php
}
?>
In this code when I click on id i.e.
id='myBtn<?php echo $row['id']; ?>'
it display only one modal but when I click on new row id it show nothing. so, I want to open multiple modal with different row id. How can I fix this issue ? please help.
Thank You

PHP chat censorship

I have a chat on my website, but it doesn't have accounts, so cursing is rampant. I use PHP to write all of my data to user.txt. Is there a simple filter for mindless cursing in php? Because this js I use doesn't seem to work too well:
$(function() {
$("input:submit[name='submit']").on("click",function() {
var name = $("input:text[name='name']").val();
var message = $("input:text[name='field2']").val();
var badwords = ["dingbat", "poopy"];
/* do this */
if($.inArray(name, badwords) !==-1 || $.inArray(message, badwords) !==-1) {
alert("Your Message Contains Bad Words, Please Remove Them Before Proceeding");
return false;
}
});
});
Here is my full code (minus txt.php which just displays user.txt)
#import url(https://fonts.googleapis.com/css?family=Lato:400,100,300);
#blu {
background: #F0FAFF;
padding: 3;
width: 310;
}
b, i, p {
-webkit-transition: all 0.5s ease;
font-size: 16px;
font-size: 1rem;
line-height: 23px;
line-height: 1.4375rem;
font-weight: 400;
font-style: normal;
font-family:"Lato";
}
iframe{border: 3px solid white;}
button,input, #rcp_submit, #rcp_update_card {
display: inline-block;
font-family: "Lato", sans-serif;
font-weight: 500;
outline: 0;
border-radius: 0;
color: black;
background: #FFFFFF;
white-space: nowrap;
padding: 9px 16px !important;
line-height: 1.4;
border: 0;
color:black;
position: relative;
-webkit-transition: 0.1s;
transition: 0.1s;
}
,!--this file is called c5.php-->
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "<br>";
$ret = file_put_contents('user.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file<a href ='javascript:history.go(-1)'>go back</a>";
}
}
else {
die('no post data to process');
}
?>
<html>
<body onload="reloadIFrame();">
<script>
window.setInterval("reloadIFrame();", 3000);
function reloadIFrame() {
document.getElementById("myIframe").src="txt.php";
}
</script>
<div id ="blu">
<table>
<p>Chat about your code</p>
<td>
<iframe src ="txt.php" id ="myIframe"></iframe><br/>
<button onclick="reloadIFrame();">Refresh feed</button>
<form action="c5.php" method="POST">
<p>Name:</p>
<input name="field1" type="text" />
<h3> </h3>
<p>Question:<p>
<input name="field2" type="text" />
<input type="submit" name="submit" value="Submit">
</form>
download chat logs
</td>
</table>
</div>
let's take a look at why your js was not working
You are matching a whole sentence for a word .
here is an example if the var name is BADWORD SOMEONE_BADWORD
what you are searching if the array holds that value (BADWORD SOMEONE_BADWORD)
so what you should do is split the sentence into it's basic component words
name.split(/[(\s|_)]/) // split the name by white space or underscore
now you will have an array of
["BADWORD", "SOMEONE", "BADWORD"]
and the code becomes:
$(function() {
function containBadWord(words , banlist){
var bad = false;
$.each(words , function(k , v){
if($.inArray(v, banlist) !==-1){
bad = true;
return false;
}
});
return bad;
}
$("input:submit[name='submit']").on("click",function() {
var name = $("input:text[name='']").val();
var name_split = name.split(/[(\s|_)]/);
var message = $("input:text[name='field2']").val();
var message_split = message .split(/[(\s|_)]/);
var badwords = ["dingbat", "poopy"];
/* do this */
if(containBadWord(name_split , badwords )){
alert("your name has bad words")
}
if(containBadWord(message_split , badwords )){
alert("your messagehas bad words")
}
});
});
edit :
the code above was not working because your jquery selectors are all wrong as well .
`input:text[name='']` will select an input with an empty attribute of `name`
here is working code
https://jsfiddle.net/tq7odeLg/
I tried this, and it worked:
<?php
$find=array('bad','word','words');
$replace=array('...','...','...');
if(isset($_POST['user_input'])&&!empty($_POST['user_input']))
$data = $_POST['name'] . '-' . $_POST['user_input'] . "<br>";
$ret = file_put_contents('user.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
}
{
$user_input=$_POST['user_input'];
$user_input_new=str_ireplace($find,$replace,$user_input);
}
?>
<p> <?php
$text = file_get_contents('user.txt');
echo $text;
?>
</p>
<style>
#import url(https://fonts.googleapis.com/css?family=Lato:400,100,300);
b, i, p {
-webkit-transition: all 0.5s ease;
font-size: 16px;
font-size: 1rem;
line-height: 23px;
line-height: 1.4375rem;
font-weight: 400;
font-style: normal;
font-family:"lato";
}
</style>
<hr>
<form action="ws.php" method="POST">
<p>name:</p><input name ="name" type ="text"></input><br/>
<p>comment:</p><br/><textarea name="user_input" rows="6" col="30">
</textarea><br/>
<input type="Submit" value="Submit">
</form>
</form>

codeigniter chat box is not working

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.

Send values from one PHP file to another with JavaScript/AJAX

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.

Categories