I have a basic web application that has been coded in php.
The app carries out CRUD operations by making use of an API made through PHP. When I try to use my update.php API endpoint, I get a successful response but no changes reflect in db.
Project Structure
Project_Structure
update.php in api/mailbox
<?php
// include database and object files
include_once '../config/database.php';
include_once '../objects/mailbox.php';
// get database connection
$database = new Database();
$db = $database->getConnection();
// prepare mailbox object
$mailbox = new Mailbox($db);
//For diagnostics
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data[""];
// set ID property of product to be edited
$mailbox_id->mailbox_id = $data->mailbox_id;
// set mailbox property values
$mailbox->username = $_POST['username'];
$mailbox->password = base64_encode($_POST['password']);
$mailbox->name = $_POST['name'];
$mailbox->quota = $_POST['quota'];
$mailbox->modified = date('Y-m-d H:i:s');
$mailbox->active = $_POST['active'];
$mailbox->mailbox_id = $_POST['mailbox_id'];
// create the mailbox
if($mailbox->update()){
$mailbox_arr=array(
"status" => true,
"message" => "Successfully Updated Mailbox"
);
}
else{
$mailbox_arr=array(
"status" => false,
"message" => "Mailbox already exists!"
);
}
print_r(json_encode($mailbox_arr));
?>
mailbox.php(in objects folder)
// update mailbox
function update(){
$query = "UPDATE
". $this->table_name ."
SET
username='".$this->username."', password='".$this->password."', name='".$this->name."', quota='".$this->quota."', modified='".$this->modified."', active='".$this->active."'
WHERE
mailbox_id= '".$this->mailbox_id."'";
// prepare query
$stmt = $this->conn->prepare($query);
// execute query
if($stmt->execute()){
return true;
}
return false;
}
update.php (The rendered page, on clicking update, the error is: **Mailbox already exists)**
<?php
$content = '<div class="container"
<div class="row">
<!-- left column -->
<div class="col-md-12">
<!-- general form elements -->
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Update Mailbox</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<form role="form">
<div class="box-body">
<div class="form-group">
<div class="form-group">
<label for="exampleMBID1">Mailbox ID</label>
<input type="text" class="form-control" id="mailbox_id" placeholder="Mailbox ID" disabled>
</div>
<label for="exampleInputUserName1">User Name</label>
<input type="text" class="form-control" id="username" placeholder="Enter Username e.g jsmith">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="password" placeholder="Enter Password">
</div>
<div class="form-group">
<label for="exampleInputName1">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name of User">
</div>
<div class="form-group">
<label for="exampleInputMaildir1">Maildir</label>
<input type="text" class="form-control" id="maildir" placeholder="Enter Maildir" disabled>
</div>
<div class="form-group">
<label for="exampleInputQuota1">Quota (0=Unlimited)</label>
<input type="text" class="form-control" id="quota" placeholder="Enter Quota">
</div>
<div class="form-group">
<label for="examplelocalpart1">Local Part</label>
<input type="text" class="form-control" id="local_part" placeholder="localpart" disabled>
</div>
<div class="form-group">
<label for="exampledomain1">Domain</label>
<input type="text" class="form-control" id="domain" placeholder="domain" disabled>
</div>
<div class="form-group">
<label for="examplecreated1">Created</label>
<input type="text" class="form-control" id="created" placeholder="Created" disabled>
</div>
<div class="form-group">
<label for="examplemodified1">Modified</label>
<input type="text" class="form-control" id="modified" placeholder="Modified">
</div>
<div class="form-group">
<label for="exampleactive1">Active (0=Not Active, 1=Active)</label>
<input type="text" class="form-control" id="active" placeholder="Enter 0 or 1">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<input type="button" class="btn btn-primary" onClick="UpdateMailbox()" value="Update"></input>
</div>
</form>
</div>
<!-- /.box -->
</div>
</div>
</div>';
include('../master.php');
?>
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: "../api/mailbox/read_single.php?mailbox_id=<?php echo $_GET['mailbox_id']; ?>",
dataType: 'json',
success: function(data) {
$('#username').val(data['username']);
$('#password').val(data['password']);
$('#name').val(data['name']);
$('#maildir').val(data['maildir']);
$('#quota').val(data['quota']);
$('#local_part').val(data['local_part']);
$('#domain').val(data['domain']);
$('#created').val(data['created']);
$('#modified').val(data['modified']);
$('#active').val(data['active']);
$('#mailbox_id').val(data['mailbox_id']);
},
error: function (result) {
console.log(result);
},
});
});
function UpdateMailbox(){
$.ajax(
{
type: "POST",
url: '../api/mailbox/update.php',
dataType: 'json',
data: {
mailbox_id: <?php echo $_GET['mailbox_id']; ?>,
username: $("#username").val(),
password: $("#password").val(),
name: $("#name").val(),
maildir: $("#maildir").val(),
quota: $("#quota").val(),
domain: $("#domain").val(),
modified: $("#modified").val(),
active: $("#active").val()
},
error: function (result) {
alert(result.responseText);
},
success: function (result) {
if (result['status'] == true) {
alert("Successfully Updated Mailbox!");
window.location.href = '/MailEasy/mailbox/listAll.php';
}
else {
alert(result['message']);
}
}
});
}
</script>
1) Why is not updating when using web UI?
2) When using postman, it shows successful, why are requests not reaching the database?
Postman --> Successful response but no changes in db.
Php webpage --> Mailbox already exists.
Thank you
Related
Right now I am facing a problem : I am trying to insert records in the database with the help of jQuery & Ajax. Unfortunately, I tried to alert inserted values but It doesn't show. I also checked through serialize function and I am unable to do that.
Here is my code of ajax
<script type="text/javascript">
$(document).ready(function(){
$("#add_new").click(function(){
$("#add").slideToggle();
});
$("#submit").click(function(){
var stud_no=$("#roll").val();
if(stud_no==''){
$("#msg").html("Input Roll Number");
} else {
var datastr = $("#sampleform").serialize();
alert(datastr);
$.ajax({
type:'POST',
url:'add_it.php',
data:datastr,
success:function(response){
$("#my_form")[0].reset();
$("#msg").html("Student Successfully Added");
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
});
});
</script>
Here is body code :
<body>
<a id="add_new">+add new item</a><br /><br />
<div id="msg"></div><br />
<div id="add">
<form id="sampleform">
<fieldset>
<div class="form-group row">
<label for="roll" class="col-sm-2 col-form-label">Roll Number</label>
<div class="col-sm-6">
<input type="text" name="roll" class="form-control" id="roll">
</div>
</div>
<div class="form-group row">
<label for="name" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-6">
<input type="text" name="name" class="form-control" id="name">
</div>
</div>
<div class="form-group row">
<label for="clas" class="col-sm-2 col-form-label">Class</label>
<div class="col-sm-6">
<input type="text" name="standard" class="form-control" id="standard">
</div>
</div>
<div class="form-group row">
<label for="mail" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-6">
<input type="email" name="mail" class="form-control" id="mail">
</div>
</div>
<button type="submit" id="submit" class="btn btn-primary">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</fieldset>
</fieldset>
</form>
</div>
Here is my add_it.php
<?php
include('connectdb.php');
$stud_no = trim($_POST['stud_no']);
$name = trim($_POST['name']);
$standard = trim($_POST['standard']);
$mail = trim($_POST['mail']);
$query = "insert into student (stud_no,name,standard,email) values ('$stud_no','$name','$standard','$mail')";
mysqli_query($con,$query) or die (mysqli_error());
?>
Your HTML form fields doesnt have any of these variables sent. You need to add name="email" etc to your form fields.
So for example the email field has to look like this:
<input type="email" name="email" class="form-control" id="mail">
id, class etc is not sent in POST - and therefor can not be recieved in the other end.
Jquery's serialize() function also only handles "name" fields.
https://api.jquery.com/serialize/
Snippet :
For a form element's value to be included in the serialized string, the element must have a name attribute
I have created one IMS System. In that i have to create bill on order page and in order page when i select customer name from drop down than customer_address,customer_phone and gst number should automatically fill in text box.In database i have created one table named partys in that all data are available(Customer_name,Customer_address,customer_phone and gst) If anybody knows solution than please help.
Below is my code
<?php
$dbc = mysqli_connect('localhost', 'root', '', 'stock')
or die('Error connecting to MySQL server.');
$query = "SELECT * FROM partys";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $row['party_name'] ?>"><?php echo $row['party_name'] ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<label for="gross_amount" class="col-sm-5 control-label" style="text-align:left;">Customer Address</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="customer_address" name="customer_address" placeholder="Enter Customer Address" autocomplete="off">
</div>
</div>
<div class="form-group">
<label for="gross_amount" class="col-sm-5 control-label" style="text-align:left;">Customer Phone</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="customer_phone" name="customer_phone" placeholder="Enter Customer Phone" autocomplete="off">
</div>
</div>
<div class="form-group">
<label for="gstin" class="col-sm-5 control-label" style="text-align:left;">GSTIN</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="gstin" name="gstin" placeholder="Enter GST Number" autocomplete="off">
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
// On change of the dropdown do the ajax
$("#client").change(function() {
$.ajax({
// Change the link to the file you are using
url: '/create.php',
type: 'post',
// This just sends the value of the dropdown
data: {customer_name : party_name},
dataType: 'json',
success: function(response) {
// Parse the jSON that is returned
// Using conditions here would probably apply
// incase nothing is returned
var Vals = JSON.parse(response);
// These are the inputs that will populate
$("#customer_address").val(response.customer_address);
$("#customer_phone").val(response.customer_phone);
$("#gstin").val(response.gstin);
}
});
});
});
</script>
I have created a form for users in WordPress in a custom page, the code is below.
<div class="container" style="padding-top: 30px;width: 60%;">
<div id="FormBlock">
<form action="">
<div class="row form-group">
<div class="col-md-6">
<label for="lname">First Name:</label>
<input type="text" class="form-control" name="firstName" placeholder="Enter First Name..">
</div>
<div class="col-md-6">
<label for="lname">Last Name:</label>
<input type="text" class="form-control" name="lastName" placeholder="Enter Last Name..">
</div>
</div>
<div class="row form-group" style="margin-bottom: -8px;">
<div class="col-md-6">
<label for="email">Email</label>
<input type="email" class="form-control" name="email" placeholder="Enter Email..">
</div>
<div class="col-md-2">
<label for="cell">Phone:</label>
<?php echo countrySelector(); ?>
</div>
<div class="col-md-4">
<div class="input-group">
<label for=""> </label>
<input type="text" class="form-control" name="cellnumber" placeholder="Enter Phone Number..">
<label for=""> </label>
<span class="input-group-btn">
<button type="button" class="btn btn-basic" id="verify">Verify</button>
</span>
</div>
</div>
</div>
<div class="row form-group">
<div class="col-md-6">
<label for="Citizenship">Country of Citizenship</label>
<?php echo CountryNames("Citizenship","Citizenship"); ?>
</div>
<div class="col-md-6">
<label for="residence">Country of Residence</label>
<?php echo CountryNames("Residence","Residence"); ?>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label for="address">Residential Address</label>
<input type="text" class="form-control" name="address" placeholder="Enter your address..">
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<label for="ec2wallet">EC2 Wallet Address</label>
<input type="text" class="form-control" name="ec2wallet" placeholder="Enter your EC2 Wallet address..">
</div>
</div>
<div class="row">
<div class="col-md-12">
<label for="Upload">Upload your documents</label>
</div>
</div>
<div class="row form-group">
<div class="col-md-6">
<input type="file" name="identity" id="identity" class="form-control">
<label for="identity"><small>Upload proof of identity (Passport, Driver’s License, National Identification)</small></label>
</div>
<div class="col-md-6">
<input type="file" name="selfie" id="selfie" class="form-control">
<label for="selfie"><small>Take Selfie or Upload front facing picture</small></label>
</div>
</div>
<div class="row form-group">
<div class="col-md-12">
<input type="file" name="residenceID" id="residenceID" class="form-control">
<label for="residenceID"><small>Upload proof of residence (ID Card containing your address or utility bill, credit card statement, bank statement or tax bill dated within last 3 months).</small></label>
</div>
</div>
</form>
</div>
</div>
now I have three fields in which user have to upload documents/pics and I want to use WordPress proper method to upload media in which WordPress create database entries and their metadata etc.. and also if an image is an upload then WordPress creates it multiple sizes like a thumbnail or anything like that.
here is a view of my form.
Form View
can anyone help me or suggest me how can i do that?
I tried using ajax uploader or jquery uploading method, but there I have to do many things myself like making db entries. is there any proper method I have to follow?
using ajax call you need to create function in functions.php file.
your ajax call like:
$("#YourButtnID").click(function(){
var firstname = $('#fname').val();
// get all the fields (input) like this..
// and now for all the input type files.
var identity = jQuery('#identity').prop('files')[0];
var residence = jQuery('#residenceID').prop('files')[0];
var selfie = jQuery('#selfie').prop('files')[0];
//creating formData and inserting data into it
var formData = new FormData();
//action -> this will be your function name in functions.php
formData.append('action','your_custom_function');
//now all the data .. appending
formData.append('fname',firstname);
//Your images
formData.append('identity', identity);
formData.append('residence', residence);
formData.append('selfie', selfie);
$.ajax({
type: "POST",
url: ajaxurl,
contentType: false,
processData: false,
data: formData,
dataType: "JSON",
success:function(data){
if(data['status']){
//All went well
}else{
// something went wrong
},
error:function(err){
// You might not have caught any exception
}
});
and now in your functions.php file, create function to get all this done
<?php
function your_custom_function(){
// initial response is false by default
$response = array ('status'=>false,'msg'=>'invalid code');
// you can have server side validation here if you want
// i.e. if(!$_REQUEST['fname']) this means if this field is not sent.. then return relevant response
if (!function_exists('wp_handle_upload')) {
require_once(ABSPATH . 'wp-admin/includes/file.php');
}
$yourDBTable = $wpdb->prefix.'yourDBTable';
$uploadedfile = $_FILES['identity'];
$upload_overrides = array('test_form' => false);
$movefile = wp_handle_upload($uploadedfile, $upload_overrides);
//after uploading to uploads DIR you will get url of your image here
$id_url = $movefile['url'];
$uploadedfile = $_FILES['residence'];
$upload_overrides = array('test_form' => false);
$movefile = wp_handle_upload($uploadedfile, $upload_overrides);
$resid_url = $movefile['url'];
$uploadedfile = $_FILES['selfie'];
$upload_overrides = array('test_form' => false);
$movefile = wp_handle_upload($uploadedfile, $upload_overrides);
$selfie_url = $movefile['url'];
$user_data = array(
'fname' => $_REQUEST['fname'],
'photo_identity' => $id_url,
'photo_selfie' => $selfie_url,
'photo_residence' => $resid_url
);
try {
$result = $wpdb->insert($yourDBTable,$user_data);
$response['status']=true;
} catch (Exception $e) {
$response['msg']="Something went wrong";
}
echo json_encode($response);
wp_die();
}
<div class="row">
<div class="col-xs-12 col-lg-10 col-lg-offset-1">
<form method="post" action="" name="contactForm" id="contactform" class="clearfix">
<fieldset>
<div class="float-left">
<div class="coolfx fadeInUp">
<!--<span>*Name<label for="name"></label></span>-->
<span><input type="text" id="contactName" name="name" placeholder="*Name" class="text" required></span>
</div>
<div class="coolfx fadeInUp" >
<!--<span>*Email<label for="email"></label></span>-->
<span><input type="email" id="contactEmail" name="email" placeholder="*Email" class="email" required></span>
</div>
<div class="coolfx fadeInUp">
<!--<span>Phone<label for="phone"></label></span>-->
<span><input type="text" id="contactPhone" name="phonenumber" placeholder="Phone" class="text" required></span>
</div>
</div>
<div class="float-right">
<div class="contactform message coolfx fadeInUp">
<!--<span>Message<label for="message"></label></span>-->
<span><textarea id="contactMessage" placeholder="*Message" name="message" class="textarea" required></textarea></span>
</div>
</div>
</fieldset>
<div class="float-right"><div class="g-recaptcha" data-sitekey="6LfsPBgTAAAAAPDkaI1HeSyDm_ecF0iihVsFYBKh"></div></div>
<div class="coolfx fadeInUp">
<input name="send" type="submit" class="submit" id="submit" value="Send Email">
</div>
<?php
if(isset($_POST['g-recaptcha-response']))
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "******************************";// hide for security
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
$data = json_decode($response);
if (isset($data->success) AND $data->success==true) {?>
<script type="text/javascript">
$(function() {
$("#contactform .submit").click(function() {
var data = {
name: $("#contactName").val(),
email: $("#contactEmail").val(),
phone: $("#contactPhone").val(),
message: $("#contactMessage").val()
};
$.ajax({
type: "POST",
url: "email.php",
data: data,
success: function(){
$('.success').fadeIn(1000);
}
});
});
});
</script>
<?php }else {
echo"this is spam"
}?>
I am new in j query how to use j query code inside the php code and also how to verify google captcha code before submit a mail function nothing working .
before google captcha working my code properly but now nothing working.
thanks
You need to handle the Captcha inside email.php. Before getting other posted field values you can check for Capcha response. Also don't forget that you need to post the captcha field (g-recaptcha-response) value like you post name, phone, email and messsage.
I have a registration form for my website, and it is showing username, password and password confirmation required although i am providing all of these. This is the controller code:
{
$this->load->library('form_validation');
$this->form_validation->set_rules('username','Username','trim|required|min_length[4]|xss_clean');
$this->form_validation->set_rules('email','Email','trim|required|valid_email');
$this->form_validation->set_rules('pass1','Password','trim|required|min_length[4]|max_length[32]');
$this->form_validation->set_rules('pass2','Password Confirmation','trim|required|matches[pass1]');
if ($this->form_validation->run() === FALSE)
{
$password = $this->input->post('pass1');
echo json_encode(array('error' => '1', 'message' => validation_errors('<div class="alert alert-error"><strong>Error!</strong> ', '</div>')));
}
else
{
$username = $this->input->post('username');
$password = $this->input->post('pass1');
$email = $this->input->post('email');
$date = date('Y/m/d H:i:s');
$this->load->model('ui_model');
$this->ui_model->register_user($username,$password,$email,$date);
echo json_encode(array('error' => '0', 'message' => '<div class="alert alert-success"><strong>Success!</strong> You have been registered!</div>'));
}
and this is the view code:
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Registration</h3>
</div>
<div class="modal-body">
<div id="registerModalerror" style="display: none;"></div>
<?php
$attributes = array('class' => 'form-horizontal','id' => 'registerModalform');
echo form_open('',$attributes);
?>
<div class="control-group">
<label class="control-label" for="Username">Username</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-user"></i></span>
<input type="text" id="inputUser" placeholder="Username" name="username" value ="" >
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail">Email</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-envelope"></i></span>
<input type="text" id="inputEmail" placeholder="email" name="email" value = "">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-lock"></i></span>
<input type="password" id="inputPassword" placeholder="Password" name="pass1" value = "">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword2">Retype Password</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-lock"></i></span>
<input type="password" id="inputPassword2" placeholder="Retype Password" name="pass2" value = "">
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn">Register</button>
</div>
</div>
</div>
<?php echo form_close(); ?>
<div class="modal-footer">
</div>
</div>
<script>
$(document).ready(function() {
$('#myModalReg').removeData('modal');
$('#myModalReg').hide();
$('#registerModalform').submit(registerUser);
});
function registerUser(event)
{
//Stop the form from submitting
event.preventDefault();
//Collect our form data.
var form_data = {
username : $("[name='username']").val(),
password1 : $("[name='pass1']").val(),
password2 : $("[name='pass2']").val(),
email : $("[name='email']").val()
};
//Begin the ajax call
$.ajax({
url: "http://localhost/fys/index.php/ui/do_register",
type: "POST",
data: form_data,
dataType: "json",
cache: false,
async : false,
success: function (json) {
// alert(json.pass);
if (json.error==1)
{
$('#registerModalerror').html(json.message).show();
}
else {
//Hide our form
$('#registerModalform').slideUp();
//Show the success message
$('#registerModalerror').html(json.message).show();
}
},
error: function(json)
{
alert(json.message);
}
});
}
</script>
I am not sure where it went wrong, and it is bugging me for almost 24 hours. Can anyone provide some help?
Thanks!
Your POST object is
{
username : $("[name='username']").val(),
password1 : $("[name='pass1']").val(),
password2 : $("[name='pass2']").val(),
email : $("[name='email']").val()
}
But your Controller's POST name is pass1 and pass2. You're passing up password1 and password2
:P