chat app with user typing partly working - php

This code works very well for chatting. I have added ajaxcall.php for real time notification. The problem is; instead of displaying a typing notification when other users are typing, it will be displaying myself whenever am typing.please how do i make it to show other users typing.
index.php
<?php
ob_start();
?>
<?php
session_start();
?>
<!doctype>
<html>
<head>
<title>Chat</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<script type="text/javascript" src="jscolor.js"></script>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function() {
$.ajaxSetup(
{
cache: false,
beforeSend: function() {
$('#messages').hide();
$('#messages').show();
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
},
complete: function() {
$('#messages').hide();
$('#messages').show();
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
},
success: function() {
$('#messages').hide();
$('#messages').show();
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
}
});
var $container = $("#messages");
$container.load('ajaxload.php?id=<?php echo htmlentities( $_GET['id'], ENT_QUOTES, "UTF-8"); ?>');
var refreshId = setInterval(function()
{
$container.load('ajaxload.php?id=<?php echo htmlentities( $_GET['id'], ENT_QUOTES, "UTF-8"); ?>');
}, 3000);
$("#userArea").submit(function() {
$.post('ajaxPost.php', $('#userArea').serialize(), function(data) {
$("#messages").append(data);
$("#messages").animate({"scrollTop": $('#messages')[0].scrollHeight}, "slow");
document.getElementById("output").value = "";
});
return false;
});
});
</script>
<!--Ajax Server Call-->
<script>
function getAjaxFromServer(str){
if (str.length==0){
document.getElementById("ajaxResponse").innerHTML="";
return;
}
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("ajaxResponse").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",'ajaxcall.php?id=<?php echo htmlentities( $_GET['id'], ENT_QUOTES, "UTF-8"); ?>',true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="chatwrapper">
<!--display-->
<!--http://www.youtube.com/watch?v=FyXeOX-uYMc-->
<div id="messages"></div>
<!--post-->
<form id="userArea">
<div id="usercolor">
<input name="reciever" type="hidden" value="<?php echo htmlentities($_GET['id'], ENT_QUOTES, "UTF-8");?>"><br>
<input name="text" class="color" id="text" maxlength="6" value="000000" />
</div>
<div id="messagesntry">
<textarea id="output" name="messages" placeholder="Message" onkeyup="getAjaxFromServer(this.value)"/></textarea>
</div>
<div id="messagesubmit">
<input type="submit" value="Post message" id="submitmessage" />
</div>
</form>
</div>
</body>
</html>
ajaxload.php
<?php
ob_start();
?>
<?php
session_start();
?>
<?php
include('connect.php');
$id=$_GET['id'];
$result = $db->prepare("SELECT * FROM messages ORDER BY id ASC");
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
echo '<div style="color:'.$row['textcolor'].'">' .$row['user'] . ' : '. $row['message'] .'</div>';
}
?>
ajaxcall.php
<?php
ob_start();
?>
<?php
session_start();
?>
<?php
$txt=strip_tags($_GET['id']);
$txt1=strip_tags($_SESSION['SESS_MEMBER_ID']);
echo $txt;
echo " is typing ";
?>

