How to validate a wizard form with php and jquery? - php

A brief explanation of how this simple jQuery wizard works
Sessions are used to save data for each step.
consists of a session variable to save in what step we are.
consists of a session variable to store the form data.
Each time we change the step we save the data of the form and the step in session with an ajax request.
If the data is updated the data is retrieved from the session.
This wizard form consists of 3 steps.
As I can correct the errors and validate the form with php if there is a field without data do not let go to the next step, until all fields of the form are completed by the user.
There are warning errors in each of the form fields in each text input shows me a warning message.
Notice: Undefined index: datos_form in C:\xampp\htdocs\prueba\wizar.php on line 229
I would like to add a cookie to the session where the steps are saved to avoid erasing the data stored in the session in case the browser is closed in error, create a session cookie with a validation time of 30 days.
now to remove the cookie from the data saved by the user create a cancel button, the cancel button will delete the cookie, including the data saved in the session.
My complete code:
wizar.php
<?php
session_start();
// check if there is a previous step.
if ( !empty($_SESSION['datos_form']['__paso__']) ) {
$paso = $_SESSION['datos_form']['__paso__'];
}
// if there is no previous step we set step 1.
else{
$paso = '1';
}
?><!DOCTYPE html>
<html>
<head>
<title>Form por pasos</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
mostrar_paso(<?= $paso; ?>);
});
function animacion(caso){
switch(caso) {
case 1:
$(".backdrop").css("background-position", `0px 0px`);
break;
case 2:
$(".backdrop").css("background-position", `0px -16px`);
break;
case 3:
$(".backdrop").css("background-position", `0px -32px`);
break;
default:
$(".backdrop").css("background-position", `0px 0px`);
};
};
function mostrar_paso(paso)
{
var data = $( "#form" ).serialize();
var url = 'saveTemp.php?paso=' + paso;
var valor_radio = $('input:radio[name=radio]:checked').next("label").text();
$.ajax({
type: "POST",
url: url,
data: data
})
.done(function( resp ) {
$('.step').css( "display", "none" );
$('#paso'+paso).fadeIn("slow");
$('#div_producto').html(valor_radio);
animacion(paso);
});
};
</script>
</head>
<body>
<div class="setup">
<ul class="backdrop">
<li class="process item1">step 1</li>
<li class="process item2">step 2</li>
<li class="process item3">FINALIZE</li>
</ul>
</div>
<form id="form" action="procesar.php">
<div id="paso1" class="step">
<input type="text" name="campo1" value="<?= $_SESSION['datos_form']['campo1']; ?>">
<select class="form-select" name="sexo">
<?php
if( !empty($_SESSION['datos_form']['sexo']) ) {
$sexo = $_SESSION['datos_form']['sexo'];
echo '<option value="'.$sexo.'" selected="selected">'.$sexo.'</option>';
}
else{
echo '<option disabled selected="selected">I am...</option>';
}
?>
<option value="Mem">Men</option>
<option value="Woman">Woman</option>
<option value="I prefer not to say">I prefer not to say</option>
</select>
<?php
if( !empty($_SESSION['datos_form']['condiciones']) ) {
echo '<input type="checkbox" name="condiciones" checked>';
}
else{
echo '<input type="checkbox" name="condiciones">';
}
?>
...
onclick="mostrar_paso('numero de paso') -->
continuar
</div>
<div id="paso2" class="step">
<?php
$r =array(
1 => 'Product 1',
2 => 'Product 2',
3 => 'Product 3',
);
foreach ($r as $key => $value)
{
if( $_SESSION['datos_form']['radio'] == $key ) {
echo '<input name="radio" type="radio" id="'.$key.'" value="'.$key.'" checked="checked" >';
echo '<label for="'.$key.'" title="'.$value.'">'.$value.'</label>';
}
else{
echo '<input name="radio" type="radio" id="'.$key.'" value="'.$key.'" >';
echo '<label for="'.$key.'" title="'.$value.'">'.$value.'</label>';
}
}
?>
Atras
continuar
</div>
<div id="paso3" class="step">
<div id="div_producto"></div><br>
<input type="text" name="campo3" value="<?= $_SESSION['datos_form']['campo3']; ?>">
<input type="submit" name="cancel">
Atras
<input type="submit" name="Terminar">
</div>
</form>
</body>
</html>
saveTemp.php
Note: This file is responsible for saving the step and data of the form.
<?php
session_start();
// We save the form data in a session variable
$_SESSION['datos_form'] = $_POST;
// we added the step also to the array, you can not use this name (__paso__) as name in the form
$_SESSION['datos_form']['__paso__'] = $_GET['paso'];

