I have an Ajax script on a PHP page which is to run a php script on clicking a button.
The code is as follows:
<script>
$('#signup-form').submit(function(e){
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: 'insertfromsession.php',
type: 'POST',
data: $(this).serialize(), // it will serialize the form data
dataType: 'html'
})
.done(function(data){
$('#form-container').fadeOut('slow', function(){
$('#form-container').fadeIn('slow').html(data);
});
document.getElementById('submitBtn').disabled = true;
document.getElementById("submitBtn").value="Thanks!";
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
});
When I first open the web page the script isn't run, but if i click back and repeat the process the script executes without an issue. Does anyone know what is causing the issue?
Insert.php which runs this code is here:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="js/submit.js"></script>
<!-- /.website title -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<!-- CSS Files -->
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="fonts/icon-7-stroke/css/pe-icon-7-stroke.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet" media="screen">
<link href="css/owl.theme.css" rel="stylesheet">
<link href="css/owl.carousel.css" rel="stylesheet">
<style type="text/css">
body { background: white !important; } /* Adding !important forces the browser to overwrite the default style applied by Bootstrap */
</style>
<!-- Colors -->
<link href="css/css-index.css" rel="stylesheet" media="screen">
<!-- <link href="css/css-index-green.css" rel="stylesheet" media="screen"> -->
<!-- <link href="css/css-index-purple.css" rel="stylesheet" media="screen"> -->
<!-- <link href="css/css-index-red.css" rel="stylesheet" media="screen"> -->
<!-- <link href="css/css-index-orange.css" rel="stylesheet" media="screen"> -->
<!-- <link href="css/css-index-yellow.css" rel="stylesheet" media="screen"> -->
<!-- Google Fonts -->
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Lato:100,300,400,700,900,100italic,300italic,400italic,700italic,900italic" />
</head>
<div id="top"></div>
<div class="fullscreen landing parallax" style="background-image:url('images/fireworks.jpg');" data-img-width="2000" data-img-height="1333" data-diff="100">
<div class="overlay">
<div class="container">
<div class="row">
<div class="col-md-10">
<!-- /.logo -->
<!-- /.main title -->
<h2 class="wow fadeInLeft">Thank you for submitting your details</h2>
<h2 class="wow bounce infinite">While you are here, why not apply for one of other fantastic products?</h2>
<?php
session_start();
include ("dbconnect.php");
// prepare and bind
$stmt = $conn->prepare("INSERT INTO wills (forename,surname,postcode,telno,email,ipaddress,capturedate,url,user) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssssss", $forename, $surname, $postcode, $telno, $email, $ipaddress, $capturedate, $url, $user);
$forename = $_POST["forename"];
$surname = $_POST["surname"];
$postcode = $_POST["postcode"];
$telno = $_POST["telno"];
$email = $_POST["email"];
$ipaddress = $_SERVER['REMOTE_ADDR'];
$capturedate = date('Y-m-d H:i:s');
$url ="www.test.com";
$user ="testuser";
$_SESSION["forename"] = $forename;
$_SESSION["surname"] = $surname;
$_SESSION["postcode"] = $postcode;
$_SESSION["telno"] = $telno;
$_SESSION["email"] = $email;
$_SESSION["ipaddress"] = $ipaddress;
$_SESSION["capturedate"] = $capturedate;
$_SESSION["url"] = $url;
$_SESSION["user"] = $user;
echo "<br>"."Forename: ".$forename."<br>";
echo "Surname: ".$surname."<br>";
echo "Telno: ".$telno."<br>";
echo "Email: ".$email."<br>";
echo "IP Address: ".$ipaddress."<br>";
echo "Session User: ".$_SESSION["user"]."<br>";
if (!$stmt->execute()) {
echo $stmt->error;
} else {
}
$stmt->close();
$conn->close();
?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="text-center">Back to Main Page</div>
<div class="col-md-12">
<!-- /.product 1 -->
<div class="col-sm-6 feat-list">
<i class="pe-7s-phone pe-5x pe-va wow fadeInUp"></i>
<div class="inner">
<h4>Grab a Mobile SIM</h4>
<p>With a SIM only contract, you get the all the benefits of an ongoing contract, without the additional high cost of a handset.
Short-term SIM only contracts give you freedom and flexibility. All the networks offer them from as little as 30 days, and you can then keep them rolling month-by-month
</p>
<form method="post" id="signup-form" autocomplete="off">
<div class="form-group">
<input type="submit" class="btn btn-success btn-block btn-lg" id="submitBtn" value="Apply for Mobile Sim?">
</div>
</form>
</div>
</div>
<!-- /.product 2 -->
<div class="col-sm-6 feat-list">
<i class="pe-7s-like2 pe-5x pe-va wow fadeInUp"></i>
<div class="inner">
<h4>Debt Plan</h4>
<p>Do you have more than £5,000 worth of debt?<br>
Do you need help to reduce the monthly payments?<br>
If so, find out if you qualify to write off up to 80% of your debt here</p>
<form method="post" id="signup-formdebt" autocomplete="off">
<div class="form-group">
<input type="submit" class="btn btn-success btn-block btn-lg" id="submitBtndebt" value="Get help now">
</div>
</form>
</div>
</div>
</div>
<!-- /.footer -->
<footer id="footer">
<div class="container">
<div class="col-sm-4 col-sm-offset-4">
<!-- /.social links -->
<div class="social text-center">
<ul>
<li><a class="wow fadeInUp" href="https://twitter.com/"><i class="fa fa-twitter"></i></a></li>
<li><a class="wow fadeInUp" href="https://www.facebook.com/" data-wow-delay="0.2s"><i class="fa fa-facebook"></i></a></li>
</ul>
</div>
<i class="pe-7s-up-arrow pe-va"></i>
</div>
</div>
</footer>
<!-- /.javascript files -->
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/custom.js"></script>
<script src="js/jquery.sticky.js"></script>
<script src="js/wow.min.js"></script>
<script src="js/owl.carousel.min.js"></script>
<script>
new WOW().init();
</script>
</body>
<script>
$( document ).ready(function() {
$('#signup-form').submit(function(e){
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: 'insertfromsession.php',
type: 'POST',
data: $(this).serialize(), // it will serialize the form data
dataType: 'html'
})
.done(function(data){
$('#form-container').fadeOut('slow', function(){
$('#form-container').fadeIn('slow').html(data);
});
document.getElementById('submitBtn').disabled = true;
document.getElementById("submitBtn").value="Thanks!";
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
});
});
</script>
<script>
$( document ).ready(function() {
console.log( "ready!" );
$('#signup-formdebt').submit(function(e){
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: 'insertfromsessiondebt.php',
type: 'POST',
data: $(this).serialize(), // it will serialize the form data
dataType: 'html'
})
.done(function(data){
$('#form-container').fadeOut('slow', function(){
$('#form-container').fadeIn('slow').html(data);
});
document.getElementById('submitBtndebt').disabled = true;
document.getElementById("submitBtndebt").value="Thanks!";
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
});
});
</script>
</html>
I think I solved the issue and it has nothing at all to do with the AJAX. It actually appears to be an issue with the session variables. I moved the session variables on the insert.php right to the top before anything else and this makes it work as intended.
Thanks for your efforts guys
You should use a document.ready function. Here is a link to the jQuery version documentation : https://learn.jquery.com/using-jquery-core/document-ready/
Related
So, i want to populate div with id "listberita" with html code from ajax response.
Here is the php code where contain div with "listberita" id
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Jabary - Website Budaya Jabar</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/f8535c9b97.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="berita.css">
</head>
<body>
<!-- Navbar -->
<?php include 'php/navbar.php'; ?>
<div class="container my-5">
<div class="kategoricaption mb-5">
<div class="row">
<div class="col">
<h1 class="text-center fw-bold judulkategori">Berita</h1>
<hr class="mx-auto" style="width:10%; background-color: #f49f16;">
</div>
</div>
</div>
<div class="card-group vgr-cards" id="listberita">
</div>
</div>
<!-- footer -->
<?php include 'php/footer.php'; ?>
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="js/bootstrap.bundle.min.js "></script>
<script src="berita.js"></script>
</body>
</html>
Here is my ajax js code
$(this).ready(function() {
getNews()
function getNews() {
$.ajax({
type: "GET",
url: "_php/getBerita.php",
dataType: "JSON",
success: function(response) {
var kode;
$.each(response, function(i, obj) {
console.log(kode)
kode += '<div class="card kartu pb-3"><div class="card-img-body"><img class="card-img" src="img/Berita/' + obj.gambar_berita + '" alt="Card imagecap"></div><div class="card-body"><h4 class="card-title">' + obj.nama_berita + '</h4><p class="card-text">' + obj.keterangan_berita.substring(0, 250) + '....</p>Read More</div></div>'
$('#listberita').html(kode);
})
}
});
}
})
Here is my php code where ajax request to (php_/getBerita.php)
<?php
include '../koneksi.php';
$result = $conn->query("SELECT * from tbl_berita");
while($row=$result->fetch_assoc()){
$data[]=$row;
}
echo json_encode($data);
?>
The code above is working, it's return the data i want. But there is a problem.
Here is the problem
How to get rid the "undefined" thing on the beginning of div?
Try changing your var kode; to var kode = "";.
When you define the variable without initializing it, it will be undefined. And then your loop is appending text to an undefined variable. That's probably why.
I have been able to implement the same UI Logic for the Web App I found on this URL, and now I am stuck on the Backend Logic that generated the Merged images (i.e the Cropped Image and the placeholder image as seen on the page) and Renders it to the DOM.
As it is right now, my AJAX never resolves with the success callback, instead, it always resolves with the error callback and I have no clue what I am doing wrong, please?
How can I achieve exactly the same backend logic has seen from the web app in this URL:
https://rhapsodyofrealities.org/rhapathon/?
Using PHP, this is what I have so far for the Backend Logic.
Problem with this method is, it tries to output the image directly to the page:
$targetDir = "uploads/";
$fileName = $targetDir.'complete_'.time().".png";
if(isset($_POST['image'])) {
$placeholder = './rhapathon.jpeg';
$src = $_POST['image'];
list($width, $height) = getimagesize($src);
// $placeholder = imagecreatefromstring(file_get_contents($placeholder));
$placeholder = imagecreatefromjpeg($placeholder);
// $src = imagecreatefromstring(file_get_contents($src));
$src = imagecreatefrompng($src);
imagecopy($placeholder, $src, 200, 200, 0, 0, 300, 300);
header('Content-Type: image/png');
// $imgobj = array("img" => imagepng($placeholder, $fileName));
// $result = json_encode($imgobj);
// echo $result;
imagepng($placeholder);
// Free Memory
imagedestroy($placeholder);
imagedestroy($src);
}
?>
My HTML with the Entire UI and Client Logic:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<meta name=description content="Christ Embassy Kubwa Church">
<meta name=viewport content="width=device-width, initial-scale=1">
<title>Good Miracle Friday Crusade Flyer Generator</title>
<!-- <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap-reboot.min.css"> -->
<!-- <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap-grid.min.css"> -->
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css">
<!-- <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.4/croppie.css"> -->
<link rel="stylesheet" type="text/css" href="./node_modules/croppie/croppie.css">
<link rel="stylesheet" type="text/css" href="./index.css">
</head>
<body>
<!-- Header -->
<header class="container-fluid p-0 text-center rounded-0 m-0 mb-5">
<div class="jumbotron p-2 bg-info rounded-0 m-0">
<h1 class="font-weight-lighter display-5 text-white">GOOD MIRACLE FRIDAY CRUSADE</h1>
</div>
</header>
<!-- /Header -->
<div class="container">
<!-- Card -->
<div class="card mx-auto rounded-top rounded-bottom" style="overflow: hidden;">
<!-- Card-Head -->
<div class="card-heading bg-dark text-white p-2 lead font-weight-light">Create Avatar</div>
<!-- /card-Head -->
<!-- Card-Body -->
<div class="card-body">
<div class="row">
<div class="col-md-4 text-center">
<div id="upload-demo" style="width:350px"></div>
</div>
<!-- Col -->
<div class="col-md-4" style="padding-top:30px;">
<div class="mt-0 mb-5">
<strong>STEP 1 : Select Image and adjust to fit</strong>
<input type="file" id="upload" name="fileToUpload">
</div>
<div class="mt-0 mb-5">
<strong>STEP 2 : Upload Image and Download</strong>
<br>
<button class="btn btn-info upload-result">Upload Image</button>
</div>
</div>
<!-- /Col -->
<!-- Col -->
<div class="col-md-4">
<div id="upload-demo-i" style="background:url('./rhapathon.jpeg'); background-size: 300px 300px; width:300px;height:300px;margin-top:30px">
</div>
</div>
<!-- /Col -->
</div>
</div>
</div>
</div>
<!-- Scripts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.min.js"></script>
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.4/croppie.js"></script> -->
<script src="./node_modules/croppie/croppie.js"></script>
<!-- <script src="./node_modules/html2canvas/dist/html2canvas.min.js"></script> -->
<!-- <script src="./node_modules/canvas2image/canvas2image.js"></script> -->
<script src="./index.js"></script>
<script type="text/javascript">
$uploadCrop = $('#upload-demo').croppie({
enableExif: true,
enableOrientation: true,
viewport: {
width: 300,
height: 300,
type: 'circle'
},
boundary: {
width: 300,
height: 300
}
});
$('#upload').on('change', function () {
var reader = new FileReader();
reader.onload = function (e) {
$uploadCrop.croppie('bind', {
url: e.target.result
}).then(function(){
console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
});
$('.upload-result').on('click', function (ev) {
console.log('Uploading image');
$uploadCrop.croppie('result', {
type: 'canvas',
size: 'viewport',
}).then(function (resp) {
$.ajax({
url: "upload.php",
type: "POST",
data: {"image":resp},
dataType:'JSON',
success: function (data) {
console.log('response ='+data.img);
// html = '<img src="' + resp + '" />';
// $("#upload-demo-i").html(html);
html = '<img width="300px" src="' + data.img + '" /><button style="margin-top:20px; margin-bottom:100px" class="btn btn-danger upload-result">Download Avatar</button> <button style="margin-top:-50px; margin-bottom:100px" class="btn btn-info upload-result">Proceed to Rhapsody Official Website</button>';
$("#upload-demo-i").html(html);
},
error: function (err) {
console.error('Error occured: ', err);
}
});
});
});
// Remove alt attribute from image
window.onload = () => {
document.querySelector('.cr-image').removeAttribute("alt");
document.querySelector('.cr-slider').value="0";
document.querySelector('.cr-slider').focus();
};
</script>
</body>
</html>
after save image file add this lines:
$image_file = fopen($fileName, 'r');
$image_data = fread($image_file, filesize($fileName));
header("Content-type: application/json");
echo json_encode(['img' -> 'data:image/jpeg;base64,' . base64_encode($image_data) );
And if you have problem with merge images look at : Merge two PNG images with PHP GD library
how can i pass multiple $_session to a page with different value
i have a page action.php and index.php, where the index.phpsubmit to action.php and the error message is store in a $_SESSION but i can only pass one of the $_session to the index.php here is my index.php
<?php
session_start();
include_once 'dbconnect.php';
if (isset($_SESSION['userSession'])!="") {
//header("Location: home.php");
}
error_reporting(0);
$Loginmsg = $_SESSION['LoginMsg'];
$_SESSION['LoginMsg'] = "";
extract($_POST);
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Dashboard</title>
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css" rel="stylesheet">
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<!-- Bootstrap 3.3.5 -->
<link rel="stylesheet" href="../bootstrap/css/bootstrap.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="dist/css/AdminLTE.min.css">
<link rel="stylesheet" href="dist/css/skins/_all-skins.min.css">
<!--jquery-->
<script src="plugins/jQuery/jQuery-2.1.4.min.js"></script>
<link rel="stylesheet" href="dist/css/summernote.css">
<script src="dist/js/summernote.js"></script>
</head>
<body class="hold-transition skin-blue sidebar-mini">
<div class="wrapper">
<header class="main-header">
<!-- Logo -->
<a href="#" class="logo">
<!-- mini logo for sidebar mini 50x50 pixels -->
<span class="logo-mini"><b>A</b>LT</span>
<!-- logo for regular state and mobile devices -->
<span class="logo-lg"><b>Administrator</b></span>
</a>
<!-- Header Navbar: style can be found in header.less -->
<nav class="navbar navbar-static-top" role="navigation">
<!-- Sidebar toggle button-->
<a href="#" class="sidebar-toggle" data-toggle="offcanvas" role="button">
<span class="glyphicon glyphicon-menu-hamburger"></span>
</a>
</nav>
</header>
<?php if ($Loginmsg != "") {
echo '<center><div class="alert alert-success" role="alert">' . $Loginmsg . '</div></center>';
} ?>
<!-- Left side column. contains the logo and sidebar -->
<?php include'menu.php'; ?>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<!-- Main content -->
<section class="content">
<?php
if(isset($_GET['page']))
{
switch($_GET['page'])
{
case 'berita': include'form_b.php'; break;
case 'users': include'users.php'; break;
case 'media': include'media.php'; break;
case 'edit': include'edit.php'; break;
case 'slider': include'slider.php'; break;
case 'list_berita': include'list_berita.php';$order=3; break;
}
}
?>
</section>
</div>
<!-- /.content-wrapper -->
<footer class="main-footer">
<div class="pull-right hidden-xs">
<b>Version</b> 2.3.0
</div>
<strong>Copyright © 2015Detailed Technology Center.</strong> All rights reserved.
</footer>
<div class="control-sidebar-bg"></div>
</div>
<!-- ./wrapper -->
<!-- Bootstrap 3.3.5 -->
<script src="../bootstrap/js/bootstrap.min.js"></script>
<script>
$(document).ready(function () {
$('.konten').summernote({
height: 300, // set editor height
minHeight: null, // set minimum height of editor
maxHeight: null, // set maximum height of editor
focus: true, // set focus to editable area after initializing summernote
toolbar: [
['style', ['style']],
['font', ['bold', 'italic', 'underline', 'clear']],
['fontname', ['fontname']],
['color', ['color']],
['para', ['ul', 'ol', 'paragraph']],
['height', ['height']],
['table', ['table']],
['insert', ['link', 'hr']],
['view', ['fullscreen', 'codeview']]
],
onPaste: function (e) {
var bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('Text');
e.preventDefault();
setTimeout(function () {
document.execCommand('insertText', false, bufferText);
}, 10);
}
});
});
</script>
<script src="plugins/datatables/jquery.dataTables.min.js"></script>
<script src="plugins/datatables/dataTables.bootstrap.min.js"></script>
<script>
$(function () {
$("#example1").DataTable({
"order": [[<?php echo $order; ?>, "desc"]]
});
});
</script>
<script>
$.widget.bridge('uibutton', $.ui.button);
</script>
<!-- Sparkline -->
<script src="plugins/sparkline/jquery.sparkline.min.js"></script>
<!-- jvectormap -->
<script src="plugins/jvectormap/jquery-jvectormap-1.2.2.min.js"></script>
<script src="plugins/jvectormap/jquery-jvectormap-world-mill-en.js"></script>
<!-- jQuery Knob Chart -->
<script src="plugins/knob/jquery.knob.js"></script>
<!-- daterangepicker -->
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.2/moment.min.js"></script>-->
<script src="plugins/daterangepicker/daterangepicker.js"></script>
<!-- datepicker -->
<script src="plugins/datepicker/bootstrap-datepicker.js"></script>
<!-- Slimscroll -->
<script src="plugins/slimScroll/jquery.slimscroll.min.js"></script>
<!-- FastClick -->
<script src="plugins/fastclick/fastclick.min.js"></script>
<!-- AdminLTE App -->
<script src="dist/js/app.min.js"></script>
<!-- AdminLTE dashboard demo (This is only for demo purposes) -->
<script src="dist/js/pages/dashboard.js"></script>
<!-- AdminLTE for demo purposes -->
<script src="dist/js/demo.js"></script>
<script>
$('#tgl_agenda').datepicker({
format: 'dd-mm-yyyy'
})
</script>
</body>
</html>
the problem with the above code is that i can only pass one error message via session how can i make it as much as i want with different values
A session can be used just like an array. You don't pass a single variable to a single page. A session makes it possible to save and retrieve data on whatever page you are.
You need to make sure to start your session on top of each page:
session_start();
if you are handling errors you can create a subarray to contain all of them:
$_SESSION['errors'] = array();
// If there's an error
if ($error) {
// Add error to array
$_SESSION['errors'][] = $error;
}
// Check if there are errors
if (is_array($_SESSION['errors']) && count($_SESSION['errors']) != 0) {
foreach ($_SESSION['errors'] as $error) {
echo $error."<br />";
}
}
Good luck!
<?php
session_start();
//Creating session array to store multiple session values
$_SESSION['errors'] = array();
//Value1
$sessionvalue1=$_SESSION['userSession'];
//Value 2
$_SESSION['errors'][$sessionvalue1]="Value 1";
$_SESSION['errors']['error2']="Value 2";
?>
I am trying to use jqmobi with PHP where everything is working but when I try to use PHP session it's not working. First when I use jquery post then it will retrieve data from server but when I reload page then session is destroyed.
I have kept session_start() in every file but still of no use. So if anybody have worked with jqmobi and PHP, share your experience. I am posting my main index.php file:
<?php
session_start();
?>
<!DOCTYPE html>
<!--HTML5 doctype-->
<html>
<head>
<title>UI Starter</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes" />
<META HTTP-EQUIV="Pragma" CONTENT="no-cache" >
<link rel="stylesheet" type="text/css" href="http://cdn.app-framework-software.intel.com/2.0/af.ui.base.css"/>
<link rel="stylesheet" type="text/css" href="http://cdn.app-framework-software.intel.com/2.0/icons.css" />
<link rel="stylesheet" type="text/css" href="http://cdn.app-framework-software.intel.com/2.0/af.ui.css" />
<!-- http://code.jquery.com/jquery-1.10.1.min.js -->
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="./js/lib/jquery.validate.min.js"></script>
<script src="./js/jq.appframework.js"></script>
<script src="http://cdn.app-framework-software.intel.com/2.0/appframework.ui.min.js"> </script>
<script src="./fcharts/FusionCharts/FusionCharts.js"></script>
<!-- include touch on desktop browsers only -->
<script>
// $.ui.showBackButton = false;
if (!((window.DocumentTouch && document instanceof DocumentTouch) || 'ontouchstart' in window)) {
var script = document.createElement("script");
script.src = "plugins/af.desktopBrowsers.js";
var tag = $("head").append(script);
//$.os.android = true; //let's make it run like an android device
//$.os.desktop = true;
}
</script>
</head>
<body>
<div id="afui"> <!-- this is the main container div. This way, you can have only part of your app use UI -->
<!-- this is the header div at the top -->
<div id="header">
<a onclick="$.ui.toggleSideMenu()" id="mainbuon" class="menuButton" style="float:right"></a>
</div>
<div id="content">
<!-- here is where you can add your panels -->
<div title='Management' id="elogin" class="panel" selected="true"
data-load="notloadedPanel" data-unload="notunloadedPanel">
<h2 >login</h2>
<form id="sample" style="position:absolute;width:250px;height:350px; left:50%; top:50%;margin-left:-130px;margin-top:-50px;">
<input type="email" id="email" name="email" value="" placeholder="username"style="text-align:center;" >
<div id="error"></div>
<input type="password" id="password" name="password" value="" placeholder="password" style="text-align:center;" >
<div id="error1"></div>
<a class="button" onclick="validate()" >Login</a>
</form>
<footer>
</footer>
</div>
<div title='List' data-defer="evelist.php" id="elist" class="panel" data-header="testheader"
data-tab="navbar_list" data-load="loadedPanel" data-unload="unloadedPanel">
</div>
<div id="setting" class="panel" title='Management' data-defer="Setting.php" data-load="settingloadedPanel"
data-unload="settingunloadedPanel" data-tab="navbar_list" >
</div>
<div id="missreport" class="panel" data-defer="MissReports.php" title='Management' data-load="reportloadedPanel"
data-unload="reportunloadedPanel" data-tab="navbar_list" >
</div>
<header id="testheader">
<a onclick="$.ui.toggleSideMenu()" id="mainbuon" class="menuButton" style="float:left"></a>
<!-- <a id="backButton" onclick="$.ui.goBack()" class='button'>Go Back</a> -->
<h1>Events List</h1>
</header>
</div> <!-- content ends here #smessage -->
<!-- bottom navbar. Add additional tabs here -->
<div id="navbar">
<div class="horzRule"></div>
<a href="#Dashboard" id='navbar_dash' class='icon home'>Dashboard</a>
<a href="#elist" id='navbar_list' class='icon home'>list</a>
<a href="#aevent" id='navbar_add' class='icon home'>Add ent</a>
<a href="#smessage" id='navbar_sent' class='icon home'>Sent Msg</a>
<a href="#sendmessage" id='navbar_send' class='icon home'>Send Msg</a>
</div>
<!-- this is the default left side nav menu. If you do not want any, do not include these -->
</div>
</body>
<script type="text/javascript">
var webRoot = "./";
$.ui.autoLaunch = false; //By default, it is set to true and you're app will run right away. We set it to false to show a splashscreen
$(document).ready(function(){
//
$.ui.launch();
});
$.ui.backButtonText="Back"
$(document).bind("swipeLeft",function(){
$.ui.toggleSideMenu(false);
});
$(document).bind("swipeRight",function(){
$.ui.toggleSideMenu(true);
});
//$.ui.useAjaxCacheBuster=true;
function logout(){
var rt= "<?php echo session_destroy(); ?>";
$.ui.loadContent("#elogin",false,false,"slide");
} /***login form panel start here****/
function notloadedPanel(){
$.ui.disableSideMenu();
$('#mainbuon').hide();
$.ui.clearHistory();
}
function notunloadedPanel(){
$.ui.enableSideMenu();
$('#mainbuon').show();
}
function validate(){
var validator = $("#sample").validate({
rules: {
email: {
required: true,
}
, password: {
required: true,
}
},
errorPlacement: function(error, element) {
if (element.attr("name") == "email" ) {
// error.insertAfter("#error");
error.appendTo('#error');
} else {
//error.insertAfter(element);
error.appendTo('#error1');
} },submitHandler: function() {
$.post(webRoot + 'parameter.php', {
email:$('#email').val(),password:$('#password').val(),Login:'Login'
}, function (data) {
if($.trim(data)=='success'){
$.ui.loadContent("#elist",false,false,"slide");
}else{
alert("wrong username and password");
}
});
}
});
if(validator.form()){
$('form#sample').submit();
}
}
/***login form panel ends here****/
document.addEventListener("DOMContentLoaded", init, false);
$.ui.ready(function () {
//This function will get executed when $.ui.launch has completed
// $.ui.showBackButton = false;
});
/* This code is used for native apps */
var onDeviceReady = function () {
AppMobi.device.setRotateOrientation("portrait");
AppMobi.device.setAutoRotate(false);
webRoot = AppMobi.webRoot + "/";
//hide splash screen
AppMobi.device.hideSplashScreen();
$.ui.blockPageScroll();
};
document.addEventListener("appMobi.device.ready", onDeviceReady, false);
</script>
The code should be sufficient, however you need to find out if session_destroy or unset($_SESSION) was called else where
<?php
session_start();
$_SESSION['key'] = "value";
?>
I have an update profile page.
It has three forms, it uses a get request to show any one form.
Like update_profile.php?type=profile lets the user edit his profile, update_profile.php?type=settings lets the user edit his account settings.
Type: profile has a file input, I want the users to be able to upload without page refresh.
Now this cant be done using ajax, so I will need a workaround. I've tried the iframe method, xhr2 method and html5 + ajax method which someone posted on stackoverflow.
So if someone would be kind to explain things to me in detailed steps I would appreciate that.
Here is my html:
<script type='text/javascript'>
function nouser() {
$().toastmessage('showToast', {
text : 'The user does not exist',
sticky : true,
position : 'middle-center',
type : 'error',
closeText: '',
close : function () {
console.log("toast is closed ...");
}
});
}
</script>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Update Profile</title>
<link rel="shortcut icon" type="image/png" href="includes/template/images/favicon.png" />
<link rel="stylesheet" type="text/css" href="includes/template/css2/style.css" />
<link rel="stylesheet" type="text/css" href="includes/jquery/toast/resources/css/jquery.toastmessage.css" />
<link rel="stylesheet" type="text/css" href="includes/jquery/notification/css/jquery_notification.css" />
<script type="text/javascript" src="includes/jquery/jquery_v_1.4.js"></script>
<script type="text/javascript" src="includes/jquery/toast/javascript/jquery.toastmessage.js"></script>
<script type="text/javascript" src="includes/jquery/notification/js/jquery_notification_v.1.js"></script>
<script type="text/javascript" src="includes/jquery/auto_resize/resize.js"></script>
<script type="text/javascript" src="includes/jquery/jquery_form.js"></script>
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="css2/ie.css" />
<![endif]-->
</head>
<body>
<div class="topBar" >
<marquee>Welcome to The Marshall Meme. Your IP Adress is 127.0.0.1 You are logged in as marshall</marquee>
</div>
<br />
<div class="logo" >
<img src="includes/template/images/logo.png"/><br/>
</div>
<center>
<div id="wrap">
<br>
<div class="wrapbg">
<span class="corners-top"><span></span></span>
<a class='nav' href='index.php'>Home</a>
<a class='nav' href='whoson.php'>Whos online</a>
<a class='nav' href='logout.php'>Logout</a> <a class='nav' href='forum.php'>Forum</a>
<span class="corners-bottom"><span></span></span>
</div><div class="wrapbg">
<span class="corners-top"><span></span></span>
<div id="content">
Web name
<hr class="hr1" />
<br />
<ul>
<a href='whats_new.php'><button class='action greenbtn'><span class='label'>Whats new?</span></button></a><a href='friend_requests.php'><button class='action redbtn'><span class='label'>Friend requests</span></button></a><a href='update_profile.php?type=profile'><button class='action greenbtn'><span class='label'>Edit profile</span></button></a><a href='update_profile.php?type=settings'><button class='action bluebtn'><span class='label'>Security Settings</span></button></a><a href='update_profile.php?type=changepass'><button class='action greenbtn'><span class='label'>Change password</span></button></a></div>
<span class="corners-bottom"><span></span></span>
</div><div id='emptydiv'> </div>
<div class="wrapbg">
<span class="corners-top"><span></span></span>
<div id="content"><br/>
Update profile
<hr class='hr1'>
<form action='' method="POST" enctype="multipart/form-data">
<table>
Profile picture<br>
<img src="uploads/profile_pics/TIFF_06_liam-neeson_01.jpg"></img>
Thumbnail
<img src="uploads/profile_pics_small/TIFF_06_liam-neeson_01.jpg" ?></img>
<tr><td class="lTxt">Change profile picture:</td> <td><input type="file" name="pic"/></td></tr>
<tr><td class="lTxt">About me:</td> <td><textarea name='about'>Updating my profile :|
fuck yeaaaa</textarea></td></tr>
<tr><td class="lTxt">Interests:</td> <td><textarea name='interests'>I love web development with jquery and php.
Really awesome! yea</textarea></td></tr>
<input type='hidden' name='action' value='profile'/>
<tr><td></td><td><button id="update_profile" name='update' class="action greenbtn"><span class="label">Update profile</span></button></td></tr>
</table>
</form>
</a></div>
<span class="corners-bottom"><span></span></span>
</div> <script type='text/javascript'>
$(function(){
$('form[name=update_stuff]').on("submit", function(e){
e.preventDefault();
$.ajax({
url: 'process.php',
type: 'POST',
data: $(this).serialize(),
success: function(data){
$('#emptydiv').html(data);
}
});
});
});
</script>
</div>
</br>
<div id="footer">
Copyright © 2010-2011, Marshall Meme. All rights reserved.<br>
There are no users online</div>
</div>
</center>
</body>
</html>
Here is the jQuery code I normally use to submit forms:
$(function(){
$('form[name=update_stuff]').on("submit", function(e){
e.preventDefault();
$.ajax({
url: 'process.php',
type: 'POST',
data: $(this).serialize(),
success: function(data){
$('#emptydiv').html(data);
}
});
});
});
I use the $_FILES in php to get the file name and verify its extension and size server side, so i need the information in that. How can this be done?
Also would i need to change the form name for updating profile and write a different code for it than the other forms in the same page?
You must have to use any server script to upload file so you have to Ajax method, j query with Ajax, you can try also uplaodify
http://www.uploadify.com/