Is there is a way to keep my modal open in Laravel after submit and save the values to db? - ajax

I am uploading a file in Laravel 8 with having one bootstrap modal which works dynamically . everything is working fine but I want to improve my output more:
1) Update one of my forms through a modal without refreshing the page?
2) keep the modal open if the validation fails and print the errors to modal instead of my redirect page?
I will appreciate your time helping me.
my form for updating the file
<form action="{{ route('storefile' , $requisition->id) }}" method="POST"
enctype="multipart/form-data">
#csrf
#method('PUT')
<div class="form-group row">
<div class="col-sm-12">
<label for="title"> Account Status: </label>
<select class="form-control" name="acc_status">
<option value="0" {{ $requisition->acc_status == 0 ? 'selected' : '' }}> Inactive
</option>
<option value="1" {{ $requisition->acc_status == 1 ? 'selected' : '' }}> Active
</option>
</select>
</div>
<div class="col-sm-12 pt-4">
<label for="title"> Account document File: </label>
<div>
#if (!empty($requisition->acc_document))
<label class="badge-success">
{{ $requisition->acc_document }}
</label>
#else
<label class="badge-danger">
Nothing uploaded </label>
#endif
</div>
<input type="file" name="acc_document" class="form-control" id="acc_document" />
</div>
</div>
<div class="card-footer">
<div class="row">
<div class="col-md-6 text-left">
<input type="submit" value="Upload document" class="btn btn-primary">
</div>
</div>
</div>
</div>
</form>
my controller and route
public function uploadFile($id) {
$requisition = Requisition::find($id);
return view('requisition.createFile' , compact('requisition'));
}
public function storeFile(Request $request , $id) {
$request->validate([
'acc_status' => 'required',
'acc_document' => 'required|mimes:doc,docx,pdf,txt,zip|max:2000',
]);
$requisition = Requisition::find($id);
$requisition->acc_status = $request->get('acc_status');
$FileName = uniqid() .$request->file('acc_document')->getClientOriginalName();
$path = $request->file('acc_document')->storeAs('uploads', $FileName , 'public');
$requisition->acc_document = '/storage/' . $path;
}
$requisition->save();
//$requisition->update($request->all());
return back()
->with('success', 'Your file has been uploaded successfully.');
}
Route::get('upload/{id}', [RequisitionController::class, 'uploadFile'])->name('upload');
Route::put('requisition/{id}/files', [RequisitionController::class, 'storeFile'])->name('storefile');
and last part my modal and ajax in my index page to upload the file and popup will open
<div class="col-md-6">
<a style="display:inline-block; text-decoration:none; margin-right:10px;"
class="text-secondary" data-toggle="modal" id="mediumButton"
data-target="#mediumModal" title="upload"
data-attr="{{ route('upload' , $requisition->id) }}">
<i class="fas fa-upload"></i>
</a>
</div>
<script>
// display a modal (medium modal)
$(document).on('click', '#mediumButton', function(event) {
event.preventDefault();
let href = $(this).attr('data-attr');
$.ajax({
url: href,
beforeSend: function() {
$('#loader').show();
},
// return the result
success: function(result) {
// #if (count($errors) > 0) #endif
$('#mediumModal').modal("show");
$('#mediumBody').html(result).show();
$("#date-picker").datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'yy-mm-dd'
});
} ,
complete: function() {
$('#loader').hide();
},
error: function(jqXHR, testStatus, error) {
console.log(error);
alert("Page " + href + " cannot open. Error:" + error);
$('#loader').hide();
},
timeout: 8000
});
});
</script>
<!-- medium modal -->
<div class="modal fade" id="mediumModal" tabindex="-1" role="dialog" aria-labelledby="mediumModalLabel"
aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content">
<div class="modal-body" id="mediumBody">
<form id="modal-form" method="get">
<div>
<!-- the result of displayed apply here -->
</div>
</form>
</div>
</div>
</div>
</div>
#endsection
what I want to implement looks like enter image description here

There are several ways to do this kind of thing. One way to do it, is to do something like this:
Html:
<div class="modal" id="the-modal">
<form action="{{ $theAction }}" method="POST" id="the-form">
<input type="text" name="input-name" id="the-input">
<button type="submit">
</form>
<p id="the-text"></p>
</div>
In your Controller you will return an error or an 200 response, if everything is ok.
public function theAction(Request $request , $id) {
//Do stuff
if (!$error) {
return response("OK"); //This will return a 200 response
} else {
return response("An error happened", 500); //This will return a 500 error
}
}
Then, in your JS, you'll intercept form submission and then, you're going to be able to separate errors from ok messages:
<script>
$("#the-form").on('submit', function(event) {
event.preventDefault();
let theInput = $("#the-input");
$.ajax({
url: theUrl,
data: {
the-input: theInput
}
// 200 response
success: function(result) {
$("#the-text").empty();
$("#the-text").append(result.repsonse);
} ,
error: function(jqXHR, testStatus, error) {
$("#the-text").empty();
$("#the-text").append(error.response);
}
});
});
</script>
If you want to do all this stuff inside a modal, the concept is just the same: You intercept form submission, send to controller, return separate responses for errors and 200 responses, and then update manually the inputs/texts.
I did't test the code, but the concept should work.

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>