The idea is to store a flag on a database and have an a .setTimeOut on your script on which will run whenever your field flag turns from 0 to 1
here is the code snippet to try
$('#txt_message').keyup(function(){
// Start a flag loop with an id of 'loop' and a counter.
var i = 1;
var dataString = 'flag='+ i ;
$.ajax({
type: "POST",
url: "notif.php",
data: dataString,
cache: false,
success: function(url){
}
});
this snippet will update your database whenever you type on your text field
var timer;
function AjaxRetrieve()
{
$.get("type_on.php?flag=0",function(data)
{
window.clearTimeout(timer);
$("#typing_on").html(data);
timer=window.setTimeout(function(){AjaxRetrieve()},3100);
});
}
timer=window.setTimeout(function(){AjaxRetrieve()},1300);
this snippet will be the one to update your flag after a few seconds

Related

Submit form using Ajax/Jquery and check result?

I am wanting to submit a form using ajax to go to my page 'do_signup_check.php'.
There it will check the email address the user entered against the database to see if there is a match.
If there is a match I want my ajax form to redirect the user to the login.php page.
If there isn't a match I want it to load my page 'do_signup.php'
for some reason the code seems to be doing nothing. Please can someone show me where I am going wrong?
My Ajax form:
<html lang="en">
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
</script>
<?php include 'assets/config.php'; ?>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'do_signup_check.php',
data:{"name":name,"email":email},
success: function () {
if(result == 0){
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('do_signup.php',function(){}).hide().fadeIn(500);
});
}else{
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('login.php',function(){}).hide().fadeIn(500);
}
});
});
});
</script>
</head>
<body>
<div class="sign_up_contain">
<div class="container">
<div class="signup_side">
<h3>Get Onboard.</h3>
<h6>Join the directory.</h6>
<form id="signup" action="" method="POST" autocomplete="off" autocomplete="false">
<div class="signup_row action">
<input type="text" placeholder="What's your Name?" name="name" id="name" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<input type="text" placeholder="Got an Email?" name="email" id="email" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<div class="g-recaptcha" style="margin-top:30px;" data-sitekey="6LeCkZkUAAAAAOeokX86JWQxuS6E7jWHEC61tS9T"></div>
<input type="submit" class="signup_bt" name="submit" id="submt" value="Create My Account">
</div>
</form>
</div>
</div>
</div>
</body>
</html>
My Do_Signup_Check.php page:
<?php
session_start();
require 'assets/connect.php';
$myName = $_POST["name"];
$myEmail = $_POST["email"];
$check = mysqli_query($conn, "SELECT * FROM user_verification WHERE email='".$myEmail."'");
if (!$check) {
die('Error: ' . mysqli_error($conn));
}
if (mysqli_num_rows($check) > 0) {
echo '1';
} else {
echo '0';
}
?>
Try to use input id 'submt' to trigger the form as such :
$("#submt").click(function(){
e.preventDefault();
//your logic
You have not included the jquery in your page, the function is also missing the closing parentheses.
Include the jquery at the top
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Replace your function with the following code:-
<script>
$(function () {
$('form').on('submit', function (e) {alert(123);
e.preventDefault();
$.ajax({
type: 'post',
url: 'receive-callback.php',
data:{"name":name,"email":email},
success: function () {
if(result == 0){
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('do_signup.php',function(){}).hide().fadeIn(500);
});
}else{
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('login.php',function(){}).hide().fadeIn(500);
});
}
}
});
});
});
</script>
After receiving success in Ajax and doing all necessary logic (fadeOut etc) just relocate user to login.php:
window.location.href = 'path/to/login.php';
Otherwise, in error function (it is goes just after success function) do the next:
window.location.href = 'path/to/do_signup.php';
Upd:
In case you want to have some piece of code from another file, you can use jQuery method load.
$('#some-selector').load('path/to/course/login.php');
It's a very basic example of using 'load', go google around it to explore more.
Please Try this code.
$.ajax({
type: 'post',
url: 'do_signup_check.php',
data:{"name":name,"email":email},
success: function (result) {
if(result == 0){
window.location.href = 'do_signup.php';
}else{
window.location.href = 'login.php';
}
});
My Do_Signup_Check.php page:
<?php
session_start();
require 'assets/connect.php';
$myName=$_POST["name"];
$myEmail=$_POST["email"];
$check = mysqli_query($conn, "SELECT * FROM user_verification WHERE email='".$myEmail."'");
if (!$check) {
die('Error: ' . mysqli_error($conn));
}
if(mysqli_num_rows($check) > 0){
echo json_encode(array('result'=>'1'));
exit;
}else{
echo json_encode(array('result'=>'0'));
exit;
}
?>
I hope this will work for you.

How to trigger a colorbox gallery with form submit

I have a document with two pages. The first one sends a folder name via form submit
<form method="post" >
<input type="hidden" name="portfolio" value="directory">
<input type="submit" value="author">
</form>
the second one receives this folder name and open the files with glob function
<?php
header('Content-Type: application/json');
$directoryName = $_POST['portfolio'];
echo json_encode (glob($directoryName."/".'*.{jpg,mp4}', GLOB_BRACE));
?>
...finally images appear on the first page again via Ajax
$(document).ready(function(){
$('form').submit(function(e) {
var data = $(this).serialize();
e.preventDefault();
$.ajax({
url: "PAGE2.php",
data: data,
type: "POST",
dataType: "json",
success: function(response) {
var html = "";
$.each(response, function(i, val) {
var fileExtension = val.substring(val.lastIndexOf('.'));
if (fileExtension == ".jpg") {
html += '<img src="'+val+'" height=250></img>';
}
else if (fileExtension == ".mp4") {
html += '<video width="320" height="240" src="'+val+'" type="video/mp4"controls autoplay loop></video>';
}
});
$("#display").html(html);
}
});
});
});
up to here no href tags...
I need to know how to display images like modal gallery with colorbox plugin.
I've tried this without success
$(document).ready(function(){
$('form').submit(function(e) {
var data = $(this).serialize();
e.preventDefault();
$.ajax({
url: "PAGE2.php",
data: data,
type: "POST",
dataType: "json",
success: function(response) {
var html = "";
$.each(response, function(i, val) {
var fileExtension = val.substring(val.lastIndexOf('.'));
if (fileExtension == ".jpg") {
html += '<img src="'+val+'" height=250></img>';
}
else if (fileExtension == ".mp4") {
html += '<video width="320" height="240" src="'+val+'" type="video/mp4"controls autoplay loop></video>';
}
});
$("#display").html(html);
$("#link").colorbox({ inline:true, href: "#display"});
}
});
});
});
<body>
...
<div id="display" style="display:none;"></div>
<a id="link" style="display:none"></a>
</body>
PAGE1.php
<!DOCTYPE HTML>
<html lang="">
<head>
    <meta charset="UTF-8">
    <title>page1</title>
<link rel="stylesheet" href="colorbox.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="../jquery.colorbox.js"></script>
<script>
$(function() {
$("#formID").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), function(data) {
$.colorbox({
html:data,
rel:'group1'
});
},
'html');
return false;
});
});
</script>
</head>
<body>
<div class="container">
<form action="page2.php" method="post" id="formID">
<input type="hidden" name="var" value="directory">
<input type="submit" value="author">
</form>
</div>
</body>
</html>
PAGE2.php
<!DOCTYPE HTML>
<html lang="">
<head>
<meta charset="UTF-8">
<title>page2</title>
</head>
<body>
<?php
$variable = $_POST['var'];
$img_dir = $variable . "/";
foreach(glob($img_dir . '*.jpg') as $image) {
echo '<img src="'.$image.'">'.'<img class="group">';
}
?>
</body>
</html>

