I want to create two reports and submit the report data to database by using two functions within a class: Here I have two submit buttons: "Create ES Report" and "Create RP Report".
(1) When I click on "Create ES Report", create_es_report form should display and be able to fill the data and submit successfully to database and if errors it should display the errors on the same div.
(2) When I click on "Create RP Report", create_rp_report form should display and be able to fill the data and submit successfully to dataabase and if errors it should display the errors on the same div.
Rightnow, When I click on any of the submit buttons, nothing was displaying
index.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#es').click(function ()
{
create();
});
});
function create(){
$.ajax({
url: "check.php?proc=create",
type: "POST",
dataType:'json',
success: function(data)
{
$('#returnMessage').show();
$('#returnMessage').html(data.mes);
}
});
return false;
}
</script>
</head>
<body>
<div class="container2">
<div style="float:left;margin:0px 0px;padding:7px;"><input type="submit" value="Create ES Report" id="es"></div>
<div id="returnMessage" style="display:none;"></div>
</div>
</body>
</html>
check.php
<?php
require 'includes/config.inc.php';
require 'classes/class.report.php';
$report = new Report($db);
if(isset($_GET['proc']) && !empty($_GET['proc']))
{
$proc = $_GET['proc'];
if($proc == 'create')
{
$report->create_es_report();
$return = array('mes' => 'Created' );
header('content-type: application/json; charset=utf-8');
echo json_encode($return);
}
}
else
{
$return = array('mes' => 'The $_GET is empty , check if all parms and ajax function passing to the true file, good luck :).' );
header('content-type: application/json; charset=utf-8');
echo json_encode($return);
}
?>
class.report.php
<?php
class Report
{
private $db;
public function __construct($database){
$this->db = $database;
}
//CREATE DATASOURCE REPORT
public function create_es_report()
{
if (isset($_POST['create_es_report']))
{
$report_name = htmlentities($_POST['report_name']);
$from_address = htmlentities($_POST['from_address']);
$subject = htmlentities($_POST['subject']);
$reply_to = htmlentities($_POST['reply_to']);
if (empty($_POST['report_name']) || empty($_POST['from_address']) || empty($_POST['subject']) || empty($_POST['reply_to']))
{
$errors[] = '<span class="error">All fields are required.</span>';
}
else
{
if (isset($_POST['report_name']) && empty($_POST['report_name'])) { $errors[] = '<span class="error">Report Name is required</span>'; }
else if (!ctype_alnum($_POST['report_name']))
{ $errors[] = '<span class="error">Report Name: Whitespace is not allowed, only alphabets and numbers are required</span>'; }
if (isset($_POST['from_address']) && empty($_POST['from_address']))
{ $errors[] = '<span class="error">From address is required</span>'; }
else if (filter_var($_POST['from_address'], FILTER_VALIDATE_EMAIL) === false)
{ $errors[] = '<span class="error">Please enter a valid From address</span>'; }
if (isset($_POST['subject']) && empty($_POST['subject'])) { $errors[] = '<span class="error">Subject is required</span>'; }
else if (!ctype_alnum($_POST['subject']))
{ $errors[] = '<span class="error">Subject: Whitespace is not allowed, only alphabets and numbers are required</span>'; }
if (isset($_POST['reply_to']) && empty($_POST['reply_to'])) { $errors[] = '<span class="error">Reply To is required</span>'; }
else if (filter_var($_POST['reply_to'], FILTER_VALIDATE_EMAIL) === false)
{ $errors[] = '<span class="error">Please enter a valid Reply-To address</span>'; }
}
if (empty($errors) === true)
{
$query = $this->db->prepare("INSERT INTO report(report_name, from_address, subject, reply_to) VALUES (?, ?, ?, ?) ");
$query->bindValue(1, $report_name);
$query->bindValue(2, $from_address);
$query->bindValue(3, $subject);
$query->bindValue(4, $reply_to);
try {
$query->execute();
}
catch(PDOException $e) {
die($e->getMessage());
}
header('Location:home.php?success');
exit();
}
}
if (isset($_GET['success']) && empty($_GET['success']))
{
header('Location:home.php');
echo '<span class="error">Report is succesfully created</span>';
}
?>
<form action="" method="POST" accept-charset="UTF-8">
<div style="font-weight:bold;padding:17px 80px;text-decoration:underline;">Section A</div>
<table class="create_report">
<tr><td><label>Report Name</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="report_name" required placeholder="Name of the report" value="<?php if(isset($_POST["report_name"])) echo $report_name; ?>" size="30" maxlength="30">
</td></tr>
<tr><td><label>From</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="from_address" required placeholder="From address" value="<?php if(isset($_POST["from_address"])) echo $from_address; ?>" size="30">
</td></tr>
<tr><td><label>Subject</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="subject" required placeholder="Subject" value="<?php if(isset($_POST["subject"])) echo $subject; ?>" size="30">
</td></tr>
<tr><td><label>Reply To</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="reply_to" required placeholder="Reply address" value="<?php if(isset($_POST["reply_to"])) echo $reply_to; ?>" size="30">
</td></tr>
<tr><td><input type="submit" value="create report" style="background:#8AC007;color:#080808;padding:6px;" name="create_es_report"></td></tr>
</table>
</form>
<?php
//IF THERE ARE ERRORS, THEY WOULD BE DISPLAY HERE
if (empty($errors) === false) {
echo '<div>' . implode('</p><p>', $errors) . '</div>';
}
}
}//Report CLASS ENDS
My guess is that your PHP is failing and the success option is not triggering.
I would suggest adding a console write of data.res in your success option and also add an error option and add a complete option that will write something different to console so you can determine if jquery is failing or if php is failing.
As a side note, I would combine your create_es and create_rp function to 1 since they are identical except for the query string value being passed in ajax. You would then call create_report("es") and create_report("rp") in your click events and your ajax url would be "check.php?proc=" + report, where report is your function param.
You seems don't know how to handle PHP and AJAX as well.
First change the urls E.G:
url: "check.php?proc=create_es",
to
url: "check.php?proc=create",
Look how at check.php the GET works.
And change type: "POST", to type: "GET",
Now to return the error's it's more complicated from just call a php function.
To return the error's you return from the create_es_report error's to the check.php file and return json format to you'r html page, this why i said LEARN ajax first.
Also don't use htmlentities i suggest you to use HTMLPURIFER to santize inputs from malicious inputs.
Related
I have a login popup Modal. and i am logging through ajax
Modal
<div class="modal-body">
<form action="<?php echo base_url('Login');?>" method="POST">
<div class="form-group">
<input type="text" placeholder="Email or Mobile*" value="" id="loginEmail" name="email" class="form-control input-feild">
</div>
<div class="form-group">
<input type="password" placeholder="Password*" value="" id="loginPassword" name="password" class="form-control input-feild">
</div>
<div class="form-group">
<input type="button" id="l_submit" name="l_submit" value="Login" class="btn btn-primary input-feild">
</div>
</form>
<p id="error-msg"></p>
</div>
I am trying to redirect after successful login using ajax. If email and password is correct then redirect to any page. If not then it will show the Error.
Controller
function index() {
$this->form_validation->set_rules('email', 'Email', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run() == false) {
echo validation_errors();
}else {
$email = $this->input->post("email");
$password = $this->input->post("password");
$user = $this->Perfect_mdl->check_user($email, $password);
if ($user) {
$logged_in_data = array();
foreach ($user as $logged_in_data) {
$logged_in_data = array(
'id' => $user[0]->id,
'email' => $user[0]->email
);
}
$this->session->set_userdata($logged_in_data);
$id = $this->session->userdata('email');
$data['details'] = $this->Perfect_mdl->get_login_user_detail($id);
echo "Yes";
}else {
echo "No";
}
}
}
This is my controller in which i am checking login user email and password correct/incorrect.
This is my script
<script type="text/javascript">
$("#l_submit").click(function(){
var email = $("#loginEmail").val();
var password = $("#loginPassword").val();
$.ajax({
url : "<?php echo base_url('Login');?>",
type: 'POST',
data : {'email':email,'password':password},
success: function(msg) {
if (msg == "Yes")
window.location.href = "<?php echo current_url(); ?>";
else if (msg == "No")
$('#error-msg').html('<div class="alert alert-danger text-center">Incorrect Email & Password. Please try again ...</div>');
else
$('#error-msg').html('<div class="alert alert-danger">' + msg + '</div>');
}
});
return false;
});
</script>
As you can see in the success part, when i entered the correct email/password. It is showing Yes. But i want to redirect another page, Why this is showing YES on correct email/password.and On incorrect email/password This is showing NO.
Where i am Doing Wrong???
You need to change few lines of codes in jQuery and Controller function. Here I am attaching updated version of your code. Please refer below:
View (Bootstrap Modal)
<div class="modal-body">
<form action="<?php echo base_url('Login');?>" method="POST">
<div class="form-group">
<input type="text" placeholder="Email or Mobile*" value="" id="loginEmail" name="email" class="form-control input-feild">
</div>
<div class="form-group">
<input type="password" placeholder="Password*" value="" id="loginPassword" name="password" class="form-control input-feild">
</div>
<div class="form-group">
<input type="button" id="l_submit" name="l_submit" value="Login" class="btn btn-primary input-feild">
</div>
</form>
<p id="error-msg"></p>
</div>
This is your view file. It will remain same. On clicking on button you have written a script which need to be modified. Will attact after attaching controller's function:
Controller
function index() {
if (!$this->input->is_ajax_request()) {
echo 'No direct script is allowed';
die;
}
$this->form_validation->set_rules('email', 'Email', 'trim|required');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run() == false) {
$result['status'] = 'error';
$result['message'] = validation_errors();
}else {
$email = $this->input->post("email");
$password = $this->input->post("password");
$user = $this->Perfect_mdl->check_user($email, $password);
if ($user) {
$logged_in_data = array();
foreach ($user as $logged_in_data) {
$logged_in_data = array(
'id' => $user[0]->id,
'email' => $user[0]->email
);
}
$this->session->set_userdata($logged_in_data);
$id = $this->session->userdata('email');
$data['details'] = $this->Perfect_mdl->get_login_user_detail($id);
$result['status'] = 'success';
$result['message'] = 'Yeah! You have successfully logged in.';
$result['redirect_url'] = base_url();
}else {
$result['status'] = 'error';
$result['message'] = 'Whoops! Incorrect Email & Password. Please try again';
}
}
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($result));
$string = $this->output->get_output();
echo $string;
exit();
}
Script
<script type="text/javascript">
$("#l_submit").click(function(){
var email = $("#loginEmail").val();
var password = $("#loginPassword").val();
$.ajax({
url : "<?php echo base_url('Login');?>",
type: 'POST',
data : {'email':email,'password':password},
success: function(resp) {
if (resp.status == "success")
window.location.href = resp.redirect_url;
else
$('#error-msg').html('<div class="alert alert-danger">' + resp.message + '</div>');
}
});
return false;
});
This is the correct answer. Let me know if you face any issue.
You can use a simple redirect() (comes in the url helper) in your code if you want to jump to another controller/method from the script. However, this will not alert the user that the login was successful: it's just a plain redirect.
The proper way to do it would be returning a json file, so instead of echoing a yes or no, use this:
$response['type'] = 'error';
$response['msg'] = 'Login Succesful';
$response['redirect'] = 'http://your-url.com/controller/method';
echo json_encode($response);
die;
Then, you handle the answer in your ajax call, and some good alerting (in my case, Sweet Alert) kinda like this:
success: function(data) {
if (data.redirect) {
swal({
title: '¡Success!',
text: data.msg,
timer: 2000,
type: data.type,
showConfirmButton: false
}, function() {
window.location.href = data.redirect;
});
} else {
swal('¡Error!', data.msg, data.type);
}
}
So what this code does is that if your json response has a redirect field, will trigger the redirection after a while. But if your json response does not have the field redirect, will just show an alert.
Check your return data type. May be you can use in datatype in Ajax code. Return data can't read if condition. I am facing same problem or use this
if($.trim(msg) == 'Yes') {
Change echo "Yes"; to die("Yes");. This will make sure nothing will be sent after "Yes" or "No" and then the JS code will work as expected.
Their is also a way to redirect from your controller after success.
In this case you just need to follow these two steps to redirect
This line in your controller where you get true condition and want to redirect
if($result){
echo base_url()."welcome/";
}
else{
echo 0;
}
on your html page where you applied your ajax, on true condition you try this to redirect page
success: function(result){
if(result!=0){
// On success redirect.
window.location.replace(result);
}
else
alert('wrong');
}
I will be on the point. But anyways, THANKS IN ADVACE.
So basically When I submit the form I made, it submits and stuff, but it redirects the page to the PHP file, and shows this on the browser (not as an alert) :
{"status":"success","message":"Yer message was sent."}
when the data is successfully validated, and shows this
{"status":"fail","message":"Invalid name provided."}
when the form doesn't validate. What I want, is that when the form submits, it stays on the same page and if status is true or false, it should alert the message in the array.
I'll write down the scripts and the file names are: index.html, script.js and post.php
INDEX.HTML
<form action='post.php' id='post_message' name='post_message' method="post">
<p>
<input id='email' type="email" class='post' placeholder="Email goes in here.(Required) " class="width" name="email">
<br>
<input id='fname' type="text" class='post' placeholder="First Name (Required) " name="FirstName"><br>
<input id='lname' type="text" class='post' placeholder="Last Name (Required) " name="LastName"><br>
<input id='website' type="url" class='post' placeholder="Website? (Optional!)" class="width" name="website"><br>
<textarea id='message_text' placeholder="Your Message goes here. (Required, DUH!) " name='message'></textarea>
</p>
<button type="submit" class="submit" id='btnPost'></button>
<input type="hidden" name="action" value="post_message" id="action">
</form>
SCRIPT.JS
function clearInputs(){
$("#fname").val('');
$("#lname").val('');
$("#email").val('');
$("#website").val('');
$("#message_text").val('');
}
$('#btnPost').click(function() {
var data = $("#post_message").children().serializeArray();
$.post($("#post_message").attr('action'), data, function(json){
if (json.status == "fail") {
alert(json.message);
}
if (json.status == "success") {
alert(json.message);
clearInputs();
}
}, "json");
});
POST.PHP
<?php
if($_POST){
if ($_POST['action'] == 'post_message') {
$fname = htmlspecialchars($_POST['FirstName']);
$lname = htmlspecialchars($_POST['LastName']);
$email = htmlspecialchars($_POST['email']);
$website = htmlspecialchars($_POST['website']);
$message = htmlspecialchars($_POST['message']);
$date = date('F j, Y, g:i a');
if(preg_match('/[^\w\s]/i', $fname) || preg_match('/[^\w\s]/i', $lname)) {
fail('Invalid name provided.');
}
if( empty($fname) || empty($lname) ) {
fail('Please enter a first and last name.');
}
if( empty($message) ) {
fail('Please select a message.');
}
if( empty($email)) {
fail('Please enter an email');
}
$query = "INSERT INTO portmessage SET first_name='$fname', last_name='$lname', email = '$email', website = '$website', message = '$message', date = '$date'";
$result = db_connection($query);
if ($result) {
$msg = "Yer message was sent.";
success($msg);
} else {
fail('Message failed, Please try again.');
}
exit;
}
}
function db_connection($query) {
mysql_connect('127.0.0.1', '######', '####')
OR die(fail('Could not connect to database.'));
mysql_select_db('####');
return mysql_query($query);
}
function fail($message) {
die(json_encode(array('status' => 'fail', 'message' => $message)));
}
function success($message) {
die(json_encode(array('status' => 'success', 'message' => $message)));
}
?>
And yes, it DOES submit the form to the database, but I can't overcome the alert and redirecting problem.
Thanks, again!
You can validate your form client side(using javascript)
HTML
<form action='post.php' id='post_message' name='post_message' method="post" onsubmit="return validate_form();">
Javascript
function validate_form()
{
var success = true;
if($("[name=FirstName]").val() == "")
{
success = false;
}
// your test case goes here
// you can alert here if you find any error
return success;
}
I have three buttons (create,edit,delete) with three separate functions defined in a class.
When I click on create, create function should be called and likewise for edit and delete.
Everything was working fine up-to here, but when I click on submit in anyone of the options(create/edit/delete), the page is redirecting by displaying the first div "cs_content" all the time.
My Requirement is : Until the data is stored to database successfully by submitting, then only the page should redirect to "cs_content" else in case any errors, the page should be
on the selected div.
$ (document).ready(function ()
{
//$("#cs_content").show();
$('#cs').click(function ()
{
$('#cs_content').fadeIn('slow');
$('#rp_content').hide();
});
$('#ed').click(function ()
{
$('#ed_content').fadeIn('slow');
$('#cs_content').hide();
});
$('#del').click(function ()
{
$('#del_content').fadeIn('slow');
$('#ed_content').hide();
});
});
<div class="container2">
<div id="cs" style="float:left;margin:0px 0px;padding:7px;"><input type="button" value="Create"></div>
<div id="ed" style="float:left;margin:0px 0px;padding:7px;"><input type="button" value="Edit"></div>
<div id="del" style="float:left;margin:0px 0px;padding:7px;"><input type="button" value="Delete"></div>
<div id="cs_content"><?php $ds->create_ds($db_host,$db_username,$db_password); ?> </div>
<div id="ed_content" style="display:none;"> <?php $ds->update_ds($db_host,$db_username,$db_password); ?> </div>
<div id="del_content" style="display:none;"> <?php $ds->delete_ds($db_host,$db_username,$db_password); ?> </div>
</div>
Updated code:
class Datasource
{
private $db;
public function __construct($database){
$this->db = $database;
}
//CREATE DATASOURCE
public function create_ds($db_host,$db_username,$db_password)
{
if (isset($_POST['create_dsource']))
{
$dsource_host = htmlentities($_POST['dsource_host']);
$dsource_username = htmlentities($_POST['dsource_username']);
$dsource_password = $_POST['dsource_password'];
$dsource_name = htmlentities($_POST['dsource_name']);
if (empty($_POST['dsource_host']) || empty($_POST['dsource_username']) || empty($_POST['dsource_name']))
{
$errors[] = '<span class="error">All fields are required.</span>';
}
else
{
if (isset($_POST['dsource_host']) && empty($_POST['dsource_host'])) { $errors[] = '<span class="error">Datasource Host is required</span>'; }
else if ($_POST['dsource_host'] !== $db_host)
{ $errors[] = '<span class="error">dsource Host is not matching with the application data source host </span>'; }
if(isset($_POST['dsource_username']) && empty($_POST['dsource_username'])) { $errors[] = '<span class="error">Datasource username is required</span>'; }
else if ($_POST['dsource_username'] !== $db_username)
{ $errors[] = '<span class="error">Datasource Username is not matching with the application datasource username </span>'; }
if ($_POST['dsource_password'] !== $db_password)
{ $errors[] = '<span class="error">Datasource Password is not matching with the application datasource password </span>'; }
if (isset($_POST['dsource_name']) && empty($_POST['dsource_name'])) { $errors[] = '<span class="error">Datasource name is required</span>'; }
else if (!ctype_alnum($_POST['dsource_name']))
{ $errors[] = '<span class="error">Please enter a datasource name with only alphabets and numbers</span>'; }
}
if (empty($errors) === true)
{
try
{
$this->db->exec("CREATE DATABASE IF NOT EXISTS ".$dsource_name."");
$this->db->query("USE ".$dsource_name."");
$sql_filename = "includes/datasource.sql";
$sql_contents = file_get_contents($sql_filename);
$sql_contents = explode("##", $sql_contents);
foreach($sql_contents as $query)
{
$result = $this->db->prepare($query);
$result->execute();
}
}
catch (PDOException $e) {
die("DB ERROR: ". $e->getMessage());
}
header('Location:home.php?success');
exit();
}
}
if (isset($_GET['success']) && empty($_GET['success']))
{
header('Refresh:0; url=home.php');
echo '<span class="error">Datasource is succesfully created</span>';
}
?>
<form action="" method="POST" accept-charset="UTF-8" id="create_ds" name="create_ds">
<table class="create_dsource">
<tr><td><label>Datasource Host</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="dsource_host" required placeholder="localhost/server" value="<?php if(isset($_POST["dsource_host"])) echo $dsource_host; ?>" size="30">
</td></tr>
<tr><td><label>Datasource Username</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="dsource_username" required placeholder="Datasource username" size="30" value="<?php if(isset($_POST["dsource_username"])) echo $dsource_username; ?>">
</td></tr>
<tr><td><label>Datasource Password</label></td>
<td><input type="password" name="dsource_password" placeholder="Datasource password" size="30" value="<?php if(isset($_POST["dsource_password"])) echo $dsource_password; ?>" autocomplete="off">
</td></tr>
<tr><td><label>Datasource Name</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="dsource_name" size="30" required placeholder="Datasource name" value="<?php if(isset($_POST["dsource_name"])) echo $dsource_name; ?>">
</td></tr>
<tr><td><input type="submit" value="create datasource" style="background:#8AC007;color:#080808;padding:6px;" name="create_dsource"></td></tr>
</table>
</form>
<?php
//IF THERE ARE ERRORS, THEY WOULD BE DISPLAY HERE
if (empty($errors) === false)
echo '<div>' . implode('</p><p>', $errors) . '</div>';
}
} //class closes here
$ds = new Datasource($db);
UPDATED WITH EXAMPLE.
You doing bad mistake it's not the right way to do what you want.
You should use ajax.
Read here jQuery.AJAX guide .
I made you example how to do it VERY BASIC but will do the job:
HTML PAGE :
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$ (document).ready(function ()
{
//$("#cs_content").show();
$('#cs').click(function ()
{
createDs();
});
$('#ed').click(function ()
{
updateDs();
});
$('#del').click(function ()
{
deleteDs();
});
});
function createDs(){
$.ajax({
url: "check.php?proc=create",
type: "POST",
dataType:'json',
success: function(data)
{
$('#returnMessage').show();
$('#returnMessage').html(data.mes);
}
});
return false;
}
function updateDs(){
$.ajax({
url: "check.php?proc=update",
type: "POST",
dataType:'json',
success: function(data)
{
$('#returnMessage').show();
$('#returnMessage').html(data.mes);
}
});
return false;
}
function deleteDs(){
$.ajax({
url: "check.php?proc=delete",
type: "POST",
dataType:'json',
success: function(data)
{
$('#returnMessage').show();
$('#returnMessage').html(data.mes);
}
});
return false;
}
</script>
<div class="container2">
<div style="float:left;margin:0px 0px;padding:7px;"><input type="submit" value="Create" id="cs"></div>
<div style="float:left;margin:0px 0px;padding:7px;"><input type="submit" value="Edit" id="ed"></div>
<div style="float:left;margin:0px 0px;padding:7px;"><input type="submit" value="Delete" id="del"></div>
<div style="float:left;margin:0px 0px;padding:7px;"><input type="submit" value="Clear DIV" id="clear"></div>
<div id="returnMessage" style="display:none;"></div>
<div id="returnMessage" style="display:none;"></div>
</div>
check.php: (don't forget include here $ds-)
<?php
//include here $ds- so it could work and won't give you a error.
if(isset($_GET['proc']) && !empty($_GET['proc'])){
$proc = $_GET['proc'];
if($proc == 'create'){
$ds->create_ds($db_host,$db_username,$db_password);
$return = array('mes' => 'Created' );
header('content-type: application/json; charset=utf-8');
echo json_encode($return);
}elseif($proc == 'update'){
$ds->update_ds($db_host,$db_username,$db_password);
$return = array('mes' => 'Updated' );
header('content-type: application/json; charset=utf-8');
echo json_encode($return);
}elseif($proc == 'delete'){
$ds->delete_ds($db_host,$db_username,$db_password);
$return = array('mes' => 'Deleted' );
header('content-type: application/json; charset=utf-8');
echo json_encode($return);
}
}else{
$return = array('mes' => 'The $_GET is empty , check if all parms and ajax function passing to the true file, good luck :).' );
header('content-type: application/json; charset=utf-8');
echo json_encode($return);
}
?>
You muse include files to check.php either to use $ds- , its must basic and you should take a look how ajax works.
EDIT:
Here working example :
Click on me to go to demo , Here you can download the example:Click on me to download the example
Working perfect,don't forget uncomment // from the check.php so it will do you'r stuff that you needed.
If you still can't make it work (even when you have WORKING DEMO) , go learn php and Javascript , this all i can help you.
Also research google about firebug , this will help you see error's from ajax/post request, and will help you either in anyway.
You need ajax to dynamically run some php code when binding to events such as click. Try read on .ajax()
PHP code is executed before your DOM is created. So your jquery is not running the function again it is just showing the content that is already sent by your php functions. You need Ajax to run your php function and display data sent back by it.
I want to create two reports and submit the report data to database by using two functions defined in a class: Here I have two buttons: "Create ES" and "Create RP".
Rightnow, my forms are working fine, I can insert data successfully, but the problem was when I click on submit after filling the form data, the content is hiding and displays the fist div content "cs_content" and again I need to onclick to submit again.
Could anyone give a solution for this.
Requirement :
When I click on "Create CS", I should be able to fill the form and submit data successfully with a message within "cs_content" and any form input errors, the errors should display within "cs_content".
When I click on "Create RP", I should be able to fill the form and submit data successfully with a message within "rp_content" and any form input errors, the errors should display within "rp_content".
home.php
<?php
require 'classes/class.report.php';
$report = new Report($db);
?>
<html>
<head>
<script src="js/jqueryv1.10.2.js"></script>
<script>
$ (document).ready(function ()
{
//$("#cs_content").show();
$('#cs').click(function ()
{
$('#cs_content').fadeIn('slow');
$('#rp_content').hide();
});
$('#rp').click(function ()
{
$('#rp_content').fadeIn('slow');
$('#cs_content').hide();
});
});
</script>
</head>
<body>
<div class="container2">
<div style="margin:0px 0px;padding:3px 217px;overflow:hidden;">
<div id="cs" style="float:left;margin:0px 0px;padding:7px;"><input type="button" value="CREATE CS"></div>
<div id="rp" style="float:left;margin:0px 0px;padding:7px;"><input type="button" value="CREATE RP"></div><br>
</div>
<div id="cs_content"> <?php $report->create_cs_report(); ?> </div>
<div id="rp_content" style="display:none;"> <?php $report->create_rp_report(); ?> </div>
</div>
</body>
</html>
class.report.php
<?php
class Report
{
private $db;
public function __construct($database){
$this->db = $database;
}
public function create_cs_report()
{
if (isset($_POST['create_es_report']))
{
$report_name = htmlentities($_POST['report_name']);
$from_address = htmlentities($_POST['from_address']);
$subject = htmlentities($_POST['subject']);
$reply_to = htmlentities($_POST['reply_to']);
if (empty($_POST['report_name']) || empty($_POST['from_address']) || empty($_POST['subject']) || empty($_POST['reply_to']))
{
$errors[] = '<span class="error">All fields are required.</span>';
}
else
{
if (isset($_POST['report_name']) && empty($_POST['report_name'])) { $errors[] = '<span class="error">Report Name is required</span>'; }
else if (!ctype_alnum($_POST['report_name']))
{ $errors[] = '<span class="error">Report Name: Whitespace is not allowed, only alphabets and numbers are required</span>'; }
if (isset($_POST['from_address']) && empty($_POST['from_address']))
{ $errors[] = '<span class="error">From address is required</span>'; }
else if (filter_var($_POST['from_address'], FILTER_VALIDATE_EMAIL) === false)
{ $errors[] = '<span class="error">Please enter a valid From address</span>'; }
if (isset($_POST['subject']) && empty($_POST['subject'])) { $errors[] = '<span class="error">Subject is required</span>'; }
else if (!ctype_alnum($_POST['subject']))
{ $errors[] = '<span class="error">Subject: Whitespace is not allowed, only alphabets and numbers are required</span>'; }
if (isset($_POST['reply_to']) && empty($_POST['reply_to'])) { $errors[] = '<span class="error">Reply To is required</span>'; }
else if (filter_var($_POST['reply_to'], FILTER_VALIDATE_EMAIL) === false)
{ $errors[] = '<span class="error">Please enter a valid Reply-To address</span>'; }
}
if (empty($errors) === true)
{
$query = $this->db->prepare("INSERT INTO report(report_name, from_address, subject, reply_to) VALUES (?, ?, ?, ?) ");
$query->bindValue(1, $report_name);
$query->bindValue(2, $from_address);
$query->bindValue(3, $subject);
$query->bindValue(4, $reply_to);
try {
$query->execute();
}
catch(PDOException $e) {
die($e->getMessage());
}
header('Location:home.php?success');
exit();
}
}
if (isset($_GET['success']) && empty($_GET['success']))
{
header('Location:home.php');
echo '<span class="error">Report is succesfully created</span>';
}
?>
<form action="" method="POST" accept-charset="UTF-8">
<div style="font-weight:bold;padding:17px 80px;text-decoration:underline;">Section A</div>
<table class="create_report">
<tr><td><label>Report Name</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="report_name" required placeholder="Name of the report" value="<?php if(isset($_POST["report_name"])) echo $report_name; ?>" size="30" maxlength="30">
</td></tr>
<tr><td><label>From</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="from_address" required placeholder="From address" value="<?php if(isset($_POST["from_address"])) echo $from_address; ?>" size="30">
</td></tr>
<tr><td><label>Subject</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="subject" required placeholder="Subject" value="<?php if(isset($_POST["subject"])) echo $subject; ?>" size="30">
</td></tr>
<tr><td><label>Reply To</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="reply_to" required placeholder="Reply address" value="<?php if(isset($_POST["reply_to"])) echo $reply_to; ?>" size="30">
</td></tr>
<tr><td><input type="submit" value="create report" style="background:#8AC007;color:#080808;padding:6px;" name="create_es_report"></td></tr>
</table>
</form>
<?php
//IF THERE ARE ERRORS, THEY WOULD BE DISPLAY HERE
if (empty($errors) === false) {
echo '<div>' . implode('</p><p>', $errors) . '</div>';
}
}
public function create_rp_report()
{
if (isset($_POST['create_rp_report']))
{
$report_name = htmlentities($_POST['report_name']);
$to_address = htmlentities($_POST['to_address']);
$subject = htmlentities($_POST['subject']);
$reply_to = htmlentities($_POST['reply_to']);
if (empty($_POST['report_name']) || empty($_POST['to_address']) || empty($_POST['subject']) || empty($_POST['reply_to']))
{
$errors[] = '<span class="error">All fields are required.</span>';
}
else
{
if (isset($_POST['report_name']) && empty($_POST['report_name'])) { $errors[] = '<span class="error">Report Name is required</span>'; }
else if (!ctype_alnum($_POST['report_name']))
{ $errors[] = '<span class="error">Report Name: Whitespace is not allowed, only alphabets and numbers are required</span>'; }
if (isset($_POST['to_address']) && empty($_POST['to_address']))
{ $errors[] = '<span class="error">to address is required</span>'; }
else if (filter_var($_POST['to_address'], FILTER_VALIDATE_EMAIL) === false)
{ $errors[] = '<span class="error">Please enter a valid to address</span>'; }
if (isset($_POST['subject']) && empty($_POST['subject'])) { $errors[] = '<span class="error">Subject is required</span>'; }
else if (!ctype_alnum($_POST['subject']))
{ $errors[] = '<span class="error">Subject: Whitespace is not allowed, only alphabets and numbers are required</span>'; }
if (isset($_POST['reply_to']) && empty($_POST['reply_to'])) { $errors[] = '<span class="error">Reply To is required</span>'; }
else if (filter_var($_POST['reply_to'], FILTER_VALIDATE_EMAIL) === false)
{ $errors[] = '<span class="error">Please enter a valid Reply-To address</span>'; }
}
if (empty($errors) === true)
{
$query = $this->db->prepare("INSERT INTO report(report_name, to_address, subject, reply_to) VALUES (?, ?, ?, ?) ");
$query->bindValue(1, $report_name);
$query->bindValue(2, $to_address);
$query->bindValue(3, $subject);
$query->bindValue(4, $reply_to);
try {
$query->execute();
}
catch(PDOException $e) {
die($e->getMessage());
}
header('Location:home.php?success');
exit();
}
}
if (isset($_GET['success']) && empty($_GET['success']))
{
header('Location:home.php');
echo '<span class="error">Report is succesfully created</span>';
}
?>
<form action="" method="POST" accept-charset="UTF-8">
<div style="font-weight:bold;padding:17px 80px;text-decoration:underline;">Section A</div>
<table class="create_report">
<tr><td><label>Report Name</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="report_name" required placeholder="Name of the report" value="<?php if(isset($_POST["report_name"])) echo $report_name; ?>" size="30" maxlength="30">
</td></tr>
<tr><td><label>to</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="to_address" required placeholder="to address" value="<?php if(isset($_POST["to_address"])) echo $to_address; ?>" size="30">
</td></tr>
<tr><td><label>Subject</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="subject" required placeholder="Subject" value="<?php if(isset($_POST["subject"])) echo $subject; ?>" size="30">
</td></tr>
<tr><td><label>Reply To</label><span style="color:#A60000">*</span></td>
<td><input type="text" name="reply_to" required placeholder="Reply address" value="<?php if(isset($_POST["reply_to"])) echo $reply_to; ?>" size="30">
</td></tr>
<tr><td><input type="submit" value="create report" style="background:#8AC007;color:#080808;padding:6px;" name="create_rp_report"></td></tr>
</table>
</form>
<?php
//IF THERE ARE ERRORS, THEY WOULD BE DISPLAY HERE
if (empty($errors) === false) {
echo '<div>' . implode('</p><p>', $errors) . '</div>';
}
}
}//Report CLASS ENDS
First of all
1)
You need javascript code to handle this form validation like:
$("form").submit(function(){
// Your validation code
if(validation not satisfied){
return false;
}
});
2) Check the form wich for is active and make that form active after submit. And your HTML should like this
<body>
<div class="container2">
<div style="margin:0px 0px;padding:3px 217px;overflow:hidden;">
<div id="cs" style="float:left;margin:0px 0px;padding:7px;"><input type="button" value="CREATE CS"></div>
<div id="rp" style="float:left;margin:0px 0px;padding:7px;"><input type="button" value="CREATE RP"></div><br>
</div>
<?php $active_form = (is_first_form_checked)?'first_form':'second_form'; ?>
<div id="cs_content" style="<?php echo ($active_form == 'first_form')?'display:none;':''; ?>"> <?php $report->create_cs_report(); ?> </div>
<div id="rp_content" style="<?php echo ($active_form == 'second_form')?'display:none;':''; ?>"> <?php $report->create_rp_report(); ?> </div>
</div>
this is my first post and i'm rather new to php + ajax.
I have most of my coding set up only problem now is that when i press the submit button an notification shows up that only should show up when the text fields aren't empty.
This is my code:
<head><script>
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#ContactForm').ajaxForm(function() {
alert("Thank you for subscribing to SHCA");
document.forms["ContactForm"].reset();
});
});
</script> </head>
followed by some php coding:
<?php
if(strlen($_POST['name']) > 0 AND strlen($_POST['email']) > 0)
{
if(isset($_POST['submit']))
{
$hostdb = '';
$namedb = '';
$userdb = '';
$passdb = '';
$conn = mysqli_connect($hostdb , $userdb, $passdb ,$namedb);
$sql = "INSERT INTO subscribers (name, email) VALUES('$_POST[name]', '$_POST[email]')";
if (!mysqli_query($conn, $sql))
{
die('Error: ' .mysql_error($conn));
}
if (!mysqli_ping($conn)) {
echo 'Lost connection, exiting after query #1';
exit;
}
mysqli_close($conn);
}}
else
{
?>
<form id="ContactForm" action="" method="post">
<label for="author">Name:</label> <input type="text" id="name" name="name" class="required input_field float_r" />
</br>
</br>
<label for="email">Email:</label> <input type="text" id="email" name="email" class="validate-email required input_field float_r" />
<div class="cleaner h10"></div>
<input type="submit" value="Subscribe" id="submit" name="submit" class="submit_btn float_l" />
</form>
<?php } ?>
hope anyone here is able to tell me what i should do to only show the "Thank you for subscribing to SHCA" message when the textfields aren't empty
final anwser Dereck forgot the '' in the objects so shout out to dereck for helping me!
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#ContactForm').ajaxForm(function() {
if( !$('#name').val()) {
alert("please enter your name");
}
if(!$('#email').val()) {
alert("plese enter your email adress");
}
else{
alert("Thank you for subscribing to SHCA");
}
document.forms["ContactForm"].reset();
});
});
You need to check the contents of the fields before submitting to the server, a simple script method can check before you submit. If the fields are empty then display an error messge and don't submit the form.
function SubmitDetails()
{
if(window.ContactForm.name.value == "")
{
window.alert("Please enter a name");
return;
}if(window.ContactForm.email.value == "")
{
window.alert("Please enter an email" );
return;
}
window.ContactForm.submit();
}
This should do it without having to do a refresh
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#ContactForm').ajaxForm(function() {
if( !$(#name).val() || !$(#email).val()) {
//don't display
}else{
alert("Thank you for subscribing to SHCA");
}
document.forms["ContactForm"].reset();
});
});