Autocomplete issue in append html - ajax

I'm trying to make autocomplete in appended field.
My codeigniter view file:
<div class="right_col" role="main">
<div class="clearfix"></div>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="x_panel">
<span class="section">Search Product's Info</span>
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="name">Product Name <span class="required">*</span></label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="prosearch" class="form-control col-md-7 col-xs-12" name="prosearch" type="text" placeholder="Search">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
My script:
<script type="text/javascript">
var $ = jQuery.noConflict();
$(function() {
// alert('hello');
$( "#prosearch" ).autocomplete({
source: function( request, response ) {
var t = $('#prosearch').val();
$.ajax({
type: "POST",
url: "<?php echo site_url('sale/search') ?>",
data: { term: request.term },
dataType: 'json',
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.data,
value: item.product_name,
id: item.id
}
}));
}
});
}
})
});
</script>
My Controller method:
public function search(){
$q=$_POST["term"];
#print_r($q); exit;
$query = $this->db->query("SELECT * FROM product WHERE product_name LIKE '".strtoupper($q)."%';");
$data= $query->result_array();
$json = json_encode($data);
echo $json;
}
My output is:
Well i am trying to my search result is under own input like any other autosuggestion.
Any kind of help.

Related

Laravel 8 Dynamic Dependent Input

it's been a while since I stuck in this problem. So I want to make a dynamic selection, when I select a nis (student_id) then the column nama (name) is filled with the student name.
Input form
Output i want
method create
public function create()
{
return view('admin.counseling.create', [
'title' => 'Tambah Bimbingan dan Konseling',
'students' => Student::all()
]);
}
create_blade.php
<form action="/admin/counseling/store" method="post" enctype="multipart/form-data">
#csrf
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Nomor Induk Siswa</label>
<select name="nis" required class="form-control" id="nis">
<option value="0" disabled="true" selected="true">-Pilih-</option>
#foreach($students as $student)
<option value="{{$student->id}}">{{$student->nis}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Nama</label>
<input type="text" class="form-control" name="name" required />
</div>
</div>
</div>
<div class="row">
<div class="col text-right">
<button
type="submit"
class="btn btn-success px-5"
>
Simpan
</button>
</div>
</div>
</div>
</form>
I have watched and read some questions with similar problems, and yet I still didn't get it
UPDATE
My method in my controller
public function find_nis(Request $request)
{
$data = Student::find($request->id); //Counseling::with('student', 'student.student_class')->where('student_id', $request->id)->first();
return response()->json(['view' => view('admin.counseling.create', ['data' => $data])->render()]);
}
My Ajax in create.blade.php
<script type="text/javascript">
$(document).ready(function (){
$(document).on('change','.student_nis',function () {
var student_id = $(this).val();
var a = $(this).parent();
console.log(student_id);
var op="";
$.ajax({
type : 'GET',
url : '{!! URL::to('find_nis') !!}',
data : 'id=' + student_id,
success:function(data){
console.log(data);
a.find('.student_name').val(data.name);
},
error:function(){
}
});
});
});
</script>
My Route
Route::get('/admin/counseling/find_nis', [CounselingController::class, 'find_nis'])->name('find_nis');
this is output in my browser console when i select nis 1212
i think for getting response from DB without refresh page you should use ajax,
post student_id with ajax to Controller get username from DB and return your view like this:
in your blade:
first you must set this meta tag inside of :
<meta name="csrf-token" content="{{ csrf_token() }}">
then config and post your data with ajax like this:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var studentId = $("input[name=student]").val();
$.ajax({
xhrFields: {withCredentials: true},
type:'POST',
url:"{{ route('getStudentInfo') }}",
data:{studentId:studentId},
success:function(data){
$('html').html(data.view);
}
});
</script>
in your Controller inside of getStudentInfo():
$student = DB::table('user')->find($studen_id);
$username = $student->username;
return response()->json(['view' => view('admin.counseling.create', compact('username'))->render()]);
Here the working solutions
*Route
Route::get('/admin/counseling/find_student', [CounselingController::class, 'find_nis'])->name('find_student');
*Controller
public function create()
{
return view('admin.counseling.create', [
'title' => 'Tambah Bimbingan dan Konseling',
'students' => Student::all(),
'problems' => Problem::all()
]);
}
public function find_nis(Request $request)
{
$student = Student::with('student_class')->findOrFail($request->id);
return response()->json($student);
}
*blade
<div class="container-fluid mt--7">
<div class="mt-8">
<div class="dashboard-content">
<div class="row">
<div class="col-12">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="/admin/counseling/store" method="post" enctype="multipart/form-data">
#csrf
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Nomor Induk Siswa</label>
<select name="nis" required class="form-control" id="nis">
<option value="0" disabled="true" selected="true">-Pilih-</option>
#foreach($students as $student)
<option value="{{$student->id}}">{{$student->nis}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Nama</label>
<input type="text" class="form-control" name="student_name" id="student_name" disabled required/>
</div>
<div class="form-group">
<label>Kelas</label>
<input type="text" class="form-control" name="student_class_name" id="student_class" disabled required/>
</div>
<div class="form-group">
<label>Permasalahan</label>
<div class="row">
<div class="col">
#foreach ($problems as $problem)
<div class="form-check">
<input type="checkbox" id="" name="problem_name[]" value="{{ $problem->name }}">
<label class="fs-6 fw-light">{{ $problem->name }}</label>
</div>
#endforeach
</div>
</div>
</div>
<div class="form-group">
<label>Bobot Permasalahan</label>
<select name="priority" required class="form-control" id="nis">
<option value="null" disabled="true" selected="true">-Pilih-</option>
<option value="1">Normal</option>
<option value="3">Penting</option>
<option value="5">Sangat Penting</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col text-right">
<button
type="submit"
class="btn btn-success px-5"
>
Simpan
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
*ajax
<script type="text/javascript">
$(document).ready(function (){
$(document).on('change', '#nis', function() {
var student_id = $(this).val();
var a = $('#student_name').parent();
$.ajax({
type : 'GET',
url : '{{ route('find_student') }}',
data : 'id=' + student_id,
success:function(data){
a.find('#student_name').val(data.name);
},
error:function(){
}
});
});
$(document).on('change', '#nis', function() {
var student_id = $(this).val();
var a = $('#student_class').parent();
$.ajax({
type : 'GET',
url : '{{ route('find_student') }}',
data : 'id=' + student_id,
success:function(data){
a.find('#student_class').val(data.student_class.name);
},
error:function(){
}
});
});
});
</script>

My previously edited data is edited again when I update second data in codeigniter using ajax

I am using codeigniter framework to develop my project. I am also using AJAX to edit the data. When I edit the first data it is being edited correctly but when I am updating the second data without refreshing the browser then previous edited data or current editing data both are updated with new result. Please solve my problem. Thanks in advance.
function editFunction(id)
{
$.ajax({
url: "edit_result/" +id,
data: {id:id},
type: "post",
async: false,
dataType: 'json',
success: function(response){
$('#reg_no').val(response.reg);
$('#total_marks').val(response.tot_marks);
$('#grade').val(response.grade);
},
error: function()
{
alert("error");
}
});
$('#updateBtn').click(function(event){
event.preventDefault();
var grade_id = document.getElementById("grade").value;
var total_id = document.getElementById("total_marks").value;
if(grade_id=='' || total_id=='')
{
$('#updateBtn').prop('disabled',true);
setTimeout(function(){document.getElementById("updateBtn").disabled = false;},2000);
$('.message').html('Please fill all fields').fadeIn().delay(1000).fadeOut('slow');;
}
else
{
$.ajax({
url: "edit_result_valid/" +id,
data: $(this).serialize(),
type: "post",
async: false,
dataType: 'json',
success: function(response){
alert('success');
},
error: function()
{
alert("error");
}
});
}
});
}
I am performing edit operation on modal. Please check also HTML code
<div class="modal fade" id="editModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h2 class="modal-title">Edit Result</h2>
<p class="message" style="color: red;"></p>
</div>
<div class="modal-body">
<form role="form" id="updateForm">
<div class="box-body">
<div class="form-group">
<label for="exampleInputEmail1">Reg No :</label>
<input type="text" class="form-control" id="reg_no" readonly="">
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label>Total Marks :</label>
<input type="number" class="form-control" id="total_marks" placeholder="Enter total marks" onfocus="colorFunction(this)" name="tot_marks">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Grade</label>
<?php
$firstItem[''] = 'Please select one...';
$options = array(
'A++' => 'A++ (90% & above)',
'A+' => 'A+ (80% to 89%)',
'A' => 'A (60% to 79%)',
'B+' => 'B+ (50% to 59%)',
'B' => 'B (40% to 49%)',
);
$options = array_merge($firstItem, $options);
$selected_option = $this->input->post('grade', TRUE);
echo form_dropdown('grade', $options,$selected_option,['class'=>'form-control','id'=>'grade','onfocus'=>'colorFunction(this)']); ?>
</div>
</div>
</div>
</div>
<!-- /.box-body -->
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger pull-left" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-success pull-right" data-dismiss="modal" id="updateBtn">Update</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
I have got an answer of my question. I am using off('click') in code you can see update code below.
$('#updateForm').off('click','#updateBtn').on('click','#updateBtn',function(event){
event.preventDefault();
var grade_id = document.getElementById("grade").value;
var total_id = document.getElementById("total_marks").value;
if(grade_id=='' || total_id=='')
{
$('#updateBtn').prop('disabled',true);
setTimeout(function(){document.getElementById("updateBtn").disabled = false;},2000);
$('.message').html('Please fill all fields').fadeIn().delay(1000).fadeOut('slow');;
}
else
{
$.ajax({
url: "edit_result_valid/" +id,
data: $("#updateForm").serialize(),
type: "post",
async: false,
dataType: 'json',
success: function(response){
if(response=='1')
{
$('.alert-success').show();
$('.alert-success').html('Result Updated Successfully').fadeIn().delay(4000).fadeOut('slow');
$('#example1').DataTable().ajax.reload();s
}
},
error: function()
{
alert("error");
}
});
}
});
play a game at view first. i guess you are not using primary key of db to update. let me explain.
at view:
at one more input element which type is hidden and has value your primary key . assign it an id having value tbl_id example
<input type="hidden" value="<?php echo {variable that has your primary key } ?>" id="tbl_id" >
and at ajax call before you start writing it
var id = $("#tbl_id").val();
when you call controller check you have id available or not
next you are going to call a model to update.
that is where your other all data get update.
when you are going to call model use statement before it
if($id != '') { // $id is what you have shared via ajax call
$this->model_name->update_function($id,$array); // $array is all other fields as per codeigniter need
} else { echo "unable to capture id"; exit; }
and last you update model..
all done by ajax :)

AJAX code not working on iPad only

We've created an event check-in page where nonprofits can add volunteers at an event. The page is working great on all platforms besides iPad. (iPhone Safari is working.)
On iPad, clicking id=add-volunteer button has no effect. Desired behavior is that clicking the button adds the volunteer name to the list of registered volunteers and saves the user info on the backend. (Other backend tasks such as sending an invite email should occur on the backend as well.)
HTML
<form id="form-add" method="post">
<input type="hidden" name="csrfmiddlewaretoken">
<div class="row one-margin-bottom center">
<div id="new-volunteers" class="small-12 medium-8 small-centered columns">
<h6 class="left">Add volunteer</h6>
<div class="row">
<div class="input-right small-6 columns">
<input class="center" id="new-firstname" name="user_firstname" placeholder="First name" type="text" required="">
</div>
<div class="input-right small-6 columns">
<input class="center" id="new-lastname" name="user_lastname" placeholder="Last name" type="text" required="">
</div>
<div class="input-right small-12 medium-12 columns">
<input class="lead center" id="new-email" name="user_email" placeholder="Email address" type="email" required="">
</div>
</div>
<div class="no-margin-top qtr-margin-bottom checkbox center">
<input type="checkbox" name="invite-optin" id="invite-optin" class="custom-checkbox" checked="">
<label for="invite-optin">Invite volunteer to openCurrents</label>
</div>
<a id="add-volunteer" class="half-margin-bottom button round small secondary">
Add volunteer
</a>
</div>
</div>
</form>
<form id="form-checkin" method="post">
<input type="hidden" name="csrfmiddlewaretoken">
<div class="row">
<div class="small-12 medium-8 small-centered columns">
<h6 class="left half-margin-bottom">Registered volunteers</h6>
<div class="row">
<div class="left small-8 columns">
<p class="small-text half-margin-top half-margin-bottom"><strong>Name / Email</strong></p>
</div>
<div class="right small-4 columns">
<p class="small-text half-margin-top half-margin-bottom"><strong>Check in</strong></p>
</div>
</div>
</div>
</div>
<div class="row">
<div id="registered-volunteers" class="small-12 medium-8 small-centered columns">
</div>
</div>
</form>
<div class="row">
<a href="/org-admin/" class="button round small secondary">
Back to org home
</a>
</div>
JS
let onCheckClick = function(event) {
let name = event.target.name;
let elem = $(`#${name}`);
let userid = elem.val();
let isChecked = elem.prop("checked");
$.ajax({
url: "{% url 'openCurrents:event_checkin' event_id %}",
type: 'POST',
data : {
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[1].value,
userid: userid,
checkin: isChecked
},
dataType : "json",
context: document.body
}).done(function( data ){
// console.log('checkin request:');
// console.log(data);
if (isChecked) {
let dt = new Date();
$(`#vol-status-${userid}`).text(`${dt.toLocaleTimeString()}`);
$(`#vol-status-${userid}`).show();
}
else {
$(`#vol-status-${userid}`).text(`${data.responseText} min.`);
}
}).fail(function (data) {
// console.log('checkin error:')
// console.log(data);
elem.prop('checked', false);
$('#live-dashboard-error').slideDown();
});;
};
$(document).ready(function(){
// bind all existing checkbox to checkin
$("input[name^='vol-checkin']").click(onCheckClick);
$("#add-volunteer").click(function(event){
if ($(this).attr('disabled') === 'disabled') {
$('#live-dashboard-checkin-disabled').slideDown();
return;
}
if ($('#new-firstname').val() == '' || $('#new-lastname').val() == '' || $('#new-email').val() == '') {
$('#vol-error').slideDown();
} else if ( !(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test($('#new-email').val() )) ) {
$('#vol-error').slideUp();
$('#email-error').slideDown();
} else {
$('#vol-error').slideUp();
$('#email-error').slideUp();
let new_firstname = $('#new-firstname').val();
let new_lastname = $('#new-lastname').val();
let new_email = $('#new-email').val();
let invite_optin = $('#invite-optin').prop('checked');
let process_signup_url;
let form_data = {
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
user_firstname: new_firstname,
user_lastname: new_lastname,
user_email: new_email.toLowerCase()
};
if (invite_optin) {
process_signup_url = "{% url 'openCurrents:process_signup' endpoint=True verify_email=True %}"
form_data['org_admin_id'] = {{ user.id }};
}
else {
process_signup_url = "{% url 'openCurrents:process_signup' endpoint=True verify_email=False %}"
}
form_data['signup_status'] = 'vol'
$.ajax({
url: process_signup_url,
type: 'POST',
data: form_data,
dataType : "json",
}).done(function( data ) {
// console.log('signup response:')
// console.log(data);
let userid = data;
let form_data = {
csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value,
userid: userid
}
$.ajax({
url: "{% url 'openCurrents:event_register_live' eventid=event.id %}",
type: 'POST',
data: form_data,
dataType : "json",
}).done(function( data ) {
//console.log('register_live response:')
//console.log(data);
// hide any error messages present
$('#vol-exist').slideUp();
$('#live-dashboard-error-register').slideUp();
$('#live-dashboard-error').slideUp();
$('#vol-error').slideUp();
$('#email-error').slideUp();
$('#live-dashboard-not-in-progress').slideUp();
if (data.event_status >= 0) {
$('#registered-volunteers').prepend(`
<div class="row"> \
<div class="left small-9 columns"> \
<p class="half-margin-top"> \
${new_firstname} \
${new_lastname} \
</p> \
</div> \
<div class="right small-3 columns"> \
<input {% if checkin_disabled %}disabled{% endif %} type="checkbox" id="vol-checkin-${userid}" name="vol-checkin-${userid}" value="${userid}" class="hidden checkin-checkbox"/> \
<label class="checkin-checkbox-icon" for="vol-checkin-${userid}"> \
<i class="fa fa-lg fa-check-circle"></i> \
</label> \
</div> \
</div> \
`)
// clear form inputs
$('#new-firstname').val('');
$('#new-lastname').val('');
$('#new-email').val('');
$('#invite-optin').attr("checked", true);
// bind new checkbox to checkin
$(`input[name='vol-checkin-${userid}']`).click(onCheckClick);
if (data.event_status == 1) {
$(`input[name='vol-checkin-${userid}']`).trigger('click')
} else {
$('#live-dashboard-not-in-progress').slideDown();
}
}
else {
$('#new-firstname').val('');
$('#new-lastname').val('');
$('#new-email').val('');
$('#invite-optin').attr("checked", true);
$('#vol-exist').slideDown();
}
}).fail( function (data) {
// console.log('register_live error:')
// console.log(data);
$('#live-dashboard-error').slideDown();
});
}).fail(function (data) {
// console.log('signup error:')
// console.log(data);
$('#live-dashboard-error').slideDown();
});
}
});

Codeigniter form_open_multipart showing 403 Forbidden (CSRF)

I am trying to post data though ajax post but somehow unable to post . am getting 403 forbidden. Fortunately my other ajax posts are submitting properly as they are getting right re-generated token. But in form_open_multipart it's not working.
CI config
$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'my_token';
$config['csrf_cookie_name'] = 'my_cookie';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
form_open is working well, but in the case of multi part it's not working well !!!!
my HTML
<?php $parameter = array('id' => 'frm_id', 'class' => 'form-horizontal'); echo form_open_multipart('controller/save',$parameter) ;?>
<div class="form-body">
<div class="form-group">
<label class="col-md-3 control-label">Name</label>
<div class="col-md-6">
<div class="input-icon">
<i class="fa fa-bell-o"></i>
<input type="text" id="catId" class="form-control " placeholder="Type Something..." name='name' />
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Description</label>
<div class="col-md-6">
<div>
<textarea class="form-control" rows="3" name="description"></textarea>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Image 1</label>
<div class="col-md-6">
<div>
<input type="file" name="thumb_image">
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Image 2</label>
<div class="col-md-6">
<div>
<input type="file" name="banner_image">
</div>
</div>
</div>
</div>
<div class="form-actions">
<div class="row">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn btn-flat green">Submit</button>
<button type="button" class="btn btn-flat grey-salsa">Cancel</button>
</div>
</div>
</div>
<?php echo form_close() ;?>
My JS
<script type="text/javascript">
var frmSave = $('#frm_id');
frmSave.on('submit', function(event){
event.preventDefault();
$form=$(this);
var fd = new FormData($('#frm_id')[0]);
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
dataType: 'json',
data: fd,
contentType: false,
cache: false,
processData: false,
success: function(data){
console.log(data)
}
})
});
</script>
Still I am getting this message
An Error Was Encountered. The action you have requested is not
allowed.
var vl = "; " + document.cookie;
var pr = vl.split("; csrf_cookie=");
var obj; if (pr.length == 2) { obj = pr.pop().split(";").shift(); }
using this variable in the ajax body section like
data : '<?php echo $this->security->get_csrf_token_name(); ?>': obj
Now it's working fine.

AJAX - Complex user activation for login

Now this may sound complicated but I have a page called activation.php where after the user has registered using my reg.php page, they get sent an email with their activation link - activation.php then a get method of k to make activation.php?k=activation-code-here
I made it so it returns the status of the activation, e.g - success of error.
On my reg.php page, I want to make it so it uses ajax to open a sweetAlert popup saying 'Activation Success'. It will get the popup depending on if the users 'activ_status' changed from 0 to 1 in the database when they access the activation.php page with a correct activation key.
Here is my code :
Activation.php
<?php
include('inc/conf/db_.php');
$result = '';
if(empty($_GET['k']) || (!$_GET['k']))
{
header('Location: login.php');
exit();
$result = 'Hacker Tried Accessing Auth Page';
}
$key = mysqli_real_escape_string($con,$_GET["k"]);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php
if (!empty($key))
{
$query = "SELECT * FROM users WHERE activ_key = '$key'";
$result = mysqli_query($con,$query) or die('error');
if (mysqli_num_rows($result))
{
$row = mysqli_fetch_array($result);
if ($row['activ_status']!='1')
{
$query = "update users set activ_status='1' where activ_key='$key'";
$result = mysqli_query($con,$query) or die('error');
$result = 'Successfuly Activated, Return To Your Other Page.';
}
else
{
$result = "Account Already Activated";
}
}
else
{
$result = 'Invalid Access Token';
}
}
else
{
$result = 'Error';
}
?>
<?php include('inc/login_header.php'); ?>
<div class="accountbg"></div>
<div class="wrapper-page">
<div class="panel panel-color panel-primary panel-pages">
<div class="panel-body">
<br>
<center><div id="result"></center>
<br>
<h3 class="text-center m-t-0 m-b-30"> <span class=""><?php echo site_settings('site_name'); ?></h3>
<h4 class="text-muted text-center m-t-0"><b>Activation Status</b></h4>
<br>
<center><img src="assets/images/loading.gif"></center>
<br>
<center><div class="alert alert-info"><button type="button" class="close"></button><?php echo $result; ?></div></center>
<?php return $result; ?>
</body>
</html>
My reg.php page
<?php
include('inc/conf/db_.php');
if (session_status() == PHP_SESSION_ACTIVE) {
session_start();
}
if(isset($_SESSION['user_i']) || isset($_SESSION['login'])) {
header('Location: index.php');
exit();
}
else if (session_status() == PHP_SESSION_NONE) {
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link href="assets/plugins/bootstrap-sweetalert/sweet-alert.css" rel="stylesheet" type="text/css">
<?php include('inc/login_header.php'); ?>
<div class="accountbg"></div>
<div class="wrapper-page">
<div class="panel panel-color panel-primary panel-pages">
<div class="panel-body">
<center><img src="assets/images/loading.gif" id="loading-image" style="display:none"/></center>
<h3 class="text-center m-t-0 m-b-30"> <span class=""><?php echo site_settings('site_name'); ?></h3>
<h4 class="text-muted text-center m-t-0"><b>Sign Up</b></h4>
<form id="registered_form" class="form-horizontal m-t-20">
<div class="form-group has-feedback">
<div class="col-xs-12"> <input class="form-control" name="email" type="email" required="" placeholder="Email"></div>
<span class="fa fa-envelope form-control-feedback text-muted" style="margin-top: 3%;"></span>
</div>
<div class="form-group has-feedback">
<div class="col-xs-12"> <input class="form-control" name="username" type="text" required="" placeholder="Username"></div>
<span class="fa fa-user form-control-feedback text-muted" style="margin-top: 3%;"></span>
</div>
<div class="form-group has-feedback">
<div class="col-xs-12"> <input class="form-control" name="password" type="password" required="" placeholder="Password"></div>
<span class="fa fa-lock form-control-feedback text-muted" style="margin-top: 3%;"></span>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="6LeGFxYUAAAAAOqjyovTS3H0D1HS4IBgoHMvG4y_"></div>
</div>
<div class="form-group">
<div class="col-xs-12">
<div class="checkbox checkbox-primary" style="text-align: center;"> <input type="checkbox" name="checkbox" value="agree"> <label for="checkbox-signup"> I accept Terms and Conditions </label></div>
</div>
</div>
<div class="form-group text-center m-t-20">
<div class="col-xs-12"> <button class="btn btn-primary w-md waves-effect waves-light" type="submit" id="reg_button" style="width: 100%;" >Register</button></div>
</div>
<div class="form-group m-t-30 m-b-0">
<div class="col-sm-12 text-center"> Already have an account?</div>
</div>
</form>
</div>
</div>
</div>
<script src="assets/js/jquery.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="assets/js/jquery.validate.js"></script>
<script src="assets/plugins/bootstrap-sweetalert/sweet-alert.min.js"></script>
<script>
$(document).ready(function()
{
jQuery.validator.addMethod("noSpace", function(value, element)
{
return value.indexOf(" ") < 0 && value != "";
}, "Spaces are not allowed");
$("#registered_form").submit(function()
{
if ($("#registered_form").valid())
{
$('#loading-image').show();
var data1 = $('#registered_form').serialize();
$.ajax({
type: "POST",
url: "inc/pgs/register.php",
data: data1,
success: function(msg)
{
$('#loading-image').hide();
console.log(msg);
if(msg == '')
{
swal({
title: "Registration Success!",
text: "Your registration was successful! Check your email and click on your activation link to be able to access your account. NOTE: Keep this page open",
type: "success",
timer: 15000,
showConfirmButton: false
});
}
else
{
swal("Registration Error!", msg, "error");
}
}
});
$.ajax({
type: "GET",
url: "activation.php",
data: data1,
success: function(msg)
{
if(msg == 'Successfuly Activated, Return To Your Other Page.')
{
swal({
title: "Activation Success",
text: "You can now login!",
type: "success",
timer: 15000,
showConfirmButton: false
});
}
}
});
}
return false;
});
});
</script>
</body>
</html>
<?php } ?>
I found a piece of code that might help me. It doesn't seem to be loading the modal up though:
$.ajax({
url: 'activation.php',
type: 'GET',
dataType: 'jsonp',
cache: 'false',
timeout: 32000,
success: function(data) {
if(data == 'Successfuly Activated, Return To Your Other Page.')
{
swal("Activation Completed!", "You can now login using the link at the bottom of the page - Already have an account?", "success")
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error[refresh]: " + textStatus);
console.log(jqXHR);
ajaxCall();
},
});
Please clearly explain the problem you are having that is preventing the code from working as you intend.
If my interpretation is correct, you want to update the registration page that user keeps open while activating in another window, and then reflect the change on the registration page using AJAX. In fact, in this case you want to send data from the server to your client (you want something to change when a change happens on the server in the database). In this case, a simple solution is to repeatedly request the status (for instance every 2 seconds) using setTimeout. Other solutions exist but are probably overkill, such as long polling or web sockets.

Resources