Show/hide DIV with create, edit, delete - php

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.

Related

Unable to Pass Data Into DB Using AJAX

I'm trying to save some data into db using AJAX.It says it's successfully done but nothing happens.No data is being saved.Just keeps saying "Success".
index.php // form
<div id="cont">
<div id="kayit" style="display:none;">
Success
</div>
<div id="basarisiz" style="display:none;">
Empty or Fail
</div>
<form method="post" id="yaz" onsubmit="return false">
<input type="text" name="title" id="baslik" placeholder="Başlık" required><br/>
<textarea name="content" ></textarea><br/>
<input type="submit" name="gonder" value="Gönder" id="gonder" onclick="kayit()">
</form>
yaz.js
function kayit()
{
var baslik = $("input[name=title]").val();
var icerik = $("input[name=content]").val();
if (baslik =="" || icerik == "")
{
$('#basarisiz').show(1);
$('#kayit').hide(1);
}else
{
$.ajax ({
type: "POST",
url: "yazikaydet.php",
data: $("#yaz").serialize(),
success: function (sonuc) {
if (sonuc == "hata") {
alert ("unable to connect to db");
}else {
$('#kayit').show(1);
$('#basarisiz').hide(1);
$("input[name=title]").val("");
$("input[name=content]").val("");
}
}
}) }}
yazikaydet.php //the file which will save the data,not processing
<?php
include 'giris.php'; //sessions and connection strings
if(isset($_POST["gonder"]))
{
$baslik = $_POST["title"];
$icerik = $_POST["content"];
$tarih = date("d/m/20y");
$kull = $_SESSION["username"];
$kaydet = mysqli_query($connect,"INSERT INTO gonderiler (yazar,tarih,baslik,icerik) VALUES ('$kull','$tarih','$baslik','$icerik')");
if($kaydet)
{
echo "Yes";
}
else
{
echo "No";
}
}
?>

In codeigniter How to redirect after login using ajax

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');
}

