fill half form input fill on basis of another filled input - javascript

I want to create a billing system for my society application, in this system I want to generate few field dynamically on the basis of what value are reside in the form.means half form will have few data on that data I want to generate another field.
for example: when I select username I will have user type,flatno,parking slot value, now I want to particular charges if user type is owner / tenant.
my code is :
<form class="form-horizontal" role="form" method="post" id="genbill">
<div class="form-group">
<label class="col-lg-3 control-label">Person Name:</label>
<div class="col-lg-8">
<select id="user_nm" name ="user_nm" class=" form-control"></select>
<input type="hidden" name="email" id="email" class="form-control" value="">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">User Type:</label>
<div class="col-lg-8">
<input type="text" name="role" id="role" class="form-control" value="">
<!-- <select id="flatno" name ="flatno" class=" form-control"></select> -->
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Flat No.:</label>
<div class="col-lg-8">
<input type="text" name="flatno" id="flatno" class="form-control" value="">
<!-- <select id="flatno" name ="flatno" class=" form-control"></select> -->
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">PAN No.:</label>
<div class="col-lg-8">
<input type="text" name="pan" id="pan" class="form-control" value="">
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Parking Slot.:</label>
<div class="col-lg-8">
<input type="text" name="parking" id="parking" class="form-control" value="">
</div>
</div>
<div id="chargeField">
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Bill Due Date:</label>
<div class="col-lg-8" >
<select name="Duegroup" id="billdate"></select>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Bill Period:</label>
<div class="col-lg-8">
<select name="billgroup" id="daterange">
</select>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Total:</label>
<div class="col-lg-8">
<input type="text" class="form-control" onfocus="findTotal()" name="total" id="total" value="" >
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"></label>
<div class="col-md-8">
<input class="btn btn-primary" value="Save" type="submit" name="Add">
<span></span>
<input class="btn btn-default" value="Cancel" type="reset">
</div>
</div>
</form>
fill input on usernm chnages
$('#user_nm').on('change', function() {
//alert( this.value );
//var user_nm = document.getElementById('user_nm').value;
var user_nm = this.value;
var flat = document.getElementById('flatno');
var email = document.getElementById('email');
var pan = document.getElementById('pan');
var role = document.getElementById('role');
var park = document.getElementById('parking');
//alert('nm'+user_nm);
$.ajax({
type: "post",
url: "getFlatno.php",
dataType: "json",
data: { email: user_nm },
success: function(data) {
if (data.result == 1) {
flat.value = data.flat;
email.value = data.email;
pan.value = data.pan;
role.value = data.role;
park.value = data.parking;
} else {
alert('failure');
}
}
});
})
retrive charges field
$( "#parking" ).focusout(function() {
// alert( "Handler for .focus() called." );
var email = document.getElementById('email').value;
var role = document.getElementById('role').value;
var park = document.getElementById('parking').value;
alert(email);
alert(role);
alert(park);
$.ajax({
type: "post",
url: "getChargeAsperRole.php",
dataType: "json",
data:{
email:email,
role:role,
park:park
},
success: function(data) {
var html = "";
alert('success');
$.each(data, function(i, item) {
html = html + '<div class="form-group"><label class="col-lg-3 control-label">' + item.charge_title + ':</label><div class="col-lg-8"><input type="checkbox" name="charge_Arr[]" value= "' + item.charge_amt + '" class="checkValue" /><input class="form-control" id="field' + item.num + '" type="text" name="field' + item.num + '" value="' + item.charge_amt + '" readonly><input type="hidden" name="fieldid[]" id="fieldid' + item.num + '" class="form-control" value="' + item.Id + '"></div></div>';
});
$("#chargeField").html(html);
}
});
});
get Charges code :
if($_SERVER['REQUEST_METHOD']=='POST'){
$email = $_POST['email'];
$role = $_POST['role'];
$parking = $_POST['park'] ;
echo $parking;
if($role!='' && $parking!='' && $parking!=0){
$sql = "SELECT c.charge_id,c.u_id,u.ID,u.role,b.charge_id,b.charge_title FROM `users` u ,`billing_charges` b ,`charge_applied` c where c.charge_id=b.charge_id and u.ID = c.u_id and u.role='$role' and parking_slot='$parking'";
echo "one==".$sql;
}elseif($role!='' && $parking=='' && $parking!=0){
$sql = "SELECT c.charge_id,c.u_id,u.ID,u.role,b.charge_id,b.charge_title FROM `users` u ,`billing_charges` b ,`charge_applied` c where c.charge_id=b.charge_id and u.ID = c.u_id and u.role='$role'";
echo "two==".$sql;
}elseif($role!='' && $parking=='' && $parking!=0){
$sql = "SELECT c.charge_id,c.u_id,u.ID,u.role,b.charge_id,b.charge_title FROM `users` u ,`billing_charges` b ,`charge_applied` c where c.charge_id=b.charge_id and u.ID = c.u_id and parking_slot='$parking'";
echo "thiree==".$sql;
}elseif($parking!='0'){
$sql = "SELECT c.charge_id,c.u_id,u.ID,u.role,b.charge_id,b.charge_title FROM `users` u ,`billing_charges` b ,`charge_applied` c where c.charge_id=b.charge_id and u.ID = c.u_id";
echo "four==".$sql;
}else{
echo "nkagg";
}
// $sql = "SELECT c.charge_id,c.u_id,u.ID,u.role,b.charge_id,b.charge_title FROM `users` u ,`billing_charges` b ,`charge_applied` c where c.charge_id=b.charge_id and u.ID = c.u_id";
$sql = "select * FROM `billing_charges`";
//echo $sql;
$arrVal = array();
$sqltran = mysqli_query($con,$sql )or die(mysqli_error($con));
$i=1;
while ($rowList = mysqli_fetch_array($sqltran)) {
$name = array(
'num' => $i,
'Id' => $rowList['charge_id'],
'charge_title'=> $rowList['charge_title'],
'charge_type'=> $rowList['charge_type'],
'charge_amt'=> $rowList['charge_amt'],
);
array_push($arrVal, $name);
$i++;
}
echo json_encode($arrVal);
mysqli_close($con);
}

