save jquery flip state into a php session variable? - php

I am using this tutorial http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_slide_toggle
Here is the code without the style.
<script type="text/javascript">
$(document).ready(function()
{
$(".flip").click(function()
{
var panel = "open";
$(".panel").slideToggle("slow");
});
});
</script>
How would I go about saving the state of this so if I refreshed the page it would remain open or closed. I imagine a php session would be the correct way, but how do I write that in the javascript?

In JS:
var readWirite='write'; //or 'read'
$.ajax({
type: "POST",
url: "myPhpFile.php",
data: "panel="+panel+"&readWrite="+readWrite;
success: function(msg){
if(msg == '1'){
alert('Horay panel saved!');
} else {
$('#panelId').html(msg); //Write saved panel back to html
}
}
});
In myPhpFile.php:
<?php
if(!isset($_SESSION)) session_start();
if(isset($_POST['readWrite']) && isset($_POST['panel'])){
if($_POST['readWrite'] == 'write'){
$result = '0';
if($_SESSION['panel'] = $_POST['panel']) $result = '1';
echo $result;
} else if($_POST['readWrite'] == 'read') {
echo $_SESSION['panel'];
}
}
?>

Related

PHP codeigniter login error using flex auth

I am using Codeigniter 3, and I am struggling to make a simple login using flex auth, but it is not working at all.. The code used is similar to the one below:
function login_via_ajax()
{
if ($this->input->is_ajax_request())
{
$this->load->model('pat_auth_model');
$this->pat_auth_model->login_via_ajax();
$this->session->set_flashdata('message', $this->flexi_auth->get_messages());
if ($this->flexi_auth->is_logged_in()) {
$this->errorData['success'] = true;
} else {
$this->errorData['success'] = false;
}
$this->errorData['message'] = (! isset($this->errorData['message'])) ? $this->session->flashdata('message') : $this->errorData['message'];
die(json_encode($this->errorData));
}
else
{
/* Load Template */
$this->template->auth_render('auth/login', $this->data);
}
}
As supposed, if the username and password are correct, the jQuery script below should have toked me to the desired page:
<script>
$(document).ready(function(){
$('form').submit(function(e) {
e.preventDefault();
var submit_url = $(this).attr('action');
var $form_inputs = $(this).find(':input');
var form_data = {};
$form_inputs.each(function() {
form_data[this.name] = $(this).val();
});
$.ajax({
url: submit_url,
type: 'POST',
data: form_data,
dataType: 'json',
success:function(data) {
if (data['success'] == true) {
window.location.href = "<?= base_url();?>admin/dashboard"
}
else {
$('#ajxError').html('<button class="close" data-close="alert"></button>'+data['message']);
$('#ajxError').show();
}
}
});
});
});
</script>
I tried even to get the session variables like this:
die(print_r($this->session->userdata())); //print all session data
It seems that the app is granting permissions to the user and then deletes all session variables and then gets me back to the login page..
Does anyone know how to deal with that?
Thank you!

Click button and windows confirmation to update query and redirect page

i have problem with redirect page and query update. If i clicked button, there is an windows confirmation, if i click yes, i call ajax to send data to my php page, and my php page do a query. After success, i want redirect to another page. This is my html code
$(document).on("click", "#tombolvalidasi", function() {
var pil = <?php echo $_GET['pilih']; ?>;
var r = confirm("Validasi Pesanan?");
if (r == true)
{
$.ajax({
type: "GET",
url: host+'/skripsi3/web/validasipesan.php',
data: { "id": pil},
success: function (data){
if (data == "success") {
window.location = "pesanvalid.php?pilih="+pil;
}
},
error: function (e) {
alert('Fail');
}
});
}
else
{
}
});
and this is my php code
<?php
session_start();
include "connectdb.php";
$idacara = mysql_real_escape_string($_GET["id"]);
$cons = "Accepted";
$query="UPDATE `preorder` SET `statuspesanan`='$cons' WHERE `id_acara`='$idacara'";
$result = mysql_query($query);
echo "success";
?>
Hope someone can tell me what's wrong with my code. Thank You Guys and
Have a nice day!! Cheers!!

How to run PHP with Ajax to validate results?