Laravel Ajax Add To Cart Not working 500 internal error

I have code I am working on. I will list the page, the route, and the controller code. When I inspect and click on the add to cart button I get 500 internal server error and I cannot figure out what I did. It should be giving a message checking to see if the item is already in the cart and if not send a message saying item is in the cart but I can't get past the 500 internal server error.
Page
#extends('layouts.frontend.frontend')
#section('title')
Distinctly Mine - {{$products->name}}
#endsection
#section('content')
<div class="py-3 mb-4 shadow-sm babyblue border-top">
<div class="container">
<h6 class="mb-0">Collections / {{$products->category->name}} / {{$products->name}}</h6>
</div>
</div>
<div class="container">
<div class="card-shadow shadow-sm product_data">
<div class="card-body">
<div class="row">
<div class="col-md-4 border-right">
<div class="img-hover-zoom img-hover-zoom--xyz card-img-top">
<img src="{{ asset('backend/uploads/products/'.$products->image) }}" class="w-100 h-100" alt="{{$products->name}}">
</div>
</div>
<div class="col-md-8">
<h2 class="mb-0">{{ $products->name}}</h2>
<hr>
<label for="" class="me-3">Price: ${{$products->original_price}}</label>
<p class="mt-3">{!! $products->small_description !!}</p>
<hr>
#if($products->qty > 0)
<label for="" class="badge bg-success text-dark fw-bold">In Stock</label>
#else
<label for="" class="badge bg-danger text dark fw-bold">Out of Stock</label>
#endif
<div class="row mt-2">
<div class="col-md-2">
<input type="hidden" value="{{$products->id}}" class="prod_id">
<label for="Quantity">Quantity</label>
<div class="input-group text-center mb-3" style="width:130px">
<button type="button" class="input-group-text decrement-btn">-</button>
<input type="text" name="quantity" value="1" class="form-control qty-input" />
<button type="button" class="input-group-text increment-btn">+</button>
</div>
</div>
<div class="col-md-10">
<br />
<button type="button" class="btn btn-warning text-dark fw-bold ms-3 float-start"><i class=" me-1 fa fa-heart text-danger me-1"></i>Add To Wishlist</button>
<button type="button" class="btn btn-success ms-3 float-start text-dark fw-bold addToCartBtn"><i class="me-1 fa fa-shopping-cart text-dark me-1"></i>Add to Cart</button>
</div>
<hr>
<h2>Description</h2>
{{$products->description}}
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script>
$(document).ready(function (){
$('.addToCartBtn').click(function (e){
e.preventDefault();
var product_id = $(this).closest('.product_data').find('.prod_id').val();
var product_qty = $(this).closest('.product_data').find('.qty-input').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method: "POST",
url: "/add-to-cart",
data: {
'product_id': product_id,
'product_qty': product_qty,
},
dataType: "dataType",
success: function (response){
alert(response.status);
}
});
});
$('.increment-btn').click(function (e){
e.preventDefault();
var inc_value = $('.qty-input').val();
var value = parseInt(inc_value,10);
value = isNaN(value) ? 0 :value;
if(value < 10)
{
value++;
$('.qty-input').val(value);
}
});
$('.decrement-btn').click(function (e){
e.preventDefault();
var dec_value = $('.qty-input').val();
var value = parseInt(dec_value,10);
value = isNaN(value) ? 0 :value;
if(value > 1)
{
value--;
$('.qty-input').val(value);
}
});
});
</script>
#endsection
Route
Route::middleware(['auth'])->group(function (){
Route::post('/add-to-cart',[CartController::class,'addProduct']);
});
Controller
<?php
namespace App\Http\Controllers\Frontend;
use App\Models\Product;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
class CartController extends Controller
{
public function addProduct(Request $request)
{
$product_id = $request->input('product_id');
$product_qty = $request->input('product_qty');
if(Auth::check())
{
$prod_check = Product::where('id',$product_id)->first();
if($prod_check)
{
if(Cart::where('prod_id',$product_id)->where('user_id',Auth::id())->exists())
{
return response()->json(['status' => $prod_check->name." Already Added to cart"]);
}else{
$cartItem = new Cart();
$cartItem->prod_id = $product_id;
$cartItem->user_id = Auth::id();
$cartItem->prod_qty = $product_qty;
$cartItem->save();
return response()->json(['status'=>$prod_check->name." Added to cart"]);
}
}
}
else{
return response()->json(['status'=> "Login To Continue"]);
}
}
}

Async Method returns 404