If you need to change the content on input B based on the change of content of input A you can use the onchange Event
Change input A to include the call to a javascript function like the following:
<input id="a" onchange="myFunction()">
And in the script section implement myFunction() to do your intended work
<script>
function myFunction() {
var x = document.getElementById("a").value;
if(x=="Hello")
document.getElementById("b").value = "World";
}
</script>

Related

Submit button does not work, how to make it work? (code provided in description)

I am trying to make this code work, and have tried many things (some of which I also found in StackOverflow), but nothing works. When I click on "Send Message" (submit button to send the contact info), absolutely nothing happens.
HTML:
<!-- CONTACT FORM -->
<form method="post" class="wow fadeInUp" id="contact-form">
<!-- IF MAIL SENT SUCCESSFUL -->
<h6 class="text-success">Your message has been sent successfully.</h6>
<!-- IF MAIL NOT SENT -->
<h6 class="text-danger">E-mail must be valid and message must be longer than 1 character.</h6>
<div class="col-md-6 col-sm-6">
<input type="text" class="form-control" id="cf-name" name="name" placeholder="Full name">
</div>
<div class="col-md-6 col-sm-6">
<input type="email" class="form-control" id="cf-email" name="email" placeholder="Email address">
</div>
<div class="col-md-12 col-sm-12">
<input type="text" class="form-control" id="cf-subject" name="subject" placeholder="Subject">
<textarea class="form-control" rows="6" id="cf-message" name="message" placeholder="Message"></textarea>
<button type="submit" class="form-control" id="cf-submit" name="submit">Send Message</button>
</div>
</form>
JS:
// CONTACT FORM
$("#contact-form").submit(function (e) {
e.preventDefault();
var name = $("#cf-name").val();
var email = $("#cf-email").val();
var subject = $("#cf-subject").val();
var message = $("#cf-message").val();
var dataString = 'name=' + name + '&email=' + email + '&subject=' + subject + '&message=' + message;
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
if (isValidEmail(email) && (message.length > 1) && (name.length > 1)) {
$.ajax({
type: "POST",
url: "contact.php"
data: dataString,
success: function () {
$('.text-success').fadeIn(1000);
//$('.text-danger').fadeOut(500);
}
});
}
else {
$('.text-danger').fadeIn(1000);
//$('.text-success').fadeOut(500);
}
return false;
});
contact.php:
<?php
if ( isset($_POST['email']) && isset($_POST['name']) && isset($_POST['subject']) &&
isset($_POST['message']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ) {
// detect & prevent header injections
$test = "/(content-type|bcc:|cc:|to:)/i";
foreach ( $_POST as $key => $val ) {
if ( preg_match( $test, $val ) ) {
exit;
}
}
mail( "davidchau#gmail.com", "Contact Form: ". $_POST['name'], $_POST['subject'], $_POST['message'], "From:" . $_POST['email'] );
}
?>
I have the JS script inside the body of the HTML (at the end of the body). Any help is greatly appreciated.

Jquery ajax FormData is always empty

I want to sent some data with ajax to a php file. I created a FormData, and then, i append all the data to it, that i want to send. I dont get any error message in the console.
My problem is, that the formdata is always empty, and the php file is not getting any data also.
The form:
<div class="tab-pane show" id="tab5">
<form id="AllapotForm" class="form-horizontal" method="post" enctype="multipart/form-data">
<table id="products" class="table table-hover">
<thead>
<tr class="tr_bold">
<!--width="33.3%"-->
<td class="left" >Létrehozva</td>
<td class="left" >Állapot</td>
<td class="left" >A megrendelő értesítve email-ben</td>
<td class="left" >Megjegyzés</td>
</tr>
</thead>
<tbody id="allapotok">
<?php
$get_r_allaptok = mysqli_query($kapcs,
"
SELECT
rendeles_allapot.*,
rendeles_allapotok.rendeles_allapotok_nev
FROM rendeles_allapot
LEFT JOIN rendeles_allapotok ON rendeles_allapot.allapot_allapot_id = rendeles_allapotok.rendeles_allapotok_id
WHERE allapot_rendeles_id = '$id' ORDER BY allapot_id ASC
")
or die(mysqli_error($kapcs));
if(mysqli_num_rows($get_r_allaptok) > 0 )
{
while($r_allapot = mysqli_fetch_assoc($get_r_allaptok))
{
if($r_allapot['allapot_notify'] == 0 ) { $ertesitve = "Nem"; }
if($r_allapot['allapot_notify'] == 1 ) { $ertesitve = "Igen"; }
echo '<tr>
<td class="left">'.$r_allapot['allapot_datetime'].'</td>
<td class="left">'.$r_allapot['rendeles_allapotok_nev'].'</td>
<td class="left">'.$ertesitve.'</td>
<td class="left">'.$r_allapot['allapot_comment'].'</td>
</tr>';
}
}
?>
</tbody>
</table>
<img src="<?php echo $host; ?>/images/assets/preloader.gif" id="preloaderImage2" style="display:none" class="img-responsive" style="margin:10px auto;">
<div class="form-group row">
<label class="control-label col-md-2">Állapot:</label>
<div class="col-md-2">
<select name="allapot" id="allapot" class="input input-select form-control">
<?php
$check_allapot = mysqli_query($kapcs, "SELECT allapot_allapot_id FROM rendeles_allapot WHERE allapot_rendeles_id = '$id' ORDER BY allapot_id DESC LIMIT 1");
if(mysqli_num_rows($check_allapot) > 0 )
{
$allapot_fetch = mysqli_fetch_assoc($check_allapot);
$ertek = $allapot_fetch['allapot_allapot_id'];
}
else
{
$ertek = intval($a['status']);
}
$get_allapotok = mysqli_query($kapcs, "SELECT rendeles_allapotok_id, rendeles_allapotok_nev FROM rendeles_allapotok WHERE rendeles_allapotok_status = 1 ORDER BY rendeles_allapotok_nev ASC");
if(mysqli_num_rows($get_allapotok) > 0 )
{
while($allapot = mysqli_fetch_assoc($get_allapotok))
{
$selected = $ertek == $allapot['rendeles_allapotok_id'] ? ' selected="selected"':'';
echo '<option ' . $selected . ' value="' . $allapot['rendeles_allapotok_id'] . '">' . $allapot['rendeles_allapotok_nev'] . '</option>'."\n";
}
}
?>
</select>
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Megrendelő értesítése email-ben:</label>
<div class="col-md-2">
<input type="checkbox" name="notify" id="notify" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Megjegyzés hozzáadása az email-hez:<span class="help">Amennyiben ezt bepipálja, a megjegyzés az ügyfélnek kiküldött üzenetbe is bele fog kerülni.</span></label>
<div class="col-md-2">
<input type="checkbox" name="add_text" id="add_text" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Fájl csatolása az email-hez:</label>
<div class="col-md-2">
<input type="file" name="file" id="file" class="form-control" />
</div>
</div>
<div class="form-group row">
<label class="control-label col-md-2">Megjegyzés:</label>
<div class="col-md-8">
<textarea name="comment" id="comment" style="width:100%;height:200px;"></textarea>
<div style="margin-top: 10px; text-align: center;">
<a class="saveButton btn btn-primary" style="color:#fff" onclick="allapot_modosit();" id="history_button">Állapot módosítása</a>
</div>
</div>
</div>
</form>
</div>
I call this function on a button click event.
function send_data()
{
var html;
var RendelesID = <?php echo $id; ?>;
var RendelesUserEmail = "<?php echo html($a['email']); ?>";
var RendelesUserName = "<?php echo html($a['nev']); ?>";
var webshopEmail = "<?php echo $webshopEmail; ?>";
var webshopName = "<?php echo $webshopName; ?>";
var Allapot = $( "#allapot option:selected" ).val();
var Comment = CKEDITOR.instances['comment'].getData();
if($("#notify").is(':checked')){var Notify = 1;}else{var Notify = 0;}
if($("#add_text").is(':checked')){var AddToEmail = 1;}else{var AddToEmail = 0;}
var formData = new FormData($('#AllapotForm')[0]);
formData.append('fileName', $('#file')[0].files[0]);
formData.append(RendelesID, RendelesID);
formData.append(RendelesUserEmail, RendelesUserEmail);
formData.append(RendelesUserName, RendelesUserName);
formData.append(webshopEmail, webshopEmail);
formData.append(webshopName, webshopName);
formData.append(Allapot, Allapot);
formData.append(Comment, Comment);
formData.append(Notify, Notify);
formData.append(AddToEmail, AddToEmail);
console.log(formData);
$.ajax({
type: 'POST',
cache: false,
url: 'files/update_rendeles_allapot.php',
//dataType: 'html',
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: { formData:formData },
beforeSend: function(){
$('#preloaderImage2').show();
},
success: function(data)
{
alert(data);
},
complete: function(){
$('#preloaderImage2').hide();
},
error: function (e) {
alert(e.responseText);
console.log(e);
}
});
}
data: { formData:formData },
You need to pass the form data object itself, not a plain object.
data: formData
Have you already seen this?
FormData created from an existing form seems empty when I log it
If yes try to check your network look to the Network then take a look at your request.
You can also try to check your API via Postman if it's working properly.

Send data-attribute ID in JS to PHP on same index page using ajax?

I am not sure how to word this title. Feel free to edit it.
Intro I am doing a datatables.net library server-side table using JSON and PHP. I am basically done except for the edit form.
My first problem was solved. I had a while loop instead of an if statement.
My second problem is now going to be transferring this Javascript code near before the AJAX call:
var edit_id = $('#example').DataTable().row(id).data();
var edit_id = edit_id[0];
to here which is php:
$edit_id = $_POST['edit_id'];
They are both on the same page, index.php so I do not think I can use ajax for this.
Index.php
<script type="text/javascript">
$(document).on('click', '.edit_btn', function() {
var id = $(this).attr("id").match(/\d+/)[0];
var edit_id = $('#example').DataTable().row(id).data();
var edit_id = edit_id[0];
$("#form2").show();
//console.log(edit_id[0]);
$.ajax({
type: 'POST',
url: 'edit.php',
data: {
edit_id: edit_id,
first_name: $("#edit2").val(),
last_name: $("#edit3").val(),
position: $("#edit4").val(),
updated: $("#edit5").val(),
},
success: function(data) {
alert(data);
if (data == 'EDIT_OK') {
alert("success");
} else {
// alert('something wrong');
}
}
})
});
</script>
<?php
$sql="select * from employees WHERE id=$edit_id";
$run_sql=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($run_sql)){
$per_id=$row[0];
$per_first=$row[1];
$per_last=$row[2];
$per_position=$row[3];
//$per_date=$row[4];
$per_updated=$row[5];
?>
<form id="form2" class="form-horizontal">
<label class="col-sm-4 control-label" for="txtid">ID</label>
<input id="edit1" type="text" class="form-control" name="txtid" value="<?php echo $per_id;?>" readonly>
<div class="form-group">
<label class="col-sm-4 control-label" id="edit2" for="txtname">First Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="txtname" name="txtname" value="<?php echo $per_first;?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="txtsalary">Last Name</label>
<div class="col-sm-6">
<input type="number" class="form-control" id="edit3" name="txtsalary" value="<?php echo $per_last;?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="txtage">Position</label>
<div class="col-sm-6">
<input type="number" class="form-control" id="edit4" name="txtage" value="<?php echo $per_position;?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="txtage">Updated</label>
<div class="col-sm-6">
<input type="number" class="form-control" id="edit5" name="txtage" value="<?php echo $per_updated;?>">
</div>
<button type="button" class="close" value="Cancel" data-dismiss="modal">×</button>
<button type="button" class="update" value="Update"></button>
</form>
edit.php
$edit_id = $_POST['edit_id'];
$stmt = $conn->prepare("UPDATE employees SET first_name=?, last_name=?, position=?, updated=? WHERE id=?");
$stmt->bind_param('ssssi', $_POST['first_name'], $_POST['last_name'], $_POST['position'], $_POST['updated'], $_POST['edit_id']);
$confirmUpdate = $stmt->execute();
if($confirmUpdate) {
echo "EDIT_OK";
}else {
trigger_error($conn->error, E_USER_ERROR);
return;
}
?>
I eventually figured it out:
<script type="text/javascript">
$(document).on('click','.edit_btn',function (){
var id = $(this).attr("id").match(/\d+/)[0];
var edit_id = $('#example').DataTable().row( id ).data();
var edit_id = edit_id[0];
alert(edit_id);
$.ajax({
url: 'index.php',
data: { edit_id : edit_id },
contentType: 'application/json; charset=utf-8',
success: function(result) {
//alert(result);
}
});
});
</script>

Custom AJAX form not working async

I have a contact from that uses PHP mailer that I have integrated into my Wordpress blog. The script sends emails no problem - the issue is that it does not work async so once the form is submitted I am taken to another page with the following text on it: {"message":"Your message was successfully submitted from PHP."}. The script works as expected when used outside of wordpress - I have no idea whats going on.
PHP
<?php
/**
* Sets error header and json error message response.
*
* #param String $messsage error message of response
* #return void
*/
function errorResponse ($messsage) {
header('HTTP/1.1 500 Internal Server Error');
die(json_encode(array('message' => $messsage)));
}
/**
* Pulls posted values for all fields in $fields_req array.
* If a required field does not have a value, an error response is given.
*/
function constructMessageBody () {
$fields_req = array("name" => true, "description" => true, "email" => true, "number" => true);
$message_body = "";
foreach ($fields_req as $name => $required) {
$postedValue = $_POST[$name];
if ($required && empty($postedValue)) {
errorResponse("$name is empty.");
} else {
$message_body .= ucfirst($name) . ": " . $postedValue . "\n";
}
}
return $message_body;
}
//header('Content-type: application/json');
//attempt to send email
$messageBody = constructMessageBody();
require 'php_mailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->CharSet = 'UTF-8';
$mail->setFrom($_POST['email'], $_POST['name']);
$mail->addAddress("example#example.com");
$mail->Subject = $_POST['name'];
$mail->Body = $messageBody;
//try to send the message
if($mail->send()) {
echo json_encode(array('message' => 'Your message was successfully submitted from PHP.'));
} else {
errorResponse('An expected error occured while attempting to send the email: ' . $mail->ErrorInfo);
}
?>
(function($) {
$('#form').on('submit', function(){
event.preventDefault();
var contactFormUtils = {
clearForm: function () {
grecaptcha.reset();
},
addAjaxMessage: function(msg, isError) {
$("#feedbackSubmit").append('<div id="emailAlert" class="alert alert-' + (isError ? 'danger' : 'success') + '" style="margin-top: 5px;">' + $('<div/>').text(msg).html() + '</div>');
}
};
$('#submit-email').prop('disabled', true).html("sending");
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(data) {
console.log('success');
$('#form').fadeOut(400)
contactFormUtils.addAjaxMessage(data.message, false);
contactFormUtils.clearForm();
},
error: function(response) {
console.log('error');
contactFormUtils.addAjaxMessage(response.responseJSON.message, true);
$('#submit-report').prop('disabled', false).html("Send message");
contactFormUtils.clearForm();
},
complete: function() {
console.log('complete');
}
});
return false;
});
})( jQuery );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-8 site-block">
<form id="form" method="post" class="form-horizontal ajax" action="<?php echo get_template_directory_uri(); ?>/assets/php/process-contact.php" data-toggle="validator">
<div class="form-group">
<label for="inputName" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input name="name" type="text" class="form-control" id="inputName" placeholder="Enter your full name and title here" required>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Phone</label>
<div class="col-sm-10">
<input name="number" type="number" class="form-control" id="inputEmail3" placeholder="Enter your preferred telephone number here" required>
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input name="email" type="email" class="form-control" id="inputEmail" placeholder="Enter your preferred email address here" required>
</div>
</div>
<div class="form-group">
<label for="inputMessage" class="col-sm-2 control-label">Message</label>
<div class="col-sm-10">
<textarea name="description" class="form-control" id="inputMessage" placeholder="Type your message here" rows="3"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button id="submit-email" name="submit" type="submit" class="btn btn-danger">Submit</button>
</div>
</div>
</form>
<div id="feedbackSubmit"></div>
</div>
change
jQuery('#form').on('submit', function(){
to
jQuery('.ajax').on('submit', function(event){
and replace ALL $ with jQuery
and
wrap your code in document ready function
jQuery(function(){});

user profile update via ajax

hi guys im trying to update user details via ajax but its not updating my users table and just stop executing when possessing... appear here is my code please help if possible
edit_profile.php
<?php
if(isset($_POST["la"])){
$firstname = strip_tags(preg_replace('#[^a-z0-9]#i', '', $_POST['fi']));
$lastname = strip_tags(preg_replace('#[^a-z]#', '', $_POST['la']));
$age = strip_tags(preg_replace('#[0-9]#', '', $_POST['ag']));
$gender = strip_tags(preg_replace('#[^a-z]#', '', $_POST['g']));
// FORM DATA ERROR HANDLING
if($gender == "" || $firsname == "" || $lastname == "" || $age == ""){
echo "some account info is empty.";
exit();
}else{
$sql = "UPDATE users SET gender='$gender', age='$age', lastname='$lastname, firstname='$firstname' WHERE username='$log_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
echo "account_success";
exit();
}
}
?>
ajax and js
<script type="text/javascript" language="javascript">
function _(x){
return document.getElementById(x);
}
function toggleElement(x){
var x = _(x);
if(x.style.display == 'block'){
x.style.display = 'none';
}else{
x.style.display = 'block';
}
}
function restrict(elem){
var tf = _(elem);
var rx = new RegExp;
if(elem == "firstname"){
rx = /[^a-z0-9]/gi;
} else if(elem == "lastname"){
rx = /[^a-z0-9]/gi;
}
tf.value = tf.value.replace(rx, "");
}
function emptyElement(x){
_(x).innerHTML = "";
}
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
function update_profile() {
var fi = _("firstname").value;
var la = _("lastname").value;
var g = _("gender").value;
var ag = _("age").value;
var status2 = _("status_profile");
if(fi == "" || la == "" || ag == "" || g == ""){
status2.innerHTML = "Fill out all of the form data";
status2.style.color = "red";
}else {
_("profilebtn").style.display = "none";
status2.innerHTML = 'processing ...';
var ajax = ajaxObj("POST", "edit_profile.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "account_success"){
_("profilebtn").style.display = "block";
}
}
}
ajax.send("&fi="+fi+"&la="+la+"&g="+g+"&ag="+ag);
}
}
</script>
the html
<div class="row profile-classic">
<div class="col-md-12 m-t-20">
<form name="updateform" id="updateform" onsubmit="return false;">
<div id="profile_form" class="panel">
<div class="panel-title line">
<div class="caption"><i class="fa fa-phone c-gray m-r-10"></i>ACCOUNT</div>
</div>
<div class="panel-body">
<div class="row">
<div class="control-label c-gray col-md-3">Username:</div>
<div class="col-md-6">
<input type="text" class="form-control" value="<?php echo $uname; ?>" disabled="disabled">
</div>
</div><br />
<div class="row">
<div class="control-label c-gray col-md-3">Firstname: *</div>
<div class="col-md-6">
<input type="text" onfocus="emptyElement('status_profile')" class="form-control" id="firstname" contenteditable="true" value="<?php echo $firstname; ?>">
</div>
</div><br />
<div class="row">
<div class="control-label c-gray col-md-3">Lastname: *</div>
<div class="col-md-6">
<input type="text" onfocus="emptyElement('status_profile')" class="form-control" id="lastname" placeholder="your lastname" value="<?php echo $lastname; ?>" >
</div>
</div><br />
<div class="row">
<div class="control-label c-gray col-md-3">Age: *</div>
<div class="col-md-6">
<input type="text" onfocus="emptyElement('status_profile')" class="form-control" id="age" value="<?php echo $age; ?>">
</div>
</div><br />
<div class="row">
<div class="col-md-6">
<select class="form-control" onfocus="emptyElement('status_profile')" id="gender" class="form-control">
<option value="<?php echo $gender; ?>"><?php echo $sex; ?></option>
<option value="m">Male</option>
<option value="f">Female</option>
</select>
</div>
<button id="profilebtn" onclick="update_profile()" class="btn btn-sm btn-default"><i class="fa fa-floppy-o"></i> Save</button><span id="status_profile"></span>
</div><br />
</div>
</div></form>
</div></div>
You can use mysqli_error($db_conx) to determine what the error is... just have your javascript display it nicely for you.
But also - the variable in your WHERE clause ( $log_username ) is undefined.

Categories