how to submit the form without refreshing the page

this is my html code when i click on submit button it displays alert and then when i open the retrieveform.php it does not show me the value please solve this mystery
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'retrieveform.php',
data: $('form').serialize(),
success: function () {
alert('helllo');
}
});
});
});
</script>
</head>
<body>
<form>
<input type="text"name="t1">
<input type="submit"name="s1"value="submit">
</form>
</body>
</html>
and my retrieveform.php is
<?php
if($_POST['t1'])
{
echo $_POST['t1'];
}
else
{
echo "hekllojjio";
}
?>
Is it possible that the element "t1" is present since it's part of your form, but empty or just empty characters .. perhaps check if this is the case?
<?php
if($_POST['t1'] && !empty($_POST['t1'])) {
echo "You submitted t1 of: ".$_POST['t1'];
} else {
echo "t1 is empty";
}
?>
Also of note is you may want to use something like firebug to view the ajax page loaded and its results. The echo statement on the ajax loaded page will not display on the parent page unless you set the contents of the response into the page:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$('.form').on('submit', function (e) {
tValue = $(this).find(input[type=text]:first).val();
e.preventDefault();
$.ajax({
type: 'post',
url: 'retrieveform.php',
data: $('form').serialize(),
success: function (response) {
alert('helllo');
$('#placeholder').html(response);
$('#placeholder2').html(tValue);
}
});
});
});
</script>
</head>
<body>
<?PHP for ($i = 1; $i <= 10; $i++) { ?>
<form class="form" name="form_<?PHP echo $i; ?>" id="form_<?PHP echo $i;?>">
<input type="text" id="t<?PHP echo $i; ?>" name="t<?PHP echo $i; ?>">
<input type="submit" name="s<?PHP echo $i; ?>" value="submit">
</form>
<?PHP } ?>
<div id="placeholder"></div>
<div id="placeholder2"></div>
</body>
</html>
with this your ajax loaded page's echo will be put on the page in the "placeholder" div.