As I can correct the errors and validate the form with php if there is
a field without data do not let go to the next step, until all fields
of the form are completed by the user.
You need to code validation rules under saveTemp.php something like this :
<?php
session_start();
//form validation
switch($_GET['paso']){
case 2:
if(empty($_POST['campo1'])){//you may add any validation rule you want here
die(json_encode(array('status' => FALSE,'message' => 'please fill campo ....')));
}
if(empty($_POST['sexo'])){
die(json_encode(array('status' => FALSE,'message' => 'please select sexo ....')));
}
if(empty($_POST['condiciones'])){
die(json_encode(array('status' => FALSE,'message' => 'please select condiciones ....')));
}
break;
case 3: //step 2 validation here
if(empty($_POST['radio'])){//you may add any validation rule you want here
die(json_encode(array('status' => FALSE,'message' => 'please fill radio1 ....')));
}
break;
}
// We save the form data in a session variable
$_SESSION['datos_form'] = $_POST;
// we added the step also to the array, you can not use this name (__paso__) as name in the form
$_SESSION['datos_form']['__paso__'] = $_GET['paso'];
die(json_encode(array('status' => TRUE,'message' => 'Temporary saved....')));
and then check response under ajax call for status, so you need to change ajax call like this:
$.ajax({
type: "POST",
url: url,
data: data,
dataType: 'json'
})
.done(function( resp ) {
if(resp.status)
{
$('.step').css( "display", "none" );
$('#paso'+paso).fadeIn("slow");
$('#div_producto').html(valor_radio);
animacion(paso);
}else{
var old_paso = paso-1;
alert(resp.message);
$('.step').css( "display", "none" );
$('#paso'+old_paso).fadeIn("slow");
$('#div_producto').html(valor_radio);
animacion(old_paso);
}
});
notice that I add "dataType" to your ajax call and set it to json
There are warning errors in each of the form fields in each text input
shows me a warning message.
that because you did not check for existence of variable before getting its value, the code you post is form.php but warning complain about wizar.php line number 229, check that line and use empty function just like the rest of your code
here is a sample wizar.php without notice/warning:
<?php
session_start();
// check if there is a previous step.
if ( !empty($_SESSION['datos_form']['__paso__']) ) {
$paso = $_SESSION['datos_form']['__paso__'];
}
// if there is no previous step we set step 1.
else{
$paso = '1';
}
?><!DOCTYPE html>
<html>
<head>
<title>Form por pasos</title>
<style type="text/css">
.backdrop {
position: absolute;
width: 630px;
height: 16px;
background: url(//drh.img.digitalriver.com/DRHM/Storefront/Site/avast/cm/images/avast/2014/breadcrumb-3.png) no-repeat;
list-style-type: none;
text-transform: uppercase;
}
.step {
padding-top: 30px;
display: none;
}
.step-1 {
display: block;
}
.setup {
width: 100%;
height: 100px;
padding: 50px 0px 0px 50px;
background-color: rgba(29, 36, 36, 0.25);
}
.process {
position: absolute;
top: -30px;
color: #e8e8e8;
font-size: 1.1em;
}
.process.item2 {
padding-left: 190px;
}
.process.item3 {
padding-left: 400px;
}
.process.item4 {
padding-left: 580px;
}
.process.item5 {
padding-left: 690px;
}
.process.item6 {
padding-left: 790px;
}
ul li {
margin: 0;
padding: 0;
border: none;
list-style: none;
list-style-type: none;
white-space: nowrap;
}
.step{
display: none;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.step').css( "display", "none" );
$('#paso'+<?= $paso; ?>).fadeIn("slow");
$('#div_producto').html(valor_radio);
animacion(<?= $paso; ?>);
});
function animacion(caso){
switch(caso) {
case 1:
$(".backdrop").css("background-position", `0px 0px`);
break;
case 2:
$(".backdrop").css("background-position", `0px -16px`);
break;
case 3:
$(".backdrop").css("background-position", `0px -32px`);
break;
default:
$(".backdrop").css("background-position", `0px 0px`);
};
};
function mostrar_paso(paso)
{
var data = $( "#form" ).serialize();
var url = 'saveTemp.php?paso=' + paso;
var valor_radio = $('input:radio[name=radio]:checked').next("label").text();
$.ajax({
type: "POST",
url: url,
data: data,
dataType: 'json'
})
.done(function( resp ) {
if(resp.status)
{
$('.step').css( "display", "none" );
$('#paso'+paso).fadeIn("slow");
$('#div_producto').html(valor_radio);
animacion(paso);
}else{
var old_paso = paso-1;
alert(resp.message);
$('.step').css( "display", "none" );
$('#paso'+old_paso).fadeIn("slow");
$('#div_producto').html(valor_radio);
animacion(old_paso);
}
});
};
</script>
</head>
<body>
<div class="setup">
<ul class="backdrop">
<li class="process item1">step 1</li>
<li class="process item2">step 2</li>
<li class="process item3">FINALIZE</li>
</ul>
</div>
<form id="form" action="procesar.php">
<div id="paso1" class="step">
<input type="text" name="campo1" value="<?= (!empty($_SESSION['datos_form']['campo1'])) ? $_SESSION['datos_form']['campo1'] : '' ; ?>">
<select class="form-select" name="sexo">
<?php
if( !empty($_SESSION['datos_form']['sexo']) ) {
$sexo = $_SESSION['datos_form']['sexo'];
echo '<option value="'.$sexo.'" selected="selected">'.$sexo.'</option>';
}
else{
echo '<option disabled selected="selected">I am...</option>';
}
?>
<option value="Mem">Men</option>
<option value="Woman">Woman</option>
<option value="I prefer not to say">I prefer not to say</option>
</select>
<?php
if( !empty($_SESSION['datos_form']['condiciones']) ) {
echo '<input type="checkbox" name="condiciones" checked>';
}
else{
echo '<input type="checkbox" name="condiciones">';
}
?>
...
onclick="mostrar_paso('numero de paso') -->
continuar
</div>
<div id="paso2" class="step">
<?php
$r =array(
1 => 'Product 1',
2 => 'Product 2',
3 => 'Product 3',
);
foreach ($r as $key => $value)
{
if( !empty($_SESSION['datos_form']['radio']) AND $_SESSION['datos_form']['radio'] == $key ) {
echo '<input name="radio" type="radio" id="'.$key.'" value="'.$key.'" checked="checked" >';
echo '<label for="'.$key.'" title="'.$value.'">'.$value.'</label>';
}
else{
echo '<input name="radio" type="radio" id="'.$key.'" value="'.$key.'" >';
echo '<label for="'.$key.'" title="'.$value.'">'.$value.'</label>';
}
}
?>
Atras
continuar
</div>
<div id="paso3" class="step">
<div id="div_producto"></div><br>
<input type="text" name="campo3" value="<?= (!empty($_SESSION['datos_form']['campo3'])) ? $_SESSION['datos_form']['campo3'] : ''; ?>">
<input type="submit" name="cancel">
Atras
<input type="submit" name="Terminar">
</div>
</form>
</body>
</html>
I would like to add a cookie to the session where the steps are saved
to avoid erasing the data stored in the session in case the browser is
closed in error, create a session cookie with a validation time of 30
days.
PHP's native session, already using cookie if visitor browser support cookie and the expiration time can be set in php.ini or at runtime by setting session.cookie_lifetime
now to remove the cookie from the data saved by the user create a
cancel button, the cancel button will delete the cookie, including the
data saved in the session.
And finally use session_destroy function to delete that cookie under procesar.php file

