Convert post-back to PHP via json to Ajax post - javascript

I am trying to integrate a Codeigniter application into Wordpress through a plugin. The codeigniter program is having difficulty in the control at this point when the customer confirms the data of a new appointment.
VIEW
<div id="wizard-frame-4" class="wizard-frame" style="display:none;">
<div class="frame-container">
<h3 class="frame-title"><?php echo $this->lang->line('step_four_title'); ?></h3>
<div class="frame-content row">
<div id="appointment-details" class="col-md-6"></div>
<div id="customer-details" class="col-md-6"></div>
</div>
</div>
<div class="command-buttons">
<button type="button" id="button-back-4" class="btn button-back"
data-step_index="4"><i class="icon-backward"></i>
<?php echo $this->lang->line('back'); ?>
</button>
<form id="book-appointment-form" style="display:inline-block" method="post">
<button id="book-appointment-submit" type="button" value="saveAppointment" name="submit1"
class="btn btn-success" onclick = "this.style.visibility='hidden', loading.style.visibility='visible'">
<i class="icon-ok icon-white"></i>
<?php
echo (!$manage_mode) ? $this->lang->line('confirm')
: $this->lang->line('update');
?>
</button>
<input type="hidden" name="csrfToken" />
<input type="hidden" name="post_data" />
</form>
</div>
</div>
JS:
$('#book-appointment-submit').click(function(event) {
var formData = jQuery.parseJSON($('input[name="post_data"]').val());
var postData = {
'csrfToken': GlobalVariables.csrfToken,
'id_users_provider': formData['appointment']['id_users_provider'],
'id_services': formData['appointment']['id_services'],
'start_datetime': formData['appointment']['start_datetime'],
};
if (GlobalVariables.manageMode) {
postData.exclude_appointment_id = GlobalVariables.appointmentData.id;
}
var postUrl = GlobalVariables.baseUrl + '/index.php/appointments/ajax_check_datetime_availability';
$.post(postUrl, postData, function(response) {
////////////////////////////////////////////////////////////////////////
console.log('Check Date/Time Availability Post Response :', response);
////////////////////////////////////////////////////////////////////////
if (response.exceptions) {
response.exceptions = GeneralFunctions.parseExceptions(response.exceptions);
GeneralFunctions.displayMessageBox('Unexpected Issues', 'Unfortunately '
+ 'the check appointment time availability could not be completed. '
+ 'The following issues occurred:');
$('#message_box').append(GeneralFunctions.exceptionsToHtml(response.exceptions));
return false;
}
if (response === true) {
$('#book-appointment-form').submit();
} else {
GeneralFunctions.displayMessageBox('Appointment Hour Taken', 'Unfortunately '
+ 'the selected appointment hour is not available anymore. Please select '
+ 'another hour.');
FrontendBook.getAvailableHours($('#select-date').val());
alert('#select-date');
}
}, 'json');
});
CONTROLLER:
if($this->input->post('submit2'))
{
$post_waiting = json_decode($_POST['post_waiting'], true);
$waitinglist = $post_waiting['appointment'];
$this->load->model('appointments_model');
$this->appointments_model->waitinglist_to_db($waitinglist);
$this->load->view('appointments/waiting_success');//return to book view
} else {
try {
$post_data = json_decode($_POST['post_data'], true);
$appointment = $post_data['appointment'];
$customer = $post_data['customer'];
if ($this->customers_model->exists($customer))
$customer['id'] = $this->customers_model->find_record_id($customer);
$customer_id = $this->customers_model->add($customer);
$appointment['id_users_customer'] = $customer_id;
$appointment['id'] = $this->appointments_model->add($appointment);
$appointment['hash'] = $this->appointments_model->get_value('hash', $appointment['id']);
$provider = $this->providers_model->get_row($appointment['id_users_provider']);
$service = $this->services_model->get_row($appointment['id_services']);
$company_settings = array(
'company_name' => $this->settings_model->get_setting('company_name'),
'company_link' => $this->settings_model->get_setting('company_link'),
'company_email' => $this->settings_model->get_setting('company_email')
);
It returns Customers_Model->exists(NULL) and says that customers email was not provided. This is all wrong and does not happen outside the frame. It appears that I cannot postback when the application is run within the wordpress page and shortcode. So, I believe I need to do an Ajax post instead. What would that look like in this case? Would it require major surgery on the code?

As I worked on this I narrowed down my question little by little and posted the solution here:
AJAX submit and 500 server error

Related

I am Having Problems Updating My MySQL table value From my Modal form Sing PHP

I created a modal form (that pops up upon a link click, i.e trigger()). This is the HTML code:
<div class="modalbg">
<div class="modalPopup">
<form action="samepage.php" class="formContainer" method="post">
<h2>Change Desk Number</h2>
<label for="studentid">
<strong></strong>
</label>
<input type="password" placeholder="Your KEY" name="studentid" required/>
<label id="status" style="color:red;"></label>
<button type="submit" class="btn" onclick="return verify()">Upgrade</button>
<button type="button" class="btn cancel" onclick="closeForm()">Close</button>
</form>
</div>
</div>
The JavaScript that controls this modal is:
function trigger(){
document.getElementById("modalPopup").style.display = "block";
}
function closeForm() {
document.getElementById("modalPopup").style.display = "none";
}
function verify() {
var studentid = document.getElementById("studentid").value;
if (studentid != dbstudentid || !studentid){
document.getElementById("status").innerHTML="Invalid Student ID!";
function trigger(event) { event.preventDefault(); }
return false;
}
else{
document.getElementById("modalPopup").submit();
}
}
Everything works at this point (i.e it pops up whenever I click the link and whenever I knowingly try to enter a wrong studentid, it returns the "Invalid student ID" on the "status" label. (Note: I had already saved the session's student ID in the variable dbstudentid using:
var dbstudentid = <?php echo json_encode($dbstudenid);?>;
My problem however comes from when I try to execute the PHP on the same page.
Whenever I insert the PHP code into the modalbg div or modalPopup div inside it, the entire modal refuses to pop, let alone submit.
This is the PHP code I used (it should be noted that at the beginning of the page, I had already used include(configure-db.php) and session_start() ) :
<?php
if(isset($_POST['studentid'])){
$studentid = $_POST['studentid'];
$desk = 1;
$deskstatus ="";
$select = "UPDATE users SET deskNo = '$desk' WHERE name='$SESSION';
}
if (mysqli_query($MyConn, $select)) {
$deskstatus = "Desk changed successfully!";
} else {
$deskstatus = "Error";
} return $deskstatus;
?>
I have tried everything, the modal just refuses to come every time, let alone successfully make the Desk Update on my Database. to make things worse, whenever I refresh the page, the modal which I set to display:none; by default on CSS suddenly starts showing. But whenever I remove the PHP code, it returns to normal.
Do I need to make the action execute in a separate page? If yes, please how?
Else, how please?
I world highly suggest you think about using AJAX to handle this probolem.
let's clear up things.
you can write var dbstudentid = '<?= $dbstudenid ?>'; instead of var dbstudentid = <?php echo json_encode($dbstudenid);?>; this will give you freedom of JS native datatype.
you need to send this form request through ajax and recive output there.
Change the php code else part to like this
else { $deskstatus = "Error: " . mysqli_error($MyConn); }
Now when there is a actual problem on code you will know what was the problem. and it will not break you interface.
4. Create seperate file that handle this form request.
5. Here is code snippet of plaing JS AJAX implementation
let post = JSON.stringify(postObj)
const url = "https://jsonplaceholder.typicode.com/posts"
let xhr = new XMLHttpRequest()
xhr.open('POST', url, true)
xhr.setRequestHeader('Content-type', 'application/json; charset=UTF-8')
xhr.send(post);
xhr.onload = function () {
if(xhr.status === 201) {
console.log("Post successfully created!");
let AlertDiv = document.querySelector('#alert');
AlertDiv.innerHTML = xhr.response;
}
}

How to disable form submit button if the username already exits in database ? (by js, ajax, php(laravel))

I am new js learner, and I am trying to build a form. in the form I want to check if the input username is already taken or exists and I have done this by laravel controller and lil JS code but I want to HIDE the submit button if the input username is already exists in the database. so how do I do this? please anybody
This is my JS code
<script type="">
$function get_user_name(id, result) {
var id = $(id).val();
$.get("<?php echo e(url('home/get_user_name')) ?>/" + id,
function (data) {
$(result).html(data);
});
}
</script>
Controller =>
**and
controller =**
public function get_user_name()
{
$username = request()->segment(3);
$user = DB::table('users')
->select('username')
->where('username', $username)
->count();
$nam = "username already taken";
if ($user >0) {
return $nam;
}else{
}
}
html form =>
<span id="username_rs" style="color: green; font-weight: bold"></span>//showing the message here,
<input id="username" name="username"
onchange="checkem('#username', '#username_rs')" >
<button type="submit" class="btn btn-primary">
{{ __('Register') }}
</button>
route =>
Route::get('/home/get_user_name/{username}', 'HomeController#get_user_name')->name('checkun');
And url look like =>
http://localhost/home/get_user_name/{input username}
My code is showing if the username is taken or not, but I want to hide the submit button if the username is taken or exists in the database.
You can return like this:
**and
controller =**
public function get_user_name()
{
$username = request()->segment(3);
$user = DB::table('users')
->select('username')
->where('username', $username)
->count();
if ($user >0) {
return Response::json(array("found"=>"yes", "message"=>"Username is already taken"));
}else{
return Response::json(array("found"=>"no", "message"=>"Something happens wrong"));
}
}
Your Script code looks like:
$function get_user_name(id, result) {
var id = $(id).val();
$.get("<?php echo e(url('home/get_user_name')) ?>/" + id,
function (data) {
if (data.found == 'yes)
{
$("#submit_btn").css("display","none")
}
});
}
HTML code looks like:
<span id="username_rs" style="color: green; font-weight: bold"></span>//showing the message here,
<input id="username" name="username"
onchange="checkem('#username', '#username_rs')" >
<button type="submit" id="submit_btn" class="btn btn-primary">
{{ __('Register') }}
</button>
I would do it like this:
function get_user_name(id, result) {
var id = $(id).val();
$.get("<?php echo e(url('home/get_user_name')) ?>/" + id,
function (data) {
//check if we get the message: username already taken
if(data) {
$(result).html(data);
$('input[type=submit]', this).attr('disabled', 'disabled'); //disable button
$('form').bind('submit',function(e){e.preventDefault();}); //disable form
} else {
$('input[type=submit]', this).removeAttr('disabled', 'disabled'); //enable button
$('form').unbind('submit'); //enable form
}
});
}

JS hide/remove dynamically div with same class name

To make it short, I have a table with multiple rows. Beneath each main row I have a hidden row, that when pressed, presents an input to upload files and a button to make the upload.
What I am trying to make is show a .gif while its processing the images and removed the .gif when its done so that the user is aware that something is actually happening. Each "upload" row has its own .gif, so when clicking on the upload button the .gif should change from display: none to visible/inline-block. A fetch is done to upload the files and if successful it should remove the .gif, the only problem is that the js does not remember the rest first .gifs.
Ill attach some images and then the js code.
Here you can see, if you press on the + sign, it shows the row beneath it, while row with ID 4 and 5 are hidden because the button was not pressed.
Here is during the upload process, what happens when I click on Upload, the .gif is added.
In this third one, all 3 were already done since I have an alert as a confirmation for debug purpose. Though you can see that only one disappeared and the rest still have the .gif visible. What I want is that as soon as the response from the fetch is ok, it should remove the respective .gif, though I have no clue on how to tackle this or even how to start. I thought maybe about an array that stores which ones were received through a data-* but then it did not make sense since i would need to send response from the server with that number.
The code:
function uploadPhotos(url, queryCollection){
this.url = url;
this.queryCollection = queryCollection;
this.upload = function(){
queryCollection.forEach(function(el){
el.addEventListener('submit', e => {
loadingGifEl = el.nextElementSibling;
button = el.closest('form').querySelector('input[type=submit]');
e.preventDefault();
if (loadingGifEl.classList.contains('hidden')) {
loadingGifEl.classList.remove('hidden');
button.classList.add('hidden');
}
const files = el.querySelector('[type=file]').files;
// const contentID = el.closest('tr').getAttribute('data-content-id');
if(el.closest('tr') == null){
var contentID = 0;
}else{
var contentID = el.closest('tr').getAttribute('data-content-id');
}
let formData = new FormData();
for (let i = 0; i < files.length; i++) {
let file = files[i];
formData.append('image_field[]', file, contentID + '___' + file.name);
}
/* Original working */
fetch(url, {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(data => {
if (this.button.classList.contains('hidden')) {
this.loadingGifEl.classList.add('hidden');
this.button.classList.remove('hidden');
}
if(Number.isInteger(parseInt(data)) != true)
alert('Erro ao inserir na base de dados');
console.log(data);
})
.catch(function(error){
if (this.button.classList.contains('hidden')) {
this.loadingGifEl.classList.add('hidden');
this.button.classList.remove('hidden');
}
alert('Erro em fazer upload');
console.log(error);
});
});
});
}
}
How HTML is being built:
<table class="table table-hover" id="city-table">
<thead>
<th>ID</th>
<th>Nome(PT)</th>
<th>Descrição(PT)</th>
<th>Popular</th>
<th>Adicionado</th>
<th>Galeria</th>
<th>Ação</th>
</thead>
<tbody>
<?php
$resp = $city->fetchAll();
if(!empty($resp)){
for($cityCounter = 0; $cityCounter < count($resp); $cityCounter++){
switch($resp[$cityCounter]->isPopular){
case 0: $isPopular = 'Não';
break;
case 1: $isPopular = 'Sim';
break;
};
echo '<tr data-content-type="city" data-content-id="'.$resp[$cityCounter]->city_link_ID.'">';
echo '<td>'.$resp[$cityCounter]->city_link_ID.'</td>';
echo '<td>'.$resp[$cityCounter]->nameTranslated.'</td>';
echo '<td>'.$resp[$cityCounter]->descriptionTranslated.'</td>';
echo '<td>'.$isPopular.'</td>';
echo '<td>'.$resp[$cityCounter]->dateCreated.'</td>';
echo '<td>
<a class="btn btn-info btn-xs" id="show-gallery" href="#collapseGallery-'.$resp[$cityCounter]->city_link_ID.'" data-toggle="collapse">
<i class="lnr lnr-plus-circle"></i>
</a>
</td>';
echo '<td>
<span class="lnr lnr-pencil"></span>
<button class="btn btn-danger btn-xs pull-right" id="delete-city"><span class="lnr lnr-trash"></span></button>
</td></tr>';
echo'
<tr data-content-type="city" data-content-id="'.$resp[$cityCounter]->city_link_ID.'" id="collapseGallery-'.$resp[$cityCounter]->city_link_ID.'" class="collapse">
<td colspan="14" class="bg-info">
<form enctype="multipart/form-data" method="post" class="file-upload" id="'.$resp[$cityCounter]->city_link_ID.'">
<input type="file" class="btn btn-info pull-left" size="100" name="image_field[]" multiple="multiple">
<input type="submit" class="btn btn-primary pull-right" name="Submit" value="Upload">
</form>
<div class="loading-gif-'.$resp[$cityCounter]->city_link_ID.' hidden">
<img style="margin-left: 25%" src="assets/img/processing.gif" alt="A carregar"/>
</div>
</td>
</tr>
';
}
}
?>
</tbody>
</table>
The use of loadingGifEl vs this. loadingGifEl seems suspicious. If I understand your question correctly, you want to keep track of the actual gif you've shown so you can hide it again when fetch is done. The below should work, although not tested. If this is not what you want let me know.
function uploadPhotos(url, queryCollection){
this.url = url;
this.queryCollection = queryCollection;
this.upload = function(){
queryCollection.forEach(function(el){
el.addEventListener('submit', e => {
var loadingGifEl = el.nextElementSibling;
var button = el.closest('form').querySelector('input[type=submit]');
e.preventDefault();
if (loadingGifEl.classList.contains('hidden')) {
loadingGifEl.classList.remove('hidden');
button.classList.add('hidden');
}
const files = el.querySelector('[type=file]').files;
// const contentID = el.closest('tr').getAttribute('data-content-id');
if(el.closest('tr') == null){
var contentID = 0;
}else{
var contentID = el.closest('tr').getAttribute('data-content-id');
}
let formData = new FormData();
for (let i = 0; i < files.length; i++) {
let file = files[i];
formData.append('image_field[]', file, contentID + '___' + file.name);
}
/* Original working */
fetch(url, {
method: 'POST',
body: formData
})
.then(response => response.text())
.then(data => {
if (button.classList.contains('hidden')) {
loadingGifEl.classList.add('hidden');
button.classList.remove('hidden');
}
if(Number.isInteger(parseInt(data)) != true)
alert('Erro ao inserir na base de dados');
console.log(data);
})
.catch(function(error){
if (button.classList.contains('hidden')) {
loadingGifEl.classList.add('hidden');
button.classList.remove('hidden');
}
alert('Erro em fazer upload');
console.log(error);
});
});
});
}
}

cannot access request array after ajax forwarding

So i'm currently working on a website that loads a container once a button is clicked and the content is loaded via an AJAX function. The problem is at the PHP side, I cannot access the variable i pass through the AJAX function through my REQUEST array. I'm not sure if it is a problem with BIG TREE CMS I'm using.But i really would appreciate some help.
This is the button i use to call the function:
<div class="button-holder">
<button class="project-btn" data-id='<?=$id?>' onclick="getProject(<?=$id?>)">
<h3 class="btn-text">View Project</h3>
<h3 class="hide-reveal">→</h3>
<h3 class="button-pike"></h3>
</button>
So this is my ajax function:
function getProject(id)
{
var ajaxUrl='ajax/singleProject?id=' + id;
$.ajax(ajaxUrl, {
async: true, complete: getProjectComplete
});
}
function getProjectComplete(xhr, status) {
if (status == false)
{
return;
}
var obj = $.parseJSON(xhr.responseText);
$('.pro-heading').html(obj.company);
$('.pro-subtext').html(obj.project_heading + '(' + obj.start_date + ')');
$('.pro-image').attr('src', obj.project_image);
$('.pro-brief').html(obj.project_brief);
$('.pro-details').html(obj.project_details);
}
and this is my PHP function:
<?php
if (isset($_REQUEST['id']))
$id = $_REQUEST['id'];
$obj = new Projects();
$single = $obj->get($id);
echo json_encode($single);
?>

How to retrieve data from sql query and use it in my javascript function

I have a form like this (which is inside a CodeIgniter View page):
<form action="<?php echo base_url(); ?>index.php/admin_logins/regis2" onsubmit="return checkTime();" method="post">
<fieldset>
<legend id="registration_legend">Registration</legend>
<div>
<label id= "std_id_add_label">Student ID:</label>
<input type="text" name="std_id" id = "student_id_add" placeholder="Student ID" required="1"/>
</div>
<br>
<div>
<label id= "is_member_add_label">Member?</label>
<input type="checkbox" name ="is_member_checkbox" class ="membercheck" checked="checked" value="1" onchange="valueChanged()"/>
</div>
<br>
<div id = "privilege_code">
<label id= "privilege_code_add_label">Privilege Code:</label>
<input type="text" name="privilege_code" id = "privilege_code_add" placeholder='0'/>
</div>
</form>
And I have a Javascript like this:
<script>
function checkTime()
{
var today = new Date();
var hour = today.getHours();
if(hour < '17')
{
return true;
}
else
{
alert("Sorry, registrations are closed after 5 pm.");
location.href = '<?php echo base_url(); ?>index.php/admin_logins/registration';
return false;
}
}
</script>
All I want to do is something like this:
<script>
function checkTime()
{
var today = new Date();
var hour = today.getHours();
//alert(hour);
if(hour < '17')
{
//well I want something like the following
query = select count(std_id) from registration where std_id = document.getElementById("student_id_add") and date = today
if(query > 1)
{
alert("You are already registered.");
return false;
}
else
{
return true;
}
}
//don't worry about the above syntax, I know it's wrong and I'm looking for the right stuff
else
{
alert("Sorry, registrations are closed after 5 pm.");
location.href = '<?php echo base_url(); ?>index.php/admin_logins/registration' ;
return false;
}
}
</script>
If count of std_id is more than one on submit, means if there is an existing std_id, then data will not be submitted.
On form submit, data will go to this controller method-
function registration_add
{
if($_POST)
{
date_default_timezone_set('Asia/Dacca');
$rdata['std_id'] = $this->input->post('std_id');
$rdata['entry_date'] = date('Y-m-d');
$rdata['is_member'] = $this->input->post('is_member_checkbox');
$rdata['privilege_code'] = $this->input->post('privilege_code');
$res = $this->registration_model->insert_registration($rdata);
if($res)
{
$this->session->set_flashdata('message','Registration information added successfully');
header('location:'.base_url()."index.php/admin_logins/regis");
}
}
else
{
$this->load->view('admin_logins/registration_add');
}
}
And model method -
public function insert_registration($data)
{
return $this->db->insert('registration', $data);
}
My database is MySQL and my table name is registration, structure as follows:
Columns Data Types
id int PK
std_id varchar(15)
entry_date date
is_member int
privilege_code varchar(12)
I want to know:
What is the correct way to do this? (I heard about using ajax, however, any solution is welcome.)
What is the correct syntax and code placements?
May be its too late, but i think it will help you..
This is just a ajax request.
In the view file
jQuery.ajax({
type : "POST",
url : "<?php echo site_url('route_name'); ?>",
data : {
"key" : value
},
success: function(result,status,xhr){
if(result.length > 0) {
msg = JSON.parse(result);
// do your work here.
},
error: function(xhr,status,error){
alert('Error Occurred.');
}
});
In the controller
// AJAX
function ajax_function()
{
$this->load->model('model_name');
echo json_encode($this->model_name->model_function($this->input->post('key')));
}

Categories