Refresh PHP SESSION var after AJAX request

I've index.php and callSession04.php. When index.php does an AJAX request PHP SESSION variables are set on callSession04.php to store the current page and rows per page but on index.php PHP SESSION variables stay as initial state until I refresh index.php
You can see the example here, Need to refresh page before each AJAX request:
http://www.sanchezvalero.com/DWS/pracSESIONES/ej4/sesion04.php
And here is the code:
index.php
<? session_start(); ?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Listado de empleados</title>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="content" align="center"></div>
<p>
<div align="center">
<label for="fldRows">Resultados por página:</label>
<input name="fldRows" type="text" id="fldRows" size="2" />
</div>
</p>
<p>
<div id="manage" align="center">
<input name="btnFirst" type="button" id="btn1" value="|<" />
<input name="btnBefore" type="button" id="btn2" value="<" />
<input name="btnAfter" type="button" id="btn3" value=">" />
<input name="btnLast" type="button" id="btn4" value=">|" />
<p>Reset</p>
</div>
</p>
<script type="text/javascript">
$(document).ready(function() {
<? if(!isset($_SESSION['rows'])){ ?>
$("#fldRows").val("10");
<? } else { ?>
$("#fldRows").val("<? echo $_SESSION['rows']; ?>");
<? } if(!isset($_SESSION['actp'])){ ?>
$actp=0;
<? } else { ?>
$actp=<? echo $_SESSION['actp']; ?>;
<? } ?>
$.ajax({type: "GET",
url: "callSesion04.php",
data: "rows="+$("#fldRows").val()+"&actp="+$actp,
success: function(data) {
$("#content").html(data);
}
});
});
$("#fldRows").keyup(function() {
if($(this).val()>=0){
$.ajax({type: "GET",
url: "callSesion04.php",
data: "rows="+$(this).val()+"&actp=0",
success: function(data) {
$("#content").html(data);
}
});
}
});
$("body").on("click","#manage input",function(){
$id=$(this).attr('id').substr($(this).attr('id').search(/\d/));
$.ajax({type:"GET",
url:"callSesion04.php",
data:"pag="+$id+"&actp=<? echo $_SESSION['actp']; ?>&rows=<? echo $_SESSION['rows']; ?>",
success: function(data) {
$("#content").html(data);
}
});
});
</script>
</body>
</html>
callSession04.php
<? session_start();
$dom = new DOMDocument();
$dom->load('empleados.xml');
$empleados=$dom->getElementsByTagName('RECORD');
foreach($empleados as $empleado){
$ids=$empleado->getElementsByTagName('ID_EMPLEADO');
$id=$ids->item(0)->nodeValue;
$array_ids[]=$id;
$nombres=$empleado->getElementsByTagName('NOMBRE');
$nombre=$nombres->item(0)->nodeValue;
$array_nombres[]=$nombre;
$apellidos=$empleado->getElementsByTagName('APELLIDOS');
$apellido=$apellidos->item(0)->nodeValue;
$array_apellidos[]=$apellido;
$fechas=$empleado->getElementsByTagName('FECHA_NACIMIENTO');
$fecha=$fechas->item(0)->nodeValue;
$array_fechas[]=$fecha;
$tipos=$empleado->getElementsByTagName('TIPO_EMPLEADO');
$tipo=$tipos->item(0)->nodeValue;
$array_tipos[]=$tipo;
$hijos=$empleado->getElementsByTagName('NUM_HIJOS');
$hijo=$hijos->item(0)->nodeValue;
$array_hijos[]=$hijo;
}
$rows=$_GET['rows'];
$actp=$_GET['actp'];
$pag=$_GET['pag'];
$_SESSION['rows']=$rows;
if($rows>0){
$tpag=intval(count($array_ids)/$rows);
}
if($pag=='1'){
$actp=0;
}else if($pag=='2' && $actp>0){
$actp--;
}else if($pag=='3' && $actp<$tpag){
$actp++;
}else if($pag=='4'){
$actp=$tpag;
}
$_SESSION['actp']=$actp;
$minrow=$rows*$actp;
$maxrow=$rows*$actp+$rows;
if($maxrow>count($array_ids)){
$maxrow=count($array_ids);
}
echo "<p align='center'><strong>EMPLEADOS</strong></p>";
echo "<table border='1' cellspacing='0' cellpadding='5'>";
echo "<tr><td>ID</td><td>Nombre</td><td>Apellidos</td><td>Nacimiento</td><td>Tipo</td><td>Hijos</td></tr>";
for($i=$minrow;$i<$maxrow;$i++){
echo "<tr><td>".$array_ids[$i]."</td><td>".$array_nombres[$i]."</td><td>".$array_apellidos[$i]."</td>
<td>".$array_fechas[$i]."</td><td>".$array_tipos[$i]."</td><td>".$array_hijos[$i]."</td></tr>";
}
echo "</table>";
?>
I need to know how refresh PHP SESSION VARS on index.php withouth press F5.
Finally I solved this, the solution, JSON. Is not necessary to refresh PHP SESSION vars on index.php, only on callSession04.php, simply I've to use AJAX callback to reflect the current server state parsing JSON array on index.php from callSession04.php then you can set new current page and rows per page vars.
index.php
<? session_start(); ?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Listado de empleados</title>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
</head>
<body>
<div id="content" align="center"></div>
<p>
<div align="center">
<label for="fldRows">Resultados por página:</label>
<input name="fldRows" type="text" id="fldRows" size="2" />
</div>
</p>
<p>
<div id="manage" align="center">
<input name="btnFirst" type="button" id="btn1" value="|<" />
<input name="btnBefore" type="button" id="btn2" value="<" />
<input name="btnAfter" type="button" id="btn3" value=">" />
<input name="btnLast" type="button" id="btn4" value=">|" />
<p>Reset</p>
</div>
</p>
<script type="text/javascript">
$(document).ready(function() {
<? if(!isset($_SESSION['rows'])){ ?>
$("#fldRows").val("10");
$rows=10;
<? } else { ?>
$("#fldRows").val("<? echo $_SESSION['rows']; ?>");
$rows=<? echo $_SESSION['rows']; ?>;
<? } if(!isset($_SESSION['actp'])){ ?>
$actp=0;
<? } else { ?>
$actp=<? echo $_SESSION['actp']; ?>;
<? } ?>
$.ajax({type: "GET",
url: "callSesion04.php",
data: "rows="+$("#fldRows").val()+"&actp="+$actp,
success: function(data) {
var json = $.parseJSON(data);
$("#content").html(json.html);
}
});
});
$("#fldRows").keyup(function() {
if($(this).val()>=0){
$.ajax({type: "GET",
url: "callSesion04.php",
data: "rows="+$(this).val()+"&actp=0",
success: function(data) {
var json = $.parseJSON(data);
$rows=json.rows;
$("#content").html(json.html);
}
});
}
});
$("body").on("click","#manage input",function(){
$id=$(this).attr('id').substr($(this).attr('id').search(/\d/));
$.ajax({type:"GET",
url:"callSesion04.php",
data:"pag="+$id+"&actp="+$actp+"&rows="+$rows,
success: function(data) {
var json = $.parseJSON(data);
$actp=json.actp;
$("#content").html(json.html);
}
});
});
</script>
</body>
</html>
callSession04.php
<? session_start();
$dom = new DOMDocument();
$dom->load('empleados.xml');
$empleados=$dom->getElementsByTagName('RECORD');
foreach($empleados as $empleado){
$ids=$empleado->getElementsByTagName('ID_EMPLEADO');
$id=$ids->item(0)->nodeValue;
$array_ids[]=$id;
$nombres=$empleado->getElementsByTagName('NOMBRE');
$nombre=$nombres->item(0)->nodeValue;
$array_nombres[]=$nombre;
$apellidos=$empleado->getElementsByTagName('APELLIDOS');
$apellido=$apellidos->item(0)->nodeValue;
$array_apellidos[]=$apellido;
$fechas=$empleado->getElementsByTagName('FECHA_NACIMIENTO');
$fecha=$fechas->item(0)->nodeValue;
$array_fechas[]=$fecha;
$tipos=$empleado->getElementsByTagName('TIPO_EMPLEADO');
$tipo=$tipos->item(0)->nodeValue;
$array_tipos[]=$tipo;
$hijos=$empleado->getElementsByTagName('NUM_HIJOS');
$hijo=$hijos->item(0)->nodeValue;
$array_hijos[]=$hijo;
}
$rows=$_GET['rows'];
$actp=$_GET['actp'];
$pag=$_GET['pag'];
if($rows>0){
$tpag=intval(count($array_ids)/$rows);
}
if($pag=='1'){
$actp=0;
}else if($pag=='2' && $actp>0){
$actp--;
}else if($pag=='3' && $actp<$tpag){
$actp++;
}else if($pag=='4'){
$actp=$tpag;
}
$_SESSION['rows']=$rows;
$_SESSION['actp']=$actp;
$minrow=$rows*$actp;
$maxrow=$rows*$actp+$rows;
if($maxrow>count($array_ids)){
$maxrow=count($array_ids);
}
$html = "<p align='center'><strong>EMPLEADOS</strong></p>";
$html .= "<table border='1' cellspacing='0' cellpadding='5'>";
$html .= "<tr><td>ID</td><td>Nombre</td><td>Apellidos</td><td>Nacimiento</td><td>Tipo</td><td>Hijos</td></tr>";
for($i=$minrow;$i<$maxrow;$i++){
$html .= "<tr><td>".$array_ids[$i]."</td><td>".$array_nombres[$i]."</td><td>".$array_apellidos[$i]."</td>";
$html .= "<td>".$array_fechas[$i]."</td><td>".$array_tipos[$i]."</td><td>".$array_hijos[$i]."</td></tr>";
}
$html .= "</table>";
$aPag = array("rows"=>$rows,"actp"=>$actp,"html"=>$html);
echo json_encode($aPag);
?>
The session state is on the server, your code updates it on the server correctly (I assume). What you experience is the representation of the server state (index.php) is not updated on the client (browser) after the Ajax call.
You have multiple options to fix that:
Use the ajax callback to reload the current page (index.php)
Use the ajax callback to update the current page (DOM manipulation) to reflect the server state
This can not be fixed in the php (server side) alone.

