jQuery, AJAX & PHP: Arrays on server and client data - php

My goal is to dynamically display information via PHP that is then editable via AJAX/json. I have this working for a single instance of the server data, but when I get into multiple instances I am getting lost on how to keep the element and div identities distinct via array on the json page as well as in the jQuery output on the main page.
This is the current main page (minus the irrelevant to this question PHP record grabbing). The references in the jQuery are not entirely correct, e.g.
data:$("#form_static_").serialize()
because it is placing the dynamic identifier after the static_ that I don't know how to handle.
<html>
<head>
<title>My Form</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#myForm").submit(function(){
$.ajax({
type:"POST",
url:"ajax_form_test2-json.php",
data:$("#form_static_").serialize(),
dataType:"json",
success:function(msg){
$("#formResponse_").removeClass('error');
$("#formResponse_").addClass(msg.status_);
$("#formResponse_").html(msg.message_);
$("#static_name_").html(msg.name_);
$("#static_description_").html(msg.description_);
},
error:function(){
$("#formResponse_").removeClass('success');
$("#formResponse_").addClass('error');
$("#formResponse_").html("There was an error submitting the form. Please try again.");
}
});
return false;
});
});
</script>
</head>
<body>
<div id="tabs-left-2" class="content">
<h1 class="page-title">Static Info</h1>
<?php do { ?>
<div id="static_name_<?php echo $row_rsStatic['id']; ?>" class="small_content_heading"><?php echo $row_rsStatic['name']; ?></div>
<div id="static_description_<?php echo $row_rsStatic['id']; ?>" class="small_content"><?php echo $row_rsStatic['description']; ?></div>
<div id="static_update_<?php echo $row_rsStatic['id']; ?>" style="display:inherit">
<form id="form_static_<?php echo $row_rsStatic['id']; ?>" name="form_static_<?php echo $row_rsStatic['id']; ?>" method="post" action="">
<div id="formResponse_<?php echo $row_rsStatic['id']; ?>"></div>
<div id="form_static_name_<?php echo $row_rsStatic['id']; ?>" class="small_content_heading">
<input name="id<?php echo $row_rsStatic['id']; ?>" type="hidden" value="<?php echo $row_rsStatic['id']; ?>">
<input name="name<?php echo $row_rsStatic['id']; ?>" type="text" value="<?php echo $row_rsStatic['name']; ?>"></div>
<div id="form_static_description_<?php echo $row_rsStatic['id']; ?>">
<textarea name="description<?php echo $row_rsStatic['id']; ?>"><?php echo $row_rsStatic['description']; ?></textarea>
<script>CKEDITOR.replace('description<?php echo $row_rsStatic['id']; ?>');</script>
</div>
</form>
</div>
<hr>
<?php } while ($row_rsStatic = mysql_fetch_assoc($rsStatic)); ?>
</div>
</body>
</html>
This is the json page, again with the dynamic identifiers left off after the respective "_" as I don't know how to make this happen programmatically:
<?php
//response array with status code and message
$response_array = array();
//validate the post form
//check the name field
if(empty($_POST['static_name_'])){
//set the response
$response_array['status_'] = 'error';
$response_array['message_'] = 'Name is blank';
//check the message field
} elseif(empty($_POST['static_description_'])) {
//set the response
$response_array['status_'] = 'error';
$response_array['message_'] = 'Description is blank';
//form validated
} else {
//(update record here)
//set the response
$response_array['status_'] = 'success';
$response_array['message_'] = 'Success!';
$response_array['name_'] = $_POST['static_name_'];
$response_array['description_'] = $_POST['static_description_'];
}
echo json_encode($response_array);
?>
I have been doing PHP forever but am new to the AJAX/JSON/jQuery world, so not sure that the way this is set up is even ideal for dynamically produced/updated data. Any ideas or advice is greatly appreciated... thanks!
EDITS #1:
I changed the files to the following, and know I am still missing something as it does not correctly update:
<html>
<head>
<title>My Form</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="ckeditor/ckeditor.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("form").submit(function(e){
e.stopPropagation();
var form = $(this); // We're going to use this instead of all those IDs
$.ajax({
type:"POST",
url:"ajax_form_test2-json.php",
data: form.serialize(),
dataType:"json",
success:function(msg){
$(".response", form)
.removeClass('error')
.addClass(msg.status)
.html(msg.message);
$(".name", form).html(msg.name);
$(".description", form).html(msg.description);
},
error:function(){
$(".response", form)
.removeClass('success')
.addClass('error')
.html("There was an error submitting the form. Please try again.");
}
});
return false;
});
});
</script>
</head>
<body>
<div class="small_content_heading name"><?php echo $row_rsSafety['name']; ?></div>
<div class="small_content description"><?php echo $row_rsSafety['description']; ?></div>
<div style="display:inherit">
<form method="post" action="">
<div class="response"></div>
<div class="small_content_heading">
<input name="id" type="hidden" value="<?php echo $row_rsSafety['id']; ?>">
<input name="name" type="text" value="<?php echo $row_rsSafety['name']; ?>">
</div>
<div>
<textarea name="description"><?php echo $row_rsSafety['description']; ?></textarea>
<script>CKEDITOR.replace('description');
function CKupdate(){
for ( instance in CKEDITOR.instances )
CKEDITOR.instances[instance].updateElement();
}
</script>
</div>
<input type="submit" name="submitForm" value="Edit" onClick="CKupdate();">
</form>
</div>
<hr>
</body>
</html>
JSON file:
<?php
//connect to DB
require_once('Connections/job_tool.php');
mysql_select_db($database_job_tool, $job_tool);
//response array with status code and message
$response_array = array();
//validate the post form
//check the name field
if(empty($_POST['name'])){
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Name is blank';
//check the message field
} elseif(empty($_POST['description'])) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Message is blank';
//form validated
} else {
//set update variables
$update_name = $_POST['name'];
$update_desc = $_POST['description'];
$update_id = $_POST['id'];
//update file on server
$sql = "UPDATE static_fields SET name='$update_name', description='$update_desc' WHERE id='$update_id'";
$update_sql = mysql_query($sql, $job_tool) or die('Could not update data: ' . mysql_error());
mysql_close();
//set the response
$response_array['status'] = 'success';
$response_array['message'] = 'Update complete!';
$response_array['name'] = $_POST['name'];
$response_array['description'] = $_POST['description'];
}
echo json_encode($response_array);
?>