Related

Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) at XMLHttpRequest.<anonymous>

I had look to the similar question and its doesn't solve my problem
I want to create file multiple upload system with progressbar using php
and i have this error
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.<anonymous>
my code is
<?php
error_reporting(0);
$state="white";
$count=0;
if(isset($_GET["state"])){
$state=$_GET["state"];
$count=$_GET["count"];
}
?>
<html >
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="keywords" content="كتابك القريب,أدهم شرقاوي,روايات, كتب pdf,تحميل كتب,كتب دراسية,pdf,books">
<meta name="google-site-verification" content="ieyWI-BKgki1_LGBMFqdFYkGyEeHlMSEAodDuxKcN7A" />
<link rel="stylesheet" href="controls.css">
<!--
-->
<style>
.bar
{
position: absolute;
height: 15px;
background-color: rgb(27, 26, 26);
box-shadow:inset 1px 1px 1px 1px #fff5;
width: 80%;
bottom: 45px;
border-radius:15px ;
}
.pbar
{
position: absolute;
height: 15px;
background-color:#941ab4;
width: 0;
border-radius:15px ;
}
</style>
<title>كتابك القريب</title>
<script src="jquery.js"></script>
<script>
var state= <?php echo '"' .$state.'"' ; ?>;
var Vcount= <?php echo $count; ?>;
if (state=="succsses") {$(document).ready(function() { $(".succsses").css("display","block");}); }
</script>
<script>
var state= <?php echo '"' .$state.'"' ; ?>;
if (state=="error") { $(document).ready(function() { $(".error").css("display","block"); }); }
</script>
<script>
$(document).ready(function() {
$(".x").click(function() {
$(".succsses").css("display","none");
});
});
$(document).ready(function() {
$(".x").click(function() {
$(".error").css("display","none");
});
});
</script>
</head>
<body>
<div class="succsses" id="succsses" >
<p><?php if ($state=="succsses") { echo"تم تحميل ($count) ملفات بنجاح" ;}?></p>
<span class="x">x</span>
</div>
<div class="error" id="error" >
<p><?php if ($state=="error") { echo"فشل التحميل " ;}?></p>
<span class="x">x</span>
</div>
<div class="login-form">
<img src="https://yourclosebook.com/res/logos/ryhan.png" alt="" class="ava">
<form action="upload.php" method="post" enctype="multipart/form-data" id="frm">
<input type="email" name="email" id="" placeholder="email (اختياري)">
<input type="file" name="file[]" id="costum-file" accept="application/pdf,application/msword,.docx" multiple >
<input type="submit" value="تحميل" id="upload">
</form>
<div class="bar">
<span class="pbar" id="pb"></span> <span class="ptext " id="pt"></span>
</div>
<P> (*.pdf,*.docx,*.doc,*.ppt,*pptx)يمكنكم تحميل ملفات من الصيغ المدرجة جانبا</P>
<h3 id="friend"> <a href="https://www.yourclosebook.com" target="_blank" > كتابك القريب !</a> صديقك المقرب</h3>
</div>
<style>
</style>
<script src="upload.js"></script>
<script>
document.getElementById('upload').addEventListener('click',function(e){
e.preventDefault();
var f = document.getElementById('costum-file');
var pb = document.getElementById('pb');
var pt = document.getElementById('pt');
app.uploader({
files:f,
porgressBar:pb,
porgressText:pt,
processor:'upload.php',
finished:function(data){
},
error:function(){
}
});
});
</script>
</body>
</html>
uploade.php
<?php
require_once("conn.php");
header("Content-Type:application/json");
$err="";
$UPLOADED=NULL;
$count=0;
$i=0;
$succeded=[];
$faild=[];
for ($i; $i <count($_FILES['file']['name']) ; $i++) {
$target_path="uploads/";
$file=$_FILES['file']['name'][$i];
$file_temp=$_FILES['file']['tmp_name'][$i];
$fileSize =$_FILES['file']['size'][$i];
$fileError =$_FILES['file']['error'][$i];
$fileType =$_FILES['file']['type'][$i];
$fileEXT =explode('.',$file);
$fileRealExt=strtolower(end($fileEXT));
$target_path= $target_path.$file;
$allowed =array('pdf','doc','docx');
if (!empty($file)) {
if (in_array($fileRealExt,$allowed)) {
if ($fileError===0) {
$helpTimes=1;
$email=$_POST['email'];
$email= $db->real_escape_string($email);
$file= $db->real_escape_string($file);
$UPLOADED=move_uploaded_file($file_temp,$target_path);
if ($UPLOADED) {
$insert = $db->query("INSERT INTO user_uploads(email,filepath,upload_time,help_times) VALUES('".$email."','".$file."',NOW(),'".$helpTimes."')");
$count=$i+1;
$succeded=array(
'name'=>$name,
'file'=>$file
);
}else{
$faild= array('name' => $name);
echo header("Location:index.php?state=error&error=failedUpload");
}
}else{
$err= "حدث خطأ غير متوقع";
echo header("Location:index.php?state=error&error=failedUpload");
}
}else{
echo header("Location:index.php?state=error&error=notAcceptedFileFormat");
}
}else{
$err=" يجب اختيار ملف واحد على الاقل";
echo header("Location:index.php?state=error&error=empty");
}
// --------------------
if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeded'=> $succeded,
'faild'=>$faild
));
}
}
echo $err;
if ($count>0) {
//index.php
echo header("Location:index.php?state=succsses&count=$count");
if (!empty($_POST['email'])) {
$email=$_POST['email'];
$from = "MIME-Version: 1.0" . "\r\n";
$from .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$from .= 'From: YOUR CLOSE BOOK TEAM <contact#yourclosebook.com>' . "\r\n";
$s=" رسالة شكر";
$messagge="<H1>باسمنا نحن فريق موقع كتابك القريب نقد لكم فائق الشكر لاجل مساعدتنا بتقديم كتبكم الثمينة</H1>";
$mail= mail($email,$s,$messagge,$from);
if (!$mail) {
echo"email sending error";
}
else{
echo"check your email";
}
}
}else{
echo header("Location:index.php?state=error");
}
upload.js
var app=app ||{};
(function(o){
"use strict";
var ajax,getFormData,setProgress;
ajax =function (data)
{
var xhr= new XMLHttpRequest(),uploaded;
xhr.addEventListener('readystatechange',function()
{
//readyState===4 => done
if (this.readyState===4)
{
/*
status===200=> ok*/
if (this.status===200)
{
uploaded= JSON.parse(this.response);
if (typeof o.options.finished==='function')
{
o.options.finished(uploaded);
}
}
else
{
if (typeof o.options.error==='function')
{
o.options.error();
}
}
}
});
xhr.upload.addEventListener('progress',function(event)
{
var percent;//%
if (event.lengthComputable===true)
{
percent= Math.round((event.loaded/event.total)/100);
setProgress(percent);
}
});
xhr.open('post',o.options.processor);
xhr.send(data);
};
getFormData =function (source) {
var data = new FormData(),i;
for ( i = 0; i < source.length; i++) {
data.append('costum-file[]',source[i]);
}
data.append('ajax',true);
return data;
};
setProgress =function (value) {
if (o.options.porgressBar !== undefined) {
o.options.porgressBar.style.width=value?value+'%':0;
}
};
o.uploader=function (options) {
o.options=options;
if (o.options.files!==undefined) {
ajax(getFormData(o.options.files.files));
}
}
}(app));
There are some issues with your code:
In your main file you have an email element but in your upload.js file you are not adding it to your FormDara object. So in your uploade.php file you don't have access to it and $email=$_POST['email']; will throw an error
In your upload.js you are naming your file objects costum-file fun in your upload.php you are looking for file objects with the name of file. These two should have same name.
echo header("Location:index.php"); is incorrect and you should only use header("Location:index.php");
If you are calling upload.php file via ajax request then you can not do php redirect(header("Location:index.php");). What you should do is to return some json response and then pars it in your main file JavaScript and show relevant messages(Error or success)
So to sum them up what you need to change to fix the error you are getting is(I'm just highlighting the changes and not the whole code):
main(index.php?) file
You need to provide an id for the email element:
<input type="email" name="email" id="email" placeholder="email (اختياري)">
You need to add this email element to your JavaScript call
<script type="text/javascript">
document.getElementById('upload').addEventListener('click',function(e){
e.preventDefault();
var f = document.getElementById('costum-file');
var pb = document.getElementById('pb');
var pt = document.getElementById('pt');
var eml = document.getElementById('email');
app.uploader({
files:f,
porgressBar:pb,
porgressText:pt,
email:eml,
processor:'upload.php',
finished:function(data){
},
error:function(){
}
});
});
</script>
upload.js
You need to change the file element to file and also add the email element in the FormData object
getFormData =function (source) {
var data = new FormData(), i;
for ( i = 0; i < source.length; i++) {
data.append('file[]',source[i]);
}
data.append('email', o.options.email.value);
data.append('ajax', true);
return data;
};
And finally in your upload.php file change all the echo header("Location:index.php") instances with a json encoded string like what you have here:
echo json_encode(array(
'succeded'=> $succeded,
'faild'=>$faild
));
With proper response which then you can parse in your index.php file.
Please give it a try and see if it fixes your issue.

How to Refresh (Update) an HTML Page For New Data After the Submit Button is Pressed

I have an HTML form that is split into three major components. The top portion is essentially a header for displaying a magazine name. This information does not change.
The middle portion is a table developed through a MySQL query for displaying the story information as a table of contents after it is entered in the bottom portion, which is a data entry screen.
The bottom portion, is a data entry screen for entering the information concerning each story contained in the magazine issue.
After entering the data and pressing the submit button in the bottom portion, the middle portion should be updated through the MySQL query to reflect the newly entered story. That was not happening.
Note: The code previously associated with this question has been removed for purposes of clarity. The solution was associated with how the various forms were called. My thanks to Sulthan Allaudeen for providing potential solutions. Currently, I am not familiar with utilizing jquery-ajax. Eventually I will need to learn.
As the OP wanted to know how do the jquery and ajax call
Step 1 :
Recognize the Input
Have a button with a class trigger
$(".trigger").click(function()
{
//your ajax call here
}
Step 2 :
Trigger your ajax call
$.ajax({
type: "POST",
url: "yourpage.php",
data: dataString,
cache: false,
success: function(html)
{
//your action
}
});
Step 3 :
Inside your success function show the result
$("#YourResultDiv").html(data);
For that you should create a div named as YourResultDiv
Note :
Inside your yourpage.php You should just print the table and it will be displayed as the output
Here's a brief example of displaying the results of submitting a form without leaving the current page. Form submission is done with the help of Ajax.
Each form has it's own button for submission, hence the loop over matching elements in onDocLoaded.
1. blank.php form is submitted to this script
<?php
echo "-------------------------------<br>";
echo " G E T - V A R S<br>";
echo "-------------------------------<br>";
var_dump( $_GET ); echo "<br>";
echo "-------------------------------<br>";
echo " P O S T - V A R S<br>";
echo "-------------------------------<br>";
var_dump( $_POST ); echo "<br>";
echo "<hr>";
if (count($_FILES) > 0)
{
var_dump($_FILES);
echo "<hr>";
}
?>
2. blank.html Contains 2 forms, shows the result of submitting either of them to the above script.
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
function allByClass(className,parent){return (parent == undefined ? document : parent).getElementsByClassName(className);}
function allByTag(tagName,parent){return (parent == undefined ? document : parent).getElementsByTagName(tagName);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
function toggleClass(elem, className){elem.classList.toggle(className);}
function toggleClassById(targetElemId, className){byId(targetElemId).classList.toggle(className)}
function hasClass(elem, className){return elem.classList.contains(className);}
function addClass(elem, className){return elem.classList.add(className);}
function removeClass(elem, className){return elem.classList.remove(className);}
function forEachNode(nodeList, func){for (var i=0, n=nodeList.length; i<n; i++) func(nodeList[i], i, nodeList); }
// callback gets data via the .target.result field of the param passed to it.
function loadFileObject(fileObj, loadedCallback){var reader = new FileReader();reader.onload = loadedCallback;reader.readAsDataURL( fileObj );}
function myAjaxGet(url, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("GET", url, true);
ajax.send();
}
function myAjaxPost(url, phpPostVarName, data, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send(phpPostVarName+"=" + encodeURI(data) );
}
function myAjaxPostForm(url, formElem, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("POST", url, true);
var formData = new FormData(formElem);
ajax.send( formData );
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
forEachNode( allByClass('goBtn'), function(elem){elem.addEventListener('click', onGoBtnClicked, false);} );
}
function onGoBtnClicked(evt)
{
evt.preventDefault();
var thisElem = this;
var thisForm = thisElem.parentNode;
myAjaxPostForm('blank.php', thisForm, onPostSuccess, onPostFailed);
function onPostSuccess(ajax)
{
byId('tgt').innerHTML = ajax.responseText;
}
function onPostFailed(ajax)
{
//byId('tgt').innerHTML = ajax.responseText;
alert("POST FAILED!!!!");
}
return false;
}
</script>
<style>
#page
{
display: inline-block;
border: solid 1px gray;
background-color: rgba(0,0,0,0.2);
border-radius: 6px;
}
.controls, .tabDiv
{
margin: 8px;
border: solid 1px gray;
border-radius: 6px;
}
.tabDiv
{
overflow-y: hidden;
min-width: 250px;
background-color: white;
border-radius: 6px;
}
.tabDiv > div
{
padding: 8px;
}
</style>
</head>
<body>
<div id='page'>
<div class='tabDiv' id='tabDiv1'>
<!-- <div style='padding: 8px'> -->
<div>
<form id='mForm' enctype="multipart/form-data" >
<label>Name: </label><input name='nameInput'/><br>
<label>Age: </label><input type='number' name='ageInput'/><br>
<input type='file' name='fileInput'/><br>
<button class='goBtn'>GO</button>
</form>
</div>
</div>
<div class='tabDiv' id='tabDiv2'>
<!-- <div style='padding: 8px'> -->
<div>
<form id='mForm' enctype="multipart/form-data" >
<label>Email: </label><input type='email' name='emailInput'/><br>
<label>Eye colour: </label><input name='eyeColourInput'/><br>
<label>Read and agreed to conditions and terms: </label><input type='checkbox' name='termsAcceptedInput'/><br>
<button class='goBtn'>GO</button>
</form>
</div>
</div>
<!-- <hr> -->
<div class='tabDiv'>
<div id='tgt'></div>
</div>
</div>
</body>
</html>
The solution to refreshing the form to display the addition of new data was to re-call it through the following line: "include("new_stories.inc.php");". This line is imediately executed just after the MySQL insert code in the data entry section of the form.
The middle section of the form "new_stories.inc.php" (the table of contents) queries the MySQL data base to retrieve the story information related to the current magazine issue. Re-calling the form is equivalent to a re-query.

How to keep current page on ajax pagination after editting a row?

The header.php has a <div id="content"></div> and then will load the page user.php
Q1: Is javascript coding on the header.php can not interact with the loaded content?
Therefore I put the js code on the loaded page, but i found a little bit strange.
Q2:
The paging function is working, suppose it is on page 4.
After I editting one of the row, the page go back to first page. I want to keep it on page 4.
< 1 2 3 4 5 6>
I want to store the current link as a text within a after i click the paging, however the link is stored first and then page will refresh and clear the data.
The href of the paging links will look like
localhost://blog/index.php/admin/users/show/10
localhost://blog/index.php/admin/users/show/20
localhost://blog/index.php/admin/users/show/30
Please point out the solution or suggest another better solution
$("input[name=submit]").click(function() {
$(this).parents('.alert-box').hide();
$form = $(this).parent('form');
$.post(
$form.attr('action'),
$form.find(':input').serializeArray(),
function(data) {
$("#content").html(data);
}
);
});
View:header.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link href="<?= $css; ?>bootstrap.css" rel="stylesheet" type="text/css">
<link href="<?= $css; ?>basic/basic.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="<?= $js; ?>jquery.js"></script>
<script type="text/javascript" src="<?= $js; ?>jquery_validate.js"></script>
<script type="text/javascript" src="<?= $js; ?>form_control.js"></script>
<script type="text/javascript" src="<?= $js; ?>additional-methods.min.js"></script>
</head>
<body>
<style>
#content{
background-color: #D0D0D0;
float:left;
width:80%;
}
#main-frame{
width:100%;
}
#list{
width:18%;
float:left;
}
#delete-alert-box{
background-color: #269abc;
position: absolute;
z-index: 99999;
display: none;
}
#edit-alert-box{
background-color: #269abc;
position: absolute;
z-index: 99999;
display: none;
}
body{
font-size:2em;
}
</style>
<script language="javascript">
$(document).ready(function() {
init();
$('.open').click(function(e) {
e.preventDefault();
$.post($(this).attr('href'), function(data) {
$('#content').html(data);
});
});
});
function init() {
$.post(
"<?php echo site_url("admin/users/show");?>", function(data) {
$("#content").html(data);
}
);
}
</script>
<div id="header">
<div id="logo">
</div>
<?php if ($this->AuthModel->check_admin_log()) { ?>
Logout
<?php }
?>
</div>
<ul id="list">
<li>
Users Manage
</li>
<li>
Group Manage
</li>
<li>
Post Mange
</li>
<li>
System Setting
</li>
<li>
<a href="<?php echo site_url('logout/admin') ?>" >Logout</a>
</li>
</ul>
<div id="content" class="box"></div>
view:users.php
<table border="1">
<tr><th>User Id</th><th>User Name</th><th>Email</th><th>Registeration Date</th><th>Group</th><th>State</th><th>Operation</th></tr>
<?php foreach ($users as $user): ?>
<tr>
<td><?= $user->id; ?></td>
<td><?= $user->username; ?></td>
<td><?= $user->email; ?></td>
<td><?= mdate('%Y-%m-%d', $user->registeration_time); ?></td>
<td><?= $user->user_type; ?></td>
<td><?= $user->account_status; ?></td>
<td>
<button type="button" value="<?php echo $user->id; ?>" name="delete">X</button>
<button type="button" value="<?php echo $user->id; ?>" name="edit">edit</button>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php echo $links ?>
<div id="delete-alert-box" class="alert-box">
<div class="cancel">X</div>
<h3>Are you sure to delete the account?</h3>
<form action="<?php echo site_url('admin/users/delete') ?>" id="deleteForm">
<input type="hidden" value="" name="user_id">
<input type="button" value="Yes" name="submit">
<input type="button" value="No" name="cancel">
</form>
</div>
<div id="edit-alert-box" class="alert-box">
<div class="cancel">X</div>
<h3>Edit User:<span id="username"></span></h3>
<form action="<?php echo site_url('admin/users/edit') ?>" id="editForm">
<table>
<tr>
<td>Group</td>
<td>
<select name="group" id="group">
<option value="1">Nomal User</option>
<option value="2">Amin</option>
</select>
</td>
</tr>
<tr>
<td>State</td>
<td>
<select name="state" id="state">
<option value="1">Activated</option>
<option value="2">Non-Activated</option>
<option value="3">Blocked</option>
</select>
</td>
</tr>
</table>
<input type="hidden" value="" name="user_id">
<input type="button" value="Yes" name="submit">
<input type="button" value="No" name="cancel">
</form>
</div>
<script>
$(document).ready(function() {
$(".cancel").click(function() {
$(this).parent('.alert-box').hide();
});
$("input[name=cancel]").click(function() {
$(this).parents('.alert-box').hide();
});
$("button[name=delete]").click(function() {
var $user_id = $(this).attr('value');
if ($user_id !=<?php echo $this->session->userdata('user_id') ?>) {
$("#delete-alert-box").show();
$('#delete-alert-box').find('input[type=hidden]').attr('value', $user_id);
}
});
$("button[name=edit]").click(function() {
var $user_id = $(this).attr('value');
if ($user_id !=<?php echo $this->session->userdata('user_id') ?>) {
$("#edit-alert-box").show();
var $tr = $(this).parents('tr');
var $tds = $tr.find('td');
$('#edit-alert-box').find('input[type=hidden]').attr('value', $user_id);
$('#group').find('option').each(function(index) {
$(this).removeAttr('selected');
});
$('#group').find("option[value=" + get_group_code($($tds[4]).html()) + "]").attr('selected', 'selected');
$('#state').find("option[value=" + get_account_code($($tds[5]).html()) + "]").attr('selected', 'selected');
}
});
$("input[name=submit]").click(function() {
$(this).parents('.alert-box').hide();
$form = $(this).parent('form');
$.post(
$form.attr('action'),
$form.find(':input').serializeArray(),
function(data) {
$("#content").html(data);
}
);
});
$('.paging a').click(function(e) {
e.preventDefault();
$.post($(this).attr("href"), function(data) {
$("#content").html(data);
});
});
});
function get_group_code(name) {
switch (name) {
case "Normal User":
return 1;
case "Admin":
return 2;
}
}
function get_account_code(name) {
switch (name) {
case "Activated":
return 1;
case "Non-Activated":
return 2;
case "Blocked":
return 3;
}
}
</script>
Controller: admin/users.php
function pagination() {
$this->load->library('pagination');
$config['base_url'] = site_url('admin/users/show');
$config['total_rows'] = $this->UsersModel->get_num_rows();
$config['per_page'] = '10';
$config['uri_segment'] = 4;
$config['full_tag_open'] = '<p class="paging">';
$config['full_tag_close'] = '</p>';
$this->pagination->initialize($config);
return $this->pagination->create_links();
}
public function show() {
$data['users'] = $this->UsersModel->get_users(10, $this->uri->segment(4, 0));
$data['links'] = $this->pagination();
$this->load->view('admin/users', $data);
}
public function delete() {
$user_id = $this->input->post('user_id');
if (!$this->UsersModel->delete_user($user_id)) {
echo "Unknown error";
}
$this->show();
}
public function edit() {
$user_id = $this->input->post('user_id');
$state = $this->input->post('state');
$group = $this->input->post('group');
$data = array(
'id' => $user_id,
'account_status_code' => $state,
'group_status_code' => $group
);
if (!$this->UsersModel->edit_user($data)) {
echo "Unknown error";
}
$this->show();
}
The paging function is working, suppose it is on page 4. After I
editting one of the row, the page go back to first page. I want to
keep it on page 4.
When opening that 4-th page in a browser, you can save its number in session and then after editing you can read that value you stored in session i.e - 4.
#session_start();
function indexAction()
{
$_SESSION['curr_page'] = 4; // or take it from $_GET
}
function saveAction(){
// .... do stuff....
header('location: page.php?page=' . $_SESSION['curr_page']);
}
first the best way to do paging is via get, to get the url friendly and rotating the User in case it needs to pass it on.
you need set data in console.log(), for view if data this value,
if the expected values ​​are coming up to the date, try switching by append html:
example.
$ ("# content") html ('.');
$ ("# content") append (date).;