I got the following problem.
in my Controller, this method is supposed to return a JSON with the pets from the database. but is being called, the server returns a 404.
public async Task<JsonResult> GetPetsAsync(int ownerId )
{
var pets = await _dataContext.Pets
.Where(p => p.Owner.Id == ownerId)
.OrderBy(p => p.Name)
.ToListAsync();
return Json(pets);
}
=====================================================
This is the form that provides the OwnerId for the method to find the pets for that particular owner.
<div class="row m-auto align-content-center">
<div class="col-md-4">
<form asp-action="Assign" enctype="multipart/form-data">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Id" />
<div class="form-group">
<label asp-for="OwnerId" class="form-label fw-bold"></label>
<select asp-for="OwnerId" asp-items="Model.Owners" class="form-control"></select>
<span asp-validation-for="OwnerId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="PetId" class="form-label fw-bold"></label>
<select asp-for="PetId" asp-items="Model.Pets" class="form-control"></select>
<span asp-validation-for="PetId" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Remarks" class="form-label fw-bold "></label>
<textarea asp-for="Remarks" class="form-control"></textarea>
<span asp-validation-for="Remarks" class="text-danger"></span>
</div>
<div class="form-group mt-3">
<button value="Assign" type="submit" class="btn btn-primary btn-sm"><i class="bi bi-calendar-plus-fill"></i></button>
<a asp-action="Index" class="btn btn-success btn-sm"><i class="bi bi-arrow-return-left"></i> Go Back</a>
<span asp-validation-for="Remarks" class="text-danger"></span>
</div>
</form>
</div>
</div>
In my View -- the AJAX request to GetPetsAsync
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(document).ready(function () {
$("#OwnerId").change(function () {
$("#PetId").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetPetsAsync", "Agenda")',
//Take the OwnerId and send it to the JsonResult Method to retrieve the pets
data: { ownerId: $("#OwnerId").val() },
dataType: 'Json',
success: function (pets) {
$("#PetId").append('<option value="0">(Select a pet...)</option>');
$.each(pets, function (i, pet) {
$("#PetId").append('<option value="'
+ pet.id + '">'
+ pet.name + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve pets. ' + ex.statusText);
}
});
return false;
})
});
</script>
It looks like this feature change is affecting you.
Async suffix for controller action names will be trimmed by default #14716
You can just drop the "Async" suffix from your view-side code. Which is why renaming your method "fixed" your problem.
You have control over this behavior in your app startup with SuppressAsyncSuffixInActionName
builder.Services.AddMvc(options =>
{
options.SuppressAsyncSuffixInActionNames = false;
});
Make sure the "httppost" attribute is used. If you continue to get an error, check the data part in the ajax section.
I found the solution. Incredibly just by changing the Method Name to GetPetAsyncronous the problem was solve. I don’t know why the previous method wouldn’t work. But It worked.

Laravel-7: Edit Image via modal and ajax

So I'm done with trying to upload image using modal and ajax, now I want to edit it. So my modal trigger is the uploaded picture itself. My problem is how do I get the data from the database and display it on my modal? Am also having this error:
Uncaught ReferenceError: data is not defined
MODAL TRIGGER: (user/gallery.blade.php)
#foreach($galleries as $art)
<div class="card" style="width: 20rem;">
<img class="card-img-top" src="/storage/upload/{{$art->upload}}" alt="Card image cap" id="editUpload" data_id="{{$art->id}}">
</div>
#endforeach
MODAL: (scripts/editUploadModal.blade.php)
<div class="modal .modal-lg bg-white" tabindex="-1" id="editUploadModal">
<div class="container">
<h3 class="text-center">EDIT UPLOAD</h3>
<form id="editForm" enctype='multipart/form-data'>
<div class="modal-body">
<input type="text" name="id" id="editId">
<input type="file" name="upload" id="editUpload"><br>
<img class="card-img-top" src="#" id="imageResult"><br>
<label>CAPTION</label>
<input type="textarea" class="form-control bg-white border-dark" name="description" id="description">
</div>
<button class="btn btn-danger">DELETE UPLOAD</button>
<button class="btn btn-success">SAVE</button>
</form>
</div>
</div>
SCRIPT: (scripts/editUpload_script.blade.php)
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('body').on('click','#editUpload', function(){
$('#editUploadModal').modal('show');
console.log($(this).attr('data_id')); //DISPLAYS ID
data_id = $(this).attr('data_id');
//THIS IS WERE AM STUCK FROM BECAUSE IT IS NOT DISPLAYING THE DATA IN CONSOLE
$.get("{{route('gallery.index')}}" + '/' + data_id + '/edit', function(Data){
console.log(data.upload + " " + data.description)
$('#editId').val(data.id);
$('#editUpload').val(data.upload);
$('#description').val(data.description);
//display image
reader.onload = function () {
$('#imageResult').attr("/storage/upload/" + data.upload);
});
});
});
</script>
CONTROLLER: (GalleryController.php) btw, I added use Response;
public function edit(Gallery $gallery)
{
return Response::json($gallery);
}

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