Rather than using IDs all the time, use jQuery context and classes:
<script type="text/javascript">
$(document).ready(function(){
$("form").submit(function(e){
e.stopPropagation();
var form = $(this); // We're going to use this instead of all those IDs
$.ajax({
type:"POST",
url:"ajax_form_test2-json.php",
data: form.serialize(),
dataType:"json",
success:function(msg){
$(".response", form)
.removeClass('error')
.addClass(msg.status);
.html(msg.message);
$(".name", form).html(msg.name);
$(".description", form).html(msg.description);
},
error:function(){
$(".response", form)
.removeClass('success')
.addClass('error')
.html("There was an error submitting the form. Please try again.");
}
});
return false;
});
});
</script>
So, rather than this:
<div id="static_description_<?php echo $row_rsStatic['id']; ?>" class="small_content"><?php echo $row_rsStatic['description']; ?></div>
You'll use a class instead:
<div class="small_content description"><?php echo $row_rsStatic['description']; ?></div>
The approach:
Use generic classes for your DIVs
Use generic names for your INPUTs
In your PHP $_POST handler, use the hidden ID field to know which record you're working with
In your JSON response, use generic status, message, name, and description keys

Related

Pop-up message after submitting a form with php

I'm trying to get a pop-up message saying if it was successfully submitted or not without having to go to a different page.
Now chrome gives me the pop-up message but it redirects me to a blank page after.
Here is my current code.
<?php
include "header.php";
include "conexao.php";
echo "<h1 align='center'>Pagina para alterar produtos</h1><div class='container'><hr>";
$referencia=$_GET['id'];
$sql = "SELECT * ";
$sql = $sql . " FROM tb_produto ";
$sql = $sql . " WHERE pr_codigo='".$referencia."'";
$produtos = $db->query($sql);
foreach ($produtos as $produto) {
$referencia = $produto["pr_codigo"];
$nome = $produto["pr_descricao"];
$preco = $produto["pr_preco"];
$disponivel = $produto["disponivel"];
}
echo "<h2>Referencia: ".$referencia."</h2>";
echo "<h2>Nome: ".$nome."</h2><hr>";
?>
<form action="confirmaAlterar.php">
<div class="form-group">
<label>Referencia</label>
<input class="form-control" type="text" name="referencia" value="<?php echo $referencia?>">
</div>
<div class="form-group">
<label>Nome</label>
<input class="form-control" type="text" name="nome" value="<?php echo $nome?>">
</div>
<div class="form-group">
<label>Preço</label>
<input class="form-control" type="text" name="preco" value="<?php echo $preco?>">
</div>
<button class="btn btn-primary">Alterar</button>
</form>
Here is where it submits the information of the form.
<?php
include "header.php";
include "conexao.php";
$nome=$_GET['nome'];
$referencia=$_GET['referencia'];
$preco=$_GET['preco'];
$sql="UPDATE tb_produto SET pr_descricao='".$nome;
$sql.="', pr_preco=".$preco;
$sql.= " WHERE pr_codigo='".$
try{
$comando=$db->prepare($sql);
$comando->execute();
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
header( "refresh2;Location:index.php" );
}
catch (PDOException $e){
echo "A";
}
To pass values using ajax. Form:
<form id="form">
<input type="text" value="test" name="akcija">
</form>
All inputs fields values in your form will be passed.
Ajax:
jQuery(function(){
$('#form').on('submit', function (e) { //on submit function
e.preventDefault();
$.ajax({
type: 'post', //method POST
url: 'yoururl.php', //URL of page where u place query and passing values
data: $('#form').serialize(), //seriallize is passing all inputs values of form
success: function(){ //on success function
$("#input").attr("disabled", true); //example
$("#input").removeClass('btn-primary').addClass('btn-success');//example
},
});
}
});
And on the ajax page you can get values by
$akcija = $_POST['akcija']
for this Problem you must use ajax method .
1- create html form and all input Required .
<form id="contactForm2" action="/your_url" method="post">
...
</form>
2- add jQuery library file in the head of html page .
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
...
3- add this method Under the jQuery library
<script type="text/javascript">
var frm = $('#contactForm2');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
if(data == 'pass')
alert('ok');
else(data == 'fail')
alert('no');
}
});
ev.preventDefault();
});
</script>
4- in your_url .php file
<?php
$a = ok ;
if( $a == 'ok' ){
echo 'pass';
}else{
echo 'fail';
}
?>
this top answer is easy management form with jquery , but you need managment Complex form better use this library http://jquery.malsup.com/form/

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.