I'm making a Ajax script which validates results with PHP file before processing. Below is my Ajax script but I don't understand how to retrieve this DATA to validate.php and how to get results back from my PHP file.
<script>
function shake(){
if($("#pw").val()=="")
{
$("#sc1810").effect("shake");
}
else{
var image = document.getElementById('go');
image.src="images/loader.gif";
var resultado="";
$.ajax({
url: "validate.php",
type: "POST",
data: "userID=" + $("#userID").val()+"&pw=" + $("#pw").val(),
success: function(data){
resultado=data;
image.src="images/png17.png";
if(resultado==0)
{
$("#sc1810").effect("shake");
$("#pw").val("");
$("#pwID").text("Password");
$("#pw").focus();
}
else{
image.src="images/png17.png";
window.location.href = resultado;
}
}
});
}
}
</script>
How can I process this Ajax script with validate.php ?
Can it be like:
<?php
// Get values from AJAX
$userid = $_GET['userID'];
$pass = $_GET['pw'];
?>
What results is this Ajax script expecting? I see resultado==0
So my question is how can I send resultado=1 with PHP to this script?
Should it be:
<?php
// Send result to AJAX
$resultado = 1;
?>
Thank you for helping.
I think this is what you're asking for.
The php script at the bottom is missing the closing tag for a reason.
In the success function, after you parse the result into a json object, you can reference the members with a '.' E.G result.varName
<script>
function shake()
{
if($("#pw").val()=="")
{
$("#sc1810").effect("shake");
}
else
{
var image = document.getElementById('go');
image.src="images/loader.gif";
var resultado="";
$.ajax({
url: "validate.php",
type: "POST",
data: {userID: $("#userID").val(), pw: $("#pw").val()},
success: function(data){
try
{
var result = $.parseJSON(data);
// result is now a JSON object
}
catch (e)
{
alert("JSON Parsing Failed on" + data );
return 0;
}
console.log(result);
if(result.isValid === 1){
// do something
}
alert(result.Message);
resultado=data;
image.src="images/png17.png";
if(resultado==0)
{
$("#sc1810").effect("shake");
$("#pw").val("");
$("#pwID").text("Password");
$("#pw").focus();
}
else
{
image.src="images/png17.png";
window.location.href = resultado;
}
}
});
}
}
</script>
<?php
if( !isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD'] != 'POST')
{
exit;
}
if( !isset($_POST['userID']) || !isset($_POST['pw']) )
{
// need more validation than this
exit;
}
$output = array();
$output['isValid'] = '1';
$output['Message'] = 'Data transfered';
$output['moreData'] = false;
echo json_encode($output);
Change data: "userID=" + $("#userID").val()+"&pw=" + $("#pw").val(), to:
data: {userID: $("#userID").val(), pw: $("#pw").val()}
Also, I'd recommend setting userID and pw vars before passing it in as it is easier to read and easier to maintain.

Ajax loaded page, pass POST data

I have all my webpages loaded with ajax, I'm not sure how to include POST data from the loaded page. The goal is to have a registration form and post that data to another php file and have it processed there.
ajaxloader.js
$(document).ready(function(){
checkURL();
$('ul li a').click(function (e){
checkURL(this.hash);
});
setInterval("checkURL()",250);
loadPage('#Home');
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
loadPage(hash);
}
}
function loadPage(url)
{
url=url.replace('#','');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
success: function(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg);
}
}
});
}
load_page.php
if(!$_POST['page']) die("0");
$page = $_POST['page'];
if(file_exists($page.'.php'))
echo include($page.'.php');
else echo 'There is no such page!';
?>
Any ideas?
So your load_page.php woudl look like
if(!$_POST['page']) die("0");
$page = $_POST['page'];
ob_start();
if(file_exists($page.'.php'))
include($page.'.php');
else echo 'There is no such page!';
$content = ob_get_clean();
echo $content;
This should do the job. HOWEVER, you can't just pass the whole website like that, you need to base64_encode() it make sure everything is ok. And then take a look at this
http://phpjs.org/functions/base64_decode/

php header is working but with mistakes

Actually I'm trying to redirect to the index after logging in with ajax button
but what is happening is strange , header is not taking me to the index.php !
i just get the HTML code of the index.php in my login.php page !!
I'm using Smarty to separate the html from php code , and I don't know how to fix the problem !
click the login and get the HTML of the index in login page !
why ?
in login.php page
if ($_POST['action'] == 'login') {
$_SESSION['username'] = $username;
header("Location: index.php");
exit();
}
the ajax function :
function ajax3(Div_Submit,Div_Response,SuccessScript,Data_Submit)
{
var Type = 1;
var Aj_type = "POST";
var post_data = '';
if(!Data_Submit)
post_data = $('#'+Div_Submit+' *').serialize();
else
post_data = Data_Submit;
$.ajax({
type: Aj_type,
url: document.URL,
data: post_data,
dataType: "text",
beforeSend: function(xhr)
{
$.blockUI({ message: '<img src="images/loading.gif" />',
css: { border: 'none', backgroundColor: 'transparent' } });
xhr.setRequestHeader("Ajax-Request", "true");
},
success: function(response) {
$('#'+Div_Response).html(response+'<script>'+SuccessScript+'</script>');
},
complete: function(){
$.unblockUI();
}
});
return false;
}
the html button call :
<div class="buttons" >
<a class="positive" onclick="$('#login_action').val('login');ajax3('login_form','login_form','','')">
<img src="images/checkbox_checked.png" alt=""/>
<font size="3px"> login </font>
</a>
</div>
That wouldn't work as what you expected.
It should be something like this.
if ($_POST['action'] == 'login') {
$_SESSION['username'] = $username;
echo "success";
}
On your javascript/jquery file.
have something like this
jQuery.ajax({
url: "login.php",
success:function(data){
if(data == "success") window.location = "index.php";
}
});
With AJAX, this is the expected output. What happens is that the AJAX request itself is being redirected to index.php, which I what is then outputted and returned to that request.
If you want to redirect to index.php from AJAX, you would need to exit with a specific code, or a JSON-encoded value and catch that in the AJAX result itself.
Example:
if ($_POST['action'] == 'login') {
$_SESSION['username'] = $username;
echo json_encode(array('redirect' => 'index.php'));
exit;
}
JavaScript:
$.ajax(
url: 'your-url',
success: function(data) {
if (data.redirect) {
document.location.href = data.redirect;
}
}
);
u can get success response whenever login credentials are appropriate , at that moment change the window location using javascript or jquery..

Categories