How to access a model method with javascript

Please have a look at the below CakePHP code
Flip2.php (Model)
<?php
class Flip2 extends AppModel {
var $name = 'Flip2';
public $useTable = false;
//Increment the correct_answer field of the specific user
public function correctAnswer($userID=89, $word)
{
$setQuery = "UPDATE `users_words` SET `correctanswer` = `correctanswer`+1 WHERE `userid`=$userID && `wordid`='$word' ";
query($setQuery);
}
}
Flip2Controller.php (Controller)
<?php
class Flip2Controller extends AppController {
public function index()
{
}
}
?>
index.ctp (View)
<?php
//echo $this->Html->css(array('bootstrap', 'mark', 'style'));
echo $this->Html->script(array('timer','swfobject','bootstrap.min.js'));
?>
<style>
#hideall {
display: none;
opacity: 0.7;
position: fixed;
height: 100%;
width: 100%;
top: 0;
left: 0;
background: #000;
border: 1px solid #cecece;
z-index: 1;
vertical-align:middle;
text-align:center;
}
.removeCardflip{
transition: rotateY(0deg);
-webkit-transition: rotateY(0deg);
transition-duration: 0s;
}
/* SECTIONS */
.section {
clear: both;
padding: 0 10px 0 10px;
margin: 0px;
}
</style>
<div id="hideall">
<?php //echo $this->Html->image('progress.gif', array('alt' => 'Wait', 'style' => 'text-align:center; padding-top:200px;'));?>
</div>
<!--<div class="wrapper" style="border: 1px solid red; width: 100%;">-->
<div class="section group" style="margin-top: 50px;">
<div class="col span_3_of_3">
<h3 style="margin:0px; font-size:22px;">Play word game: </h3>
</div>
</div>
<div class="">
<div>
<div>
<span class="remainWords"><?php //echo count($words);?></span> oxxxxxxxxxxxxxxxf <?php //echo $totalWords;?>
</div>
<div>
<?php
echo $this->Html->image("comic_edit.png",
array(
"alt" => "Pareto List",
"id" => "paretoList",
'url' => "javascript:;"
)
);
?>
</div>
</div>
</div>
<div class="container"><div class="row">
<?php
foreach($worddeck as $worcard)
{
?>
<div class="xy col-lg-3 col-md-4 col-sm-6 img-rounded" id="card1" style="width:250px; height:200px; background-color:grey; heiht:170px; margin: 10px 10px;">
<div id="enside1" >
<h1 data-pos="<?php //echo ; ?>" ><?php echo $worcard['unique_wordsforcards']['en_word']; $enSpell = $worcard['unique_wordsforcards']['en_word']; ?></h1>
</div>
<div id="ptside1" style="display:none;">
<?php echo $phonemer[$enSpell]; ?>
<p><?php echo $worcard['unique_wordsforcards']['hint']; ?></p>
</div>
<div id="cntrol1">
<button type="button" id="2" class="a btn btn-success mr5 btn-lg">Acertei</button>
<button type="button" id="2" class="e btn btn-danger mr5 btn-lg">Errei</button>
</div>
</div>
<?php
}
?>
</div></div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script type="text/javascript">
$(document).ready(function(){
$( ".btn-danger" ).click(function(){
console.log("Red Button");
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
console.log( "The act has been done");
toclose.toggle();
});
});
$( ".btn-success" ).click(function(){
console.log("Red Button");
var toclose = $(this).parent().parent();
$.ajax({
url: "../img/media.jpg",
}).done(function() {
console.log( "The act has been done");
toclose.toggle();
});
});
$( ".xy" ).click(function(){
$(this).find("#enside1").toggle();
$(this).find("#ptside1").toggle();
console.log(this);
});
});
</script>
Now, what I need to do is, this. When the user click on the Acertei button, I need to execute the function correctAnswer. I am very new to PHP and CakePHP so I am really confused about how to do this when a button is clicked. Any advice please?
You have
<div id="cntrol1">
<button type="button" id="2" class="a btn btn-success mr5 btn-lg">Acertei</button>
<button type="button" id="2" class="e btn btn-danger mr5 btn-lg">Errei</button>
</div>
You should use different IDs for each button.
You can call the correctAnswer function with ajax:
Change the button to something like
<button type="button" id="2" data-word="<?php $worcard['unique_wordsforcards']['en_word'] ?>" class="a btn btn-success mr5 btn-lg">Acertei</button>
And then add the following code in $(document).ready()
$(document).ready(function(){
$(".btn-success").click(function(){
var word = $(this).data('word');
$.post('/flip2/correct.json', { word: word })
.done(function(data) {
alert('Saved');
});
I am not sure how the user part works. You should probably have that in the session, and not sent to the function. I hardcoded user 89 and added a way for you to send the word.
Use an appropriate model method
The function correctAnswer in the model would better be written using updateAll:
public function correctAnswer($userId, $word) {
return $this->updateAll(
array('correctanswer' => 'correctanswer + 1'),
array(
'userid' => $userId,
'wordid' => $word
)
);
}
Written in this way the inputs ($userId and $word) will be escaped appropriately and not susceptible to sql injection.
Create a controller action
The doorway to the web for an application is a controller action, create a simple function, calling the model method, and write it to output json:
public function correct() {
$postData = $this->request->data;
$word = $this->request->data['word'];
$userId = $this->Auth->user('id');
$result = false;
if ($userId && $word) {
$result = $this->Flip2->correctAnswer($userId, $word);
}
$this->set('_serialize', array('result'));
$this->set('result', $result);
}
Note that
It'll only work via a post request.
The Auth component (the session) is used to get the current user id, it's not a user-defined input.
This function is defined such that it'll work as a json response.
There's no need to create a view file with the above code.
Be sure to setup your app to handle json requests:
After adding Router::parseExtensions('json'); to your routes file, CakePHP will automatically switch view classes when a request is done with the .json extension, or the Accept header is application/json.
Call the controller action
The required js would be of the form:
$(".btn-success").click(function(){
var word = ...;
$.post(
'/flip2/correct.json',
{word: word},
function (data) {
console.log(data);
// {result: bool}
}
);
});
Note that:
The url ends in .json which is a simple and robust way to provoke CakePHP to respond as json.
It is a post request.
The response will be of the form defined by _serializein the controller action.

jquery popup div and update mysql record

First time poster! Apologies for the large about of code.
The plan is to have a list of users and on clicking on each user a div popup will appear allowing changes to the users details.
Rather than the popup closing when the record is updated I'd like the popup to remain open and show the new details.
At the moment I can open the popup and edit the form without the popup closing. As soon as I add the following the form closes on submit.
$( "#popup > #skills" ).load( "popup_u_skills.php?uid=" + uid );
If I pass don't pass a variable in the url then the popup stays open. The BIG problem I have is that I need to variable to be passed to get the users information from my DB.
My code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
// show popup
$(".showpopup").click(function() {
// user id variable
var uid = $(this).attr( "uid" );
$("#popup").fadeIn();
$( "#popup > #details" ).load( "popup_u_details.php?uid=" + uid ).show();
//$( "#popup > #skills" ).load( "popup_u_skills.php?uid=" + uid );
// close popup
$(".closepopup").click(function() {
$("#popup").fadeOut();
});
// open inner options within popup
$(".open_inner_popup").click(function() {
var inneropt = $(this).attr( "option" );
$( "#details, #skills, #history" ).hide();
$.get( "pop_u_skills.php", { uid : uid } );
$( "#"+inneropt ).show();
});
// if change of skill
$("#chg_skill").click(function(event){
// use gloabel uid variable from openpopup
var user = uid;
// set array variable
var selected = new Array();
// foreach checkbox cheked pushed into array
$("input:checkbox[name=checkbox]:checked").each(function() {
selected.push($(this).val());
});
// prevent form action
event.preventDefault();
// post selected array and uid to php page
$.post(
"run_php.php",
{ name: selected, uid: user },
function(data) {
$('#stage').show();
$('#stage').html("Saved!" + data);
});
});
// end open popup
});
// end dom
});
</script>
<style>
#popup {
width:400px;
padding:10px;
display:none;
-webkit-box-shadow: 3px 3px 3px 0px #EEE;
box-shadow: 3px 3px 3px 0px #EEE;
border:1px solid #CCC;
-webkit-border-radius: 5px;
border-radius: 5px;
z-index:1;
}
.closepopup {
color:#FF0000;
font-weight:bold;
text-decoration:none;
}
#stage {
display:none;
color:#009900;
}
#details, #skills, #history {
display:none;
}
</style>
</head>
<body>
<?
$uid = date("H:s:i");
?>
<div id="overlay">
<div class="showpopup" uid="<? echo $uid; ?>">Popup</div>
<div id="popup">
x
<br>
Details Skills History
<div id="details"><? include "popup_u_details.php"; ?></div>
<div id="skills"><? include "popup_u_skills.php"; ?></div>
<div id="history">History</div>
</div>
</div>
</body>
</html>
POPUP_U_SKILLS.PHP
<div id="stage"> </div>
<? echo $_GET["uid"]; ?>
<form name="form1" method="post" action="">
<p>Option 1
<input type="checkbox" name="checkbox" value="1">
</p>
<p>
Option 2
<input type="checkbox" name="checkbox" value="2">
</p>
<p>
Option 3
<input type="checkbox" name="checkbox" value="3">
</p>
<p>
<input type="submit" name="chg_skill" id="chg_skill" value="Update">
</p>
</form>
After re-visiting jquery I have discovered the answer to my problem. Quite simple really.
To keep the popup div open on clicking a submit button within it I needed to include the code below within the submit function. e.g.
$(".submitwithinpopup").click(function() {
Do stuff...
// don't close popup afterwards
return false;
});

Categories