issue sending a retrieving value using ajax

This is a cleaner code of my preview problem, the idea is to send and retrieve a value using ajax, but the value is not being sent nor ajax seems to work. I updated this code because this way it could be easily tested on any machine. First time using ajax. Here is the code:
Javascript
<script>
jQuery(document).ready(function() {
jQuery('#centro').click( function() {
$.ajax({
url: 'request.php',
type:'POST',
data: $("#form").serialize(),
dataType: 'json',
success: function(output_string){
alert(output_string);
$('#cuentas').html(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
</script>
HTML:
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
PHP file, request.php
<?php
$centro = $_POST['centro'];
$output_string = ''.$centro;
echo json_encode($output_string);
?>
Try Changing Your Code A bit like Below .
Jquery part
success: function(d){
var output=d[0].data; // Will output only first record
$('#cuentas').html(output);
} // End of success function of ajax form
PHP PART
$centro = $_POST['centro'];
$output_string = array('data'=>$centro);
echo json_encode($output_string);
if still not works Check The Developer tool in chrome or firebug in firefox to monitor the Requests
Looking at your code:
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
I miss an ending-tag for the div id="centro". Therefore the click-event for jQuery("#centro") will not trigger.
I suppose it should be like this: (Always set <form> and </form> inside OR outside of a div, do not mix and put <form> outside and </form> inside of a div. Some things wont work as expected when you do a mix like that.
<?php
$result = 'works';
?>
<div id="centro">
<form id="form">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
</div> ><!-- end of div centro -->
<div id="cuentas">
</div>
I solved it, now this works, plus I added a gif loader:
Javascript:
<script>
jQuery(document).ready(function() {
jQuery('#centro').click( function() {
var result = $("input#centro").val();
$.ajax({
url: 'request.php',
type:'POST',
data: { 'dataString': result },
beforeSend: function(){
$("#loader").show();
},
success: function(output_string){
$("#loader").hide();
$('#cuentas').html(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
</script>
HTML
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
<div id="loader" style="display:none"><img src="ajax-loader.gif" width="20px" height="20px"></div>
Click here
<br>
<input type="hidden" name="centro" id="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
PHP
<?php
$data = $_POST['dataString'];
$output_string = '';
$output_string = '<h3>'.$data.' '.'testing'.'</h3>';
echo $output_string;
?>
Output: "works testing"

Can a submit button work without refresh AJAX?

I have a problem with my very simple chat. The page is constanly refreshing with AJAX with an timeout of 750ms. If I press or use enter to submit my 'reaction', the page refreshes: is there an way to remove that, so that you can instantly see what you've posted?
You can see the chat at my website: chat
The code:
Index.php
<!DOCTYPE HTML>
<?php include 'config.php'; ?>
<html>
<head>
<script type="text/javascript" src="jquery-1.7.1.js">
function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13)
{
myfield.form.submit();
return false;
}
else
return true;
}
</script>
<title>JavaScript Chat</title>
<link href="style.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div class="container">
<div id="chatwindow">
</div>
<div class="inputMessage">
<form method="post">
enter code here
<hr></hr>
<textarea name="message" rows="1" cols="55"></textarea><br/>Fill username here<br/>
<input type="text" value="" name="username" />
<input type="submit" value="verstuur" name="submit" onKeyPress="return submitenter(this,event)" />
</form>
<?php include 'send.php'; ?>
</div>
<script type="text/javascript">
$(document).ready(function(){
setInterval ( "get()", 750 );
});
function get(){
$.ajax({
type: 'GET',
url: 'chat.php',
success: function(data){
$("#chatwindow").html(data);
}
});
}
</script>
</div>
</body>
</html>
chat.php
<?php
include 'config.php';
$result = mysql_query("select * from Message");
while($row = mysql_fetch_array($result))
{
echo '<p>' . $row['username'] . " : " . $row['message'] . '</p>';
}
?>
send.php
<?php
if(isset($_POST['submit']))
{
if (!empty($_POST['username']))
{
if(!empty($_POST['message']))
{
$message = mysql_real_escape_string(htmlentities($_POST['message']));
$username = mysql_real_escape_string(htmlentities($_POST['username']));
$query = "INSERT INTO Message (`username`,`message`) VALUES ('".$username."','".$message."')";
mysql_query($query);
}
else
{
echo '<script type="text/javascript">alert(\'Je kan niet niks sturen\')</script>';
}
}
else
{
echo '<script type="text/javascript">alert(\'Vul een gebruikresnaam in!\')</script>';
}
}
?>
if my question is not clear say it please.
And is there a topic/question/post about good spacing? google translated it as "indent".
Thanks
Replace
<form method="post">
With
<form onsubmit="event.preventDefault()" method="post">
You may also use your callback function here like:
<form onsubmit="event.preventDefault();return submitenter(this,event);" method="post">
Working demo: http://jsfiddle.net/usmanhalalit/5RCwF/2/
Add e.preventDefault(); in JS.
Your desired action is to prevent the onSubmit action as the other answers have mentioned. Currently your script isn't quite ready to block submit as you don't have an ajax post method.
You need ajax functionality for the submission side of the application still. For this you can use jQuery post().
You want to create something like
function send() {
$.post(); // Fill in appropriate post() code.
return false;
}
And then call it from your event handlers like onsubmit="return send()" and in place of myfield.form.submit() in your keypress handler.

Update div on AJAX submit jQuery is updating all divs

I'm trying to update a div with an ajax post. Problem is...it's updating every div.
Here's the json.php:
//json.php
$data['months'] = $db->escape_value($_POST['check']);
$data['id'] = $db->escape_value($_POST['hidden']);
$query = "UPDATE month SET months = '{$data['months']}' WHERE monthID = '{$data['id']}'";
$result = $db->query($query);
if($result) {
$data['success'] = true;
$data['message'] = "Update Successful!";
$data['text'] = $_POST['check'];
echo json_encode($data);
} else {
$data['message'] = "Update could not be completed.";
}
And the html:
<?php
$query = $db->query('SELECT * FROM month');
?>
<html>
<head>
<title>jQuery/Ajax - Update is updating all divs</title>
<link rel="stylesheet" type="text/css" href="test.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("input.check, button.save, input.cancel, div.message").hide();
$(".edit").click(function(){
$(this).parent().siblings("li.liTwo").children("input.delete").hide();
$(this).parent().siblings("li.liThree").children("button.save").show();
$(this).parent().siblings("li.liFour").children("input.cancel").show();
$(this).parents("ul").siblings("div.showText").hide();
$(this).parents("ul").siblings("input.check").show();
$(this).hide();
return false;
});
$(".cancel").click(function(){
$(this).parent().siblings("li.liTwo").children("input.delete").show();
$(this).parent().siblings("li.liThree").children("button.save").hide();
$(this).parent().siblings("li.liOne").children("input.edit").show();
$(this).parents("ul").siblings("div.showText").show();
$(this).parents("ul").siblings("input.check").hide();
$(this).hide();
return false;
});
$("form[name=form1]").submit(function(){
var params = $(this);
$.post("json.php", { hidden : $(this).find("[name=hidden]").val(), check : $(this).find("[name=check]").val() },
function (data){
if(data.success) {
$(".showText").html(data.text);
$(".message").html(data.message).slideDown("fast");
$(".check").hide();
$("button.save").hide();
$(".cancel").hide();
$(".edit").show();
$(".delete").show();
$(".showText").show();
return false;
}
}, "json");
return false;
});
});
</script>
</head>
<body>
<div class="message">message</div>
<?php while($row = $db->fetch_assoc($query)) { ?>
<form action="json.php" name="form1" method="post">
<div class="container">
<div class="showText"><?php echo $row['months']; ?></div>
<input name="check" type="text" class="check" value="<?php echo $row['months']; ?>" />
<input name="hidden" type="hidden" class="hidden" value="<?php echo $row['monthID']; ?>" />
<ul class="list">
<li class="liOne">
<input name="edit" type="button" class="edit" value="edit" />
</li>
<li class="liTwo">
<input name="delete" type="submit" class="delete" value="delete" />
</li>
<li class="liThree">
<button name="save" type="submit" class="save" value="<?php echo $row['monthID']; ?>">save</button>
</li>
<li class="liFour">
<input name="cancel" type="button" class="cancel" value="cancel" />
</li>
</ul>
</div>
</form>
<?php } ?>
<!--<a id="reset" href="test3.php">reset</a>-->
</body>
</html>
You need to specify a context (the form) for the elements you're changing:
$("form[name=form1]").submit(function(){
var form = this;
var params = $(this);
$.post(form.action, { hidden : $(this).find("[name=hidden]").val(), check : $(this).find("[name=check]").val() },
function (data){
if(data.success) {
$(".showText", form).html(data.text);
$(".message", form).html(data.message).slideDown("fast");
$(".check", form).hide();
$("button.save", form).hide();
$(".cancel", form).hide();
$(".edit", form).show();
$(".delete", form).show();
$(".showText", form).show();
return false;
}
}, "json");
return false;
});
Also, if you hide a parent element, the children are hidden, too, so you probably want to do that...
Every div has the same class: showText. They need unique IDs instead, like Div1, Div2. Then update them by their ID: $("#Div1")
Hint, instead of answer:
How many elements does $(".showText") return?
2nd Hint: It's more than one!
===
Edit for more clarity:
The first issue is that you're selecting by classes like .showText. But you're creating multiple forms, each of which has an element that matches .showText. You need some way to point at the right element in each form. One way to solve this is to add an ID on each FORM tag, so you can then select things like $('#form-number-$N .showtext) -- which selects any elements with class="showtext" inside the element with id "#form-number-$N"
You're looping over rows in your database and writing the forms. So you need some variable data to identify each individual form.
You've got a while loop that populates $row:
<?php while($row = $db->fetch_assoc($query)) { ?>
But currently, every form you create has a name attribute of "form1".
So what if, instead of:
<?php while($row = $db->fetch_assoc($query)) { ?>
<form action="json.php" name="form1" method="post">
You did something like:
<?php while($row = $db->fetch_assoc($query)) { ?>
<form action="json.php" name="form<?PHP echo $row['id']; ?>" id="<?PHP echo $row['id']; ?> class="myFormClass" method="post">
Then you could use a handler that looks something like:
$("form.myFormClass").submit(function(){
var params = $(this);
$.post("json.php", { hidden : $(this).find("[name=hidden]").val(), check : $(this).find("[name=check]").val() },
function (data){
if(data.success) {
$(this.id + " .showText").html(data.text);
...
return false;
}
}, "json");
return false;
});
Do you see what's happening there?

Categories