stop form from submitting (tried e.preventDefault() after $.post but it stops form from submitting

I have this in javascript
$('#submit').on('click', function(e) {
$('#message_line').text("");
if(validate_fields_on_submit()) {
e.preventDefault();
return;
}
// e.preventDefault();
var params = $('form').serialize();
$.post('check_duplicate.php', params, function(responseText) {
submitHandler(responseText);
});
// e.preventDefault();
//return false;
});
function submitHandler(response) {
$('#message_line').text("");
response = $.trim(response);
if(response == "" && response.indexOf("<") <= -1)
$('#registration').submit();
else if(response.indexOf("<") == 0) {
var name = $('[name="regusername"]').val();
$('#message_line').text("Some error occured, please try after some time.");
$("#message_line").attr("tabindex",-1).focus();
return false;
} else {
var name = $('[name="regusername"]').val();
var arr = response.split(',');
arr.pop();
arr.toString();
$('#message_line').text("'" + name + "' already exists, Please try different username");
$("#regusername").focus();
return false;
}
$('#busy_wait').css('display','none');
}
HTML CODE
<?php
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
include("db/helper_functions.php");
if(validate_fields()) {
if(!check_duplicate($_POST["regusername"])) {
$count = insert_record($_POST["fname"],$_POST["lname"],$_POST["email"],$_POST["regusername"],$_POST["regpassword"]);
if($count > 0) {
include("includes/confirmation.php");
exit();
}
else {
$error = "Sorry registration failed, please try again.";
}
}
else {
$error = "Username already exists, please try different username.";
}
}
}
$page_title = "Registration";
if(isset($_SESSION["username"]))
include('includes/header_authorized.html');
else
include('includes/header.html');
?>
<div class="container">
<div class="regform">
<form name="registration" id="registration" method="post" action="registration.php">
<p><span class="req">* required field.</span></p>
<ul>
<li><label for="fname">First Name:</label>
<input type="text" class="textboxborder" id="fname" name="fname" size="20" maxlength="25" autofocus="autofocus" value="<?php if(isset($_POST['fname'])) echo $_POST['fname'];?>"/>
<span class="error" id="errfname">*<?php if(isset($errfname)) echo $errfname;?></span>
</li>
<li><label for="lname">Last Name:</label>
<input type="text" class="textboxborder" id="lname" name="lname" size="20" maxlength="25" value="<?php if(isset($_POST['lname'])) echo $_POST['lname'];?>"/>
<span class="error" id ="errlname">*<?php if(isset($errlname)) echo $errlname;?></span>
</li>
<li><label for="email">Email:</label>
<input type="text" class="textboxborder" name="email" id="email" size="40" maxlength="50" placeholder="abc#xyz.com" value="<?php if(isset($_POST['email'])) echo $_POST['email'];?>"/>
<span class="error" id="erremail">*<?php if(isset($erremail)) echo $erremail;?></span>
</li>
<li><label for="regusername">Username:</label>
<input type="text" name="regusername" id="regusername" size="20" maxlength="30" value="<?php if(isset($_POST['regusername'])) echo $_POST['regusername'];?>"/>
<span class="error" id="errregusername">*<?php if(isset($errregusername)) echo $errregusername;?></span>
</li>
<li><label for="regpassword">Password:</label>
<input type="password" name="regpassword" id="regpassword" size="20" maxlength="15" value="<?php if(isset($_POST['regpassword'])) echo $_POST['regpassword'];?>"/>
<span class="error" id="errregpassword">*<?php if(isset($errregpassword)) echo $errregpassword;?></span>
</li>
<li><label for="regconpassword">Confirm Password:</label>
<input type="password" name="regconpassword" id="regconpassword" size="20" maxlength="15"/>
<span class="error" id="errregconpassword">*<?php if(isset($errregconpassword)) echo $errregconpassword;?></span>
</li>
</ul>
<div id="message_line"> <?php if(isset($error)) echo $error;?></div>
<div class="buttons">
<input type="reset" value="Reset" id="reset"/>
<input type="submit" value="Submit" />
</div>
</form>
<img src="images/loading.gif" id="busy_wait" alt="busy wait icon" />
</div>
</div>
</body>
</html>
If in submit handler control goes in else if or else block form submission does not stop,I tried return false; and I tried using e.preventDefault(); at different places before ajax call and after but that stops form submission even after validation success and successful return from check_duplicate.php
Any help would be appreciated.
Assuming you have a submit button with id=submit, I would
rename the button since calling anything submit is poor practice since you need to actually submit the form programatically.
move the handler to the form submit event - I personally NEVER attach a handler to a submit button
I assume you do NOT want to submit if the validation returns false
Like this
$('#registration').on('submit', function(e) {
e.preventDefault();
$('#message_line').text("");
if(!validate_fields_on_submit()) { // I assume you meant NOT
return;
}
var params = $(this).serialize();
$.post('check_duplicate.php', params, function(responseText) {
submitHandler(responseText);
});
});
the post can be written
$.post('check_duplicate.php', params, submitHandler);
UPDATE Here is the complete script - NOTE IMPERATIVE to rename anything name=submit or id=submit to something else
$(function() {
$('#registration').on('submit', function(e) {
e.preventDefault();
$('#message_line').text("");
if(!validate_fields_on_submit()) { // I assume you meant NOT
return;
}
$('#busy_wait').show();
$.post('check_duplicate.php', $(this).serialize(), function(response) {
response = $.trim(response);
if (response == "" && response.indexOf("<") <= -1) {
$('#registration').submit(); // actually submit the form
}
else if(response.indexOf("<") == 0) {
var name = $('[name="regusername"]').val();
$('#message_line').text("Some error occured, please try after some time.");
$("#message_line").attr("tabindex",-1).focus();
} else {
var name = $('[name="regusername"]').val();
$('#message_line').text("'" + name + "' already exists, Please try different username");
$("#regusername").focus();
}
$('#busy_wait').hide();
});
});
Update3:
$(function() {
$('#registration').on('submit', function(e) {
e.preventDefault();
$('#message_line').text("");
if(!validate_fields_on_submit()) { // I assume you meant NOT
return;
}
$('#busy_wait').show();
var $thisForm=$(this); // save for later
var params = $thisForm.serialize();
$.post('check_duplicate.php', params, function(response) {
response = $.trim(response);
if (response == "" && response.indexOf("<") <= -1) {
// actually submit the form
$.post($thisForm.prop("action"), params, function(response) {
if (response.indexOf("success") !=-1) {
$('#message_line').text(response);
}
else {
$('#message_line').text("something went wrong");
}
$('#busy_wait').hide();
});
}
else if(response.indexOf("<") == 0) {
var name = $('[name="regusername"]').val();
$('#message_line').text("Some error occured, please try after some time.");
$("#message_line").attr("tabindex",-1).focus();
} else {
var name = $('[name="regusername"]').val();
$('#message_line').text("'" + name + "' already exists, Please try different username");
$("#regusername").focus();
}
$('#busy_wait').hide();
});
});
To prevent form submission the best method will be to return false on the onclick client event
Eg
$('#submit').click(function(){
return false;
})

Creating PHP Forms using jquery/ajax

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.

copyserviceimage function ajax wordpress

I have an upload field in my form.
I had this code in my form.php
<form id="photoform" name="photoform" method="post" onSubmit="return false" enctype="multipart/form-data">
<div id="upphotosection"></div>
<label>Upload photo</label>
<input name="uploadphoto" id="uploadphoto" type="file" />
<div class="innerformclear"></div>
<input id="hidden" value="" name="hidden" type="hidden" />
<label> </label>
<input name="upphoto_submit" id="upphoto_submit" type="submit" value="Submit"/>
<div style="clear:both;"> </div>
<label> </label>
<div id="result_upphoto_submit"></div>
</form>
This is the code in formaction.php
header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");
include("../../../wp-load.php");
session_start();
$err = '';
$success = '';
global $wpdb, $PasswordHash, $current_user, $user_ID;
if($upphoto = $_FILES['uploadphoto']["name"] != '' ){
$path = 'images/profilephotos/';
$upphoto = copyServiceImage($path,$_FILES['uploadphoto']) ;}
$postid = 52;
############### Check Duplication
$sel_photo = "SELECT * FROM `pro_table` WHERE `post_id` = '".$postid."'";
$sel_res = mysql_query($sel_photo) ;
if(mysql_num_rows($sel_res) == 0){
$ins_photo = "Insert into pro_table (post_id,photo_photo,int_status) values ('$postid','$upphoto','0')";
$ins_res = mysql_query($ins_photo);
}
else{
$upd_photo = "Update pro_table set photo_photo = '$upphoto' ,int_status='0' where post_id = '$postid' ";
$upd_res = mysql_query($upd_photo);
}
echo $_GET['callback'] . '('.json_encode("success").')';
This is the code in java script file.
$(document).ready(function() {
///////////// Submit action for upload photo
$("#upphoto_submit").click(function() {
if(document.getElementById('uploadphoto').value == '' ){
alert("Please upload Photo");
document.getElementById('uploadphoto').focus();
return false;
}
else {
$('#result_upphoto_submit').html('<img src="http://www.test.com/test/uploads/2012/04/ajax-loader.gif" class="loader" align="absmiddle" /> ').fadeIn();
var input_data = $('#photoform').serialize();
$.ajax({
type: "POST",
url: "http://www.test.com/test/themes/test/formaction.php",
dataType: 'jsonp',
data: input_data,
success: function(msg){
$('#result_upphoto_submit').html(' ');
if(msg == 'success') {
msg = '<p class="success_custom">Photo successfully added.</p>';
$('<div>').html(msg).appendTo('div#upphotosection').hide().fadeIn('slow');
} else {
msg = ' Exists';
alert("Error in updation");
}
}
});
return false;
}
});
});
If i browse an image and click submit it showed me the success message Photo successfully added. But there is no image in profile photos folder and there is no data stored in admin panel. I couldn't track the error. How do i correct that?
is there an error in?
$_FILES["uploadphoto"]["error"];
also i dont know how wordpress handle images but i miss the file movement:
if ($_FILES["uploadphoto"]["error"] != UPLOAD_ERR_OK) {
$tmp_name = $_FILES["uploadphoto"]["tmp_name"];
$name = $_FILES["pictures"]["name"];
$path = "images/profilephotos/".$name;
move_uploaded_file($tmp_name,$path);
}
or i suppose it is called here?
$upphoto = copyServiceImage($path,$_FILES['uploadphoto']) ;}

Categories