PHP and javascript POST

I have the following code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript">
</script>
<script type="text/javascript">
function displayTweet(){
var i = 0;
var limit = $("#twitter-results > div").size();
var myInterval = window.setInterval(function () {
var element = $("#twitter-results div:last-child");
$("#twitter-results").prepend(element);
element.fadeIn("slow");
i++;
if(i==limit){
window.setTimeout(function () {
clearInterval(myInterval);
});
}
},2000);
}
$("form#twittersearch").submit(function() {
twitterq = $('#twitterq').attr('value');
$.ajax({
type: "POST",
url: "search.php",
cache: false,
data: "twitterq="+ twitterq,
success: function(html){
$("#twitter-results").html(html);
displayTweet();
}
});
return false;
});
});
</script>
</head>
<div class="twitter_container">
<form id="twittersearch" method="post" action="">
<input name="twitterq" type="text" id="twitterq" />
<button type="submit">Search</button>
</form>
<div id="twitter-results"></div>
</div>
</html>
/***************THIS IS search.php***************************/
<?php
include('twitterapi.php');
if($_POST['twitterq']){
$twitter_query = $_POST['twitterq'];
$search = new TwitterSearch($twitter_query);
$results = $search->results();
foreach($results as $result){
echo '<div class="twitter_status">';
echo '<img src="'.$result->profile_image_url.'" class="twitter_image">';
$text_n = toLink($result->text);
echo $text_n;
echo '<div class="twitter_small">';
echo '<strong>From:</strong> <a href="http://www.twitter.com/'.$result->from_user.'">'.$result->from_user.'</a&glt;: ';
echo '<strong>at:</strong> '.$result->created_at;
echo '</div>';
echo '</div>';
}
}
?>
Why is it that when I do a var_dump($_POST['twitterq']) it is always NULL?
UPDATE:
firebug gave me this, not sure how to fix it though:
That is because you are not providing the data properly. It should be:
data: ({twitterq: twitterq}),
You are sending data in the form of JSON. You are not using URL parameters , so there is no need of '='. if you have more than one parameters, you will simply separate them with commas.

Categories