i used a modal to delete json file data delete. but i used JavaScript to view my json file data into a html file. but i used a delete modal to delete data it's not working properly. now i used to delete data without any warning message. this is my JavaScript code to view data.
var output = document.getElementById('output');
var ajaxhttp = new XMLHttpRequest();
var url = "form.json";
var xhttp = new XMLHttpRequest();
var details = '';
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//var response = JSON.parse(xhttp.responseText);
var response = JSON.parse(xhttp.responseText);
var output = '';
output += "<table class='table table-bordered'>";
output += "<tr><th scope='col'>id</th><th>First Name</th><th>Last Name</th><th>Age</th><th>Action</th></tr>";
for(x in response){
if(response[x].is_active == "1"){
output += "<tr><td>" + response[x].id + "</td><td>" + response[x].firstname + "</td><td>"+response[x].lastname+"</td><td>"+response[x].age+"</td><td><a href='edit.php?id="+response[x].id+"&firstname="+response[x].firstname+"&lastname="+response[x].lastname+"&age="+response[x].age+"' class='btn btn-primary btn-sm active' role='button' aria-pressed='true'>Edit</a><a href='update.php?id="+response[x].id+"&firstname="+response[x].firstname+"&lastname="+response[x].lastname+"&age="+response[x].age+"' class='btn btn-danger btn-sm' role='button' name='btnDelete' style='margin-left: 10px;'>Delete</a></td></tr>";
}
}
output += "</table> ";
document.getElementById("output").innerHTML = output;
and this is my delete php function to update active status.
session_start();
$success = "<div class='alert alert-danger' role='alert'>User Deleted Successfully</div>";
$success = urlencode($success);
$myFile = "form.json";
//create empty array
$arr_data = array();
try{
//Get form data
$formdata = array(
'id' => $_GET['id'],
'firstname' => $_GET['firstname'],
'lastname' => $_GET['lastname'],
'age' => $_GET['age'],
'is_active' => '0'
);
//get data from existing json file
$jsondata = file_get_contents($myFile);
//converts json data into array
$arr_data = json_decode($jsondata, true);
$updateKey = null;
foreach($arr_data as $key=>$value){
if($value['id'] == $formdata['id']){
$updateKey = $key;
}
}
if($updateKey === null){
array_push($arr_data, $formdata);
}
else{
$arr_data[$updateKey] = $formdata;
}
//push user data to array
//array_push($arr_data, $formdata);
//convert update array to json
$jsondata = json_encode($arr_data);
//write json data into form.json file
if(file_put_contents($myFile, $jsondata)){
header("location: index.php?success=$success");
}else{
echo "error deleting";
}
}
catch(Exception $e){
echo 'Caught Exception ', $e->getMessage(), "\n";
}
how i used a model to call this php function to delete data with JavaScript button.
To open a popup with delete data :
1) You will have to add id's to your data for delete link, which when clicked shows the popup.
2) The popup will have the delete confirm button, which when the user clicks a delete call via ajax to your controller method is made to delete the data from db/remote api etc.
I have shown a sample demo of that. You can try it with your own
$(".btn").click(function(){
$("#myModal").show();
$("#deletebtn").click(function(){
// Your ajax call for controller to delete
});
//
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Small Modal</h2>
<ul>
<li id="1">Item 1 <button type="button" class="btn btn-info btn-small" data-toggle="modal" data-target="#myModal">Delete</button></li><br>
<li id="2">Item 2 <button type="button" class="btn btn-info btn-small" data-toggle="modal" data-target="#myModal">Delete</button></li><br>
<li id="3">Item 3 <button type="button" class="btn btn-info btn-small" data-toggle="modal" data-target="#myModal">Delete</button></li><br>
<li id="4">Item 4 <button type="button" class="btn btn-info btn-small" data-toggle="modal" data-target="#myModal">Delete</button></li><br>
</ul>
<!-- Trigger the modal with a button -->
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Are you sure you want to delete ?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" id="deletebtn">Delete</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Related
I am now sending data to another page without refresh but my problem is the modal, I cannot send it as a modal but I can send the data into text. why ?
here is an image of my page
here is my code
for ajax4.html
This is where I submit data and perform inserts
<h1>AJAX POST FORM</h1>
<form id="postForm">
<input type="text" name="name" id="name2">
<input type="submit" value="Submit">
</form>
<script>
document.getElementById('postForm').addEventListener('submit', postName);
function postName(e){
e.preventDefault();
var name = document.getElementById('name2').value;
var params = "name="+name
;
var xhr = new XMLHttpRequest();
xhr.open('POST', 'process.php', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function(){
console.log(this.responseText);
}
xhr.send(params);
}
</script>
my ajax5.html
This is where I fetch the data and also, here is where I want to show the modal
**EDIT** here is my current HTML
<h1>Users</h1>
<div id="users"></div>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">User List</h4>
</div>
<div class="modal-body" id="user-list">
<p>User list here</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script>
var still_fetching = false;
//fetch data every 3 seconds (3000)
setInterval(function(){
if (still_fetching) {
return;
}
still_fetching = true;
loadUsers();
}, 3000);
//need to update a bit this function
function loadUsers(){
var xhr = new XMLHttpRequest();
xhr.open('GET', 'users.php', true);
xhr.onload = function(){
if(this.status == 200){
var users = JSON.parse(this.responseText);
var output = '';
for(var i in users){
output += '<div id="myModal" class="modal">' +
'<div class="modal-content">' +
'<span class="close">×</span>' +
'<p>'+users[i].id+'</p>' +
'<p>'+users[i].name+'</p>' +
'</div>' +
'</div>';
}
//document.getElementById('users').innerHTML = output;
document.getElementById('user-list').innerHTML = output;
document.getElementById('myModal').style.display = "block"; //show modal
still_fetching = false;
}
}
xhr.send();
}
</script>
</body>
</html>
process.php
<?php
//Connect to a database
$conn = mysqli_connect('localhost','root','','ajaxtest');
echo 'Processing....';
//Check for POST variable
if(isset($_POST['name'])){
$name = mysqli_real_escape_string($conn, $_POST['name']);
//echo 'GET: Your name is '. $_POST['name'];
$query = "INSERT INTO users(name) VALUES('$name')";
if(mysqli_query($conn, $query)){
echo 'User Added...';
}else{
echo 'ERROR: '.mysql_error($conn);
}
}
//Check for GET variable
if(isset($_GET['name'])){
echo 'GET: Your name is '. $_GET['name'];
}
There are some problem in your code.
1. You check the name parameter:
if(isset($_GET['name']))
But you don't provide it when get.
xhr.open('GET', 'users.php', true);
Provide it.
xhr.open('GET', 'users.php?name=shingo', true);
2. The response isn't a JSON string:
echo 'GET: Your name is '. $_GET['name'];
JSON.parse(this.responseText);
Assuming your modal is using Bootstrap:
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">User List</h4>
</div>
<div class="modal-body" id="user-list">
<p>User list here</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
Edit your JS function:
function loadUsers(){
var xhr = new XMLHttpRequest();
xhr.open('GET', 'users.php', true);
xhr.onload = function(){
if(this.status == 200){
var users = JSON.parse(this.responseText);
var output = '';
for(var i in users){
output +=
'<div>' +
'<p>'+users[i].id+'</p>' +
'<p>'+users[i].name+'</p>' +
'</div>';
}
//document.getElementById('users').innerHTML = output;
document.getElementById('user-list').innerHTML = output;
document.getElementById('myModal').style.display = "block"; //show modal
still_fetching = false;
}
}
xhr.send();
}
I am having problem with AJAX in 000webhost. The output for AJAX is not displaying. Also, there is no error in the Console when I inspected.
This is my website link:
https://cwp-geoworld.000webhostapp.com/
The AJAX part is working fine with localhost and it can display the list of continents in the sidebar as well as a table in the middle of the page when the sidebar is clicked.
Example of how it should look like is here:
https://drive.google.com/open?id=1Tn5hQXepA--o4LTqBc_DzjeZ17yz830Z
Here are the codes for the index.php which contains the AJAX code:
<?php
include("control.php");
//require_once( "classes/session.class.php" );
$username = Session::getInstance()->getProperty("username");
$userRole = Session::getInstance()->getProperty("userRole");
require_once( "classes/PDOConnection.class.php" );
//header('Content-type: application/json');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>GeoWorld | Home</title>
<!--Icon at the tab-->
<link rel="icon" type="image/png" href="images/globe_icon.png"/>
<!-- Tell the browser to be responsive to screen width -->
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<link rel="stylesheet" href="template/other_pages/bower_components/bootstrap/dist/css/bootstrap.min.css">
<!-- Font Awesome -->
<link rel="stylesheet" href="template/other_pages/bower_components/font-awesome/css/font-awesome.min.css">
<!-- Ionicons -->
<link rel="stylesheet" href="template/other_pages/bower_components/Ionicons/css/ionicons.min.css">
<!-- Theme style -->
<link rel="stylesheet" href="template/other_pages/dist/css/AdminLTE.min.css">
<!-- Skins -->
<link rel="stylesheet" href="template/other_pages/dist/css/skins/skin-purple.css">
<!-- Google Font -->
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic">
</head>
<body class="hold-transition skin-purple sidebar-mini">
<!--WRAPPER-->
<div class="wrapper">
<!-- Main Header -->
<header class='main-header'>
<!-- Logo -->
<a href='index.php' class='logo'>
<!-- mini logo for sidebar mini 50x50 pixels -->
<span class='logo-mini'><i class='fa fa-globe'></i><b>Geo</b></span>
<!-- logo for regular state and mobile devices -->
<span class='logo-lg'><b>Geo</b>World</span>
</a>
<!-- Header Navbar -->
<nav class='navbar navbar-static-top' role='navigation'>
<!-- Sidebar toggle button-->
<a href='#' class='sidebar-toggle' data-toggle='push-menu' role='button'>
<span class='sr-only'>Toggle navigation</span>
</a>
<div class="navbar-custom-menu">
<ul class="nav navbar-nav">
<!--Include Conditions for Navbar-->
<?php include ('include/navbar.php'); ?>
</ul>
</div>
</nav>
</header>
<!--Include Sidebar-->
<?php include ('include/sidebar.php'); ?>
<!-- CONTENT WRAPPER -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1 align='center'>
Welcome to GeoWorld
</h1>
</section>
<!-- Main content -->
<section class="content container-fluid">
<!-- search form (Optional) -->
<div id="searchTextBox">
<div class="input-group">
<input type="text" id='search' name="search_country" maxlength=3 class="form-control" placeholder="Search for a country here...">
<span class="input-group-btn">
<button type="submit" id='search-btn' class="btn btn-flat"><i class="fa fa-search"></i>
</button>
</span>
</div>
</div><!-- /.search form -->
<br/>
<div class="searchResults"></div><br/>
<div class="box-body">
<div id="records"></div>
</div>
</section><!-- /.content -->
</div><!-- /.content-wrapper -->
</div><!-- ./wrapper -->
<!-- Modal for show more details about country -->
<div class="modal fade" id="countryModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">More details about the country</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<!--<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>-->
<!--<button type="button" class="btn btn-primary">Save changes</button>-->
</div>
</div>
</div>
</div>
<!-- Modal for show details about city -->
<div class="modal fade" id="cityModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">City details</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body"></div>
<div class="modal-footer">
<!--<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>-->
<!--<button type="button" class="btn btn-primary">Save changes</button>-->
</div>
</div>
</div>
</div>
<!-- Modal to update HOS -->
<div class="modal fade" id="updateModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Edit details</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body"></div>
</div>
</div>
</div>
<!-- Modal to upload flag -->
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Upload Flag</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body"></div>
</div>
</div>
</div>
</body>
</html>
<!-- REQUIRED JS SCRIPTS -->
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<!-- jQuery 3 -->
<script src="template/other_pages/bower_components/jquery/dist/jquery.min.js"></script>
<!-- Bootstrap 3.3.7 -->
<script src="template/other_pages/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- AdminLTE App -->
<script src="template/other_pages/dist/js/adminlte.min.js"></script>
<!--script for displaying continents and countries records-->
<script type="text/javascript">
$(document).ready(function(){
//$('#searchTextBox').hide();
$('.records').hide();
$("input[name='search_country']").on('keypress', function (e) {
var charCode = e.which;
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || charCode == 8)
return true;
else
return false;
});
});
$(function()
{
$.getJSON( "showAllContinents.php", function(obj)
{
$.each(obj, function(key, value)
{
var sidebarOption = "";
//sidebarOption = '<input type="hidden" value="showAllContinents" name="action"/>';
sidebarOption += '<li>';
sidebarOption += '<a data-id="'+value.ID+'" class="sidebar-country">';
sidebarOption += value.Name;
sidebarOption += '</a>';
sidebarOption += '</li>';
$(".treeview-menu").append(sidebarOption);
});
});//end of $.getJSON function
$("#options_continent").change(function() {
getCountryRecords($(this).val());
});//end of option function
$(document).on('click', '.sidebar-country', function() {
getCountryRecords($(this).attr('data-id'));
});
//to show LifeExpectancy, GNP and HOS when button is clicked
$("#records").on("click", "#tbl_countries button#more_details",function()
{
$(".modal-body").empty();
var A3Code = $(this).val();
$(".records").show();
$.get(
'showCountryDetails.php',
{A3Code: A3Code},
function(data)
{
console.log(data);
//var result= $.parseJSON(data);
//console.log(result);
var string ='<table id="tbl_countries" class="table table-bordered table-hover"><tr><th>Life Expectancy</th><th>GNP</th><th>Head of State</th></tr>';
$.each( data, function( key, value )
{
$(".records").empty();
string += "<tr>"
+"<td>"+value['LifeExpectancy'] +"</td>"
+"<td>"+value['GNP']+"</td>"
+"<td>"+value['HeadOfState']+"</td>"
+"</tr>";
});
string += '</table>';
$(".modal-body").append(string);
} //end of function data
); //end of get
});//end of click button
//to show city details when button is clicked
$("#records").on("click", "#tbl_countries button#city_details",function()
{
$(".modal-body").empty();
var A3Code = $(this).val();
$(".records").show();
$.get(
'showCityDetails.php',
{A3Code: A3Code},
function(data)
{
var string ='<table id="tbl_countries" class="table table-bordered table-hover"><tr><th>City Name</th><th>District</th><th>Population</th><th>Latitude</th><th>Longitude</th></tr>';
$.each( data, function( key, value )
{
$(".records").empty();
string += "<tr>"
+"<td>"+value['name'] +"</td>"
+"<td>"+value['district']+"</td>"
+"<td>"+value['population']+"</td>"
+"<td>"+value['lat']+"</td>"
+"<td>"+value['lng']+"</td>"
+"</tr>";
});
string += '</table>';
//$(".records").append(string);
$(".modal-body").append(string);
} //end of function data
); //end of get
});//end of click button
//to update HOS modal box
$("#records").on("click", "button#update_HOS",function()
{
$(".modal-body").empty();
var A3Code = $(this).val();
$(".records").show();
$.get(
'showCountryDetails.php',
{A3Code: A3Code},
function(data)
{
console.log(data);
var forms='';
$.each( data, function( key, value )
{
forms +='<form id="updateForm" name="updateForm" action="updateHOS.php" method="post">';
forms +='<div class="form-group">';
forms +='<input type="hidden" id="A3Code" name="A3Code" value='+value["A3Code"]+'>';
forms +='<label class="control-label">HOS:</label>';
forms +='<input type="text" class="form-control" id="hos" name="hos" value='+value['HeadOfState']+'>';
forms +='</div>';
forms += '<div class="form-group">';
forms += '<input type="submit" class="btn-success" id="updateBtn" name="updateBtn" value="Update">';
forms +='</div>';
forms +='</form>';
});
$(".modal-body").append(forms);
} //end of function data
); //end of get
});//end of click button */
//to show upload flag modal box
$("#records").on("click", "button#upload_flag",function()
{
$("#uploadModal .modal-body").empty();
var A3Code = $(this).val();
$(".records").show();
$.get(
'showCountryDetails.php',
{A3Code: A3Code},
function(data)
{
console.log(data);
var uploadForm='';
$.each( data, function( key, value )
{
uploadForm +='<form id="uploadFlagForm" name="uploadFlagForm" action="upload_flag.php" method="post" enctype="multipart/form-data">';
uploadForm +='<div class="form-group" align="center">';
uploadForm +='<input type="hidden" id="A3Code" name="A3Code" value='+value["A3Code"]+'>';
uploadForm +='<input type="file" name="fileToUpload" id="fileToUpload">';
uploadForm +='</div>';
uploadForm += '<div class="form-group" align="center">';
uploadForm += '<button type="submit" class="btn btn-primary" id="uploadBtn" name="uploadBtn">Upload Flag</button>';
uploadForm +='</div>';
uploadForm +='</form>';
});
$("#uploadModal .modal-body").append(uploadForm);
} //end of function data
); //end of get
});//end of click button
//To get country records
function getCountryRecords(id) {
$.ajax
({
url: 'showCountryInfo.php',
type: 'post',
data: {ID:id},
success:function(response)
{
var userRole = "<?php echo $userRole; ?>";
var string = "";
//string += '<input type="hidden" value="showCountryInfo" name="action"/>';
string += '<table id="tbl_countries" class="table table-bordered table-hover">';
string += '<tr>';
string += '<th>Flag</th>';
string += '<th>Country Name</th>';
string += '<th width=200px>Region</th>';
string += '<th>Surface Area</th>';
string += '<th>Population</th>';
string += '<th width=150px>Independent Year</th>';
string += '<th width=100px>City Details</th>';
if (userRole === "admin")
{
string += '<th width=100px>More Details</th>';
string += '<th width=100px>Update Details</td>';
string += '<th width=100px>Upload Flag</td>';
}
string += '</tr>';
/* from result create a string of data and append to the div */
$.each( response, function( key, value )
{
//var base64URL = "";
$("#records").empty();
string += "<tr>";
//string += "<td><img src='"+value['image']+"'/></td>";
//string += "<td><img src='data:image/png;base64, "+base64URL+"'/></td>";
string += "<td>"+"<button class='btn btn-block btn-default btn-sm' id='btnView' name='btnView' type='submit' data-id='" + value['A3Code'] + "'>View</button>" + "</td>";
//string += "<td>"+"<button class='btn btn-block btn-default btn-sm' id='btnView' name='btnView' type='submit' value='" + value['A3Code'] + "'>View</button>" + "</td>";
string += "<td>"+value['Name']+"</td>";
string += "<td>"+value['Region']+"</td>";
string += "<td>"+value['SurfaceArea']+"</td>";
string += "<td>"+value['Population']+"</td>";
string += "<td>"+value['IndepYear']+"</td>";
string += "<td>"+"<button class='btn btn-block btn-info btn-sm' data-toggle='modal' data-target='#cityModal' id='city_details' name='city_details' type='submit' value='" + value['A3Code'] + "'><span class='glyphicon glyphicon-info-sign'></button>" + "</td>";
if (userRole === "admin")
{
string += "<td>"+"<button class='btn btn-block btn-info btn-sm' data-toggle='modal' data-target='#countryModal' id='more_details' name='country_details' type='submit' value='" + value['A3Code'] + "'><span class='glyphicon glyphicon-info-sign'></button>" + "</td>";
string += "<td>"+"<button class='btn btn-block btn-default btn-sm' data-toggle='modal' data-target='#updateModal' id='update_HOS' name='update_HOS' type='submit' value='" + value['A3Code'] + "'><i class='fa fa-edit'></i></button>" + "</td>";
string += "<td>"+"<button class='btn btn-block btn-default btn-sm' data-toggle='modal' data-target='#uploadModal' id='upload_flag' name='upload_flag' type='submit' value='" + value['A3Code'] + "'><i class='fa fa-flag'></i></button>" + "</td>";
}
string += "</tr>";
});
string += '</table>';
$("#records").append(string);
}
});
}
/*$(document).on('click', '#btnView', function(){
window.location.href = "view_flag.php";
});*/
$(document).on('click', '#btnView', function(){
var value = $(this).attr('data-id');
window.location.href = "view_flag.php?A3Code=" + value;
});
/*//For view flag function
$("#btnView").on('click', function(e) {
window.location.href = "view_flag.php";
});*/
/*$("#view_flag").on("click",function()
{
window.location.href = "view_flag.php";
});*/
//For search country function
$("#search-btn").on("click", function ()
{
if(document.getElementById("search").value.length < 3)
{
alert("The characters MUST NOT be less than 3!");
return false;
}
$("#records").empty();
$(".records").empty();
$('.searchResults').empty();
var searchCountry = $("#search").val();
$.get(
'searchCountryInfo.php',
{id: searchCountry}, //left->sql id ,right->script id
function (data)
{
if (!$.trim(data)){
alert("No country with that name is found!");
return false;
}
var userRole = "<?php echo $userRole; ?>";
var string = "";
//string += '<input type="hidden" value="searchCountryInfo" name="action"/>';
string += '<table id="tbl_countries" class="table table-bordered table-hover">';
string += '<tr>';
string += '<th>Flag</th>';
string += '<th>Country Name</th>';
string += '<th width=200px>Region</th>';
string += '<th>Surface Area</th>';
string += '<th>Population</th>';
string += '<th width=150px>Independent Year</th>';
string += '<th width=100px>City Details</th>';
if (userRole === "admin")
{
string += '<th width=100px>More Details</th>';
string += '<th width=100px>Update Details</td>';
string += '<th width=100px>Upload Flag</td>';
}
string += '</tr>';
// var base64URL = getBase64(data[0]['image']);
// console.log(base64URL);
/* from result create a string of data and append to the div */
$.each( data, function( key, value )
{
$("#records").empty();
string += "<tr>";
//string += "<td>"+"<img src='data:image/png;base64,base64_encode("+value['image']+")"+"'/>"+"</td>";
//string += "<td>"+"<img src='data:image/jpeg;base64, "+base64URL+"'/></td>";
string += "<td>"+"<button class='btn btn-block btn-default btn-sm' id='btnView' name='btnView' type='submit' data-id='" + value['A3Code'] + "'>View</button>" + "</td>"; string += "<td>"+value['Name']+"</td>";
string += "<td>"+value['Region']+"</td>";
string += "<td>"+value['SurfaceArea']+"</td>";
string += "<td>"+value['Population']+"</td>";
string += "<td>"+value['IndepYear']+"</td>";
string += "<td>"+"<button class='btn btn-block btn-info btn-sm' data-toggle='modal' data-target='#cityModal' id='city_details' name='city_details' type='submit' value='" + value['A3Code'] + "'><span class='glyphicon glyphicon-info-sign'></button>" + "</td>";
if (userRole === "admin")
{
string += "<td>"+"<button class='btn btn-block btn-info btn-sm' data-toggle='modal' data-target='#countryModal' id='more_details' name='country_details' type='submit' value='" + value['A3Code'] + "'><span class='glyphicon glyphicon-info-sign'></button>" + "</td>";
string += "<td>"+"<button class='btn btn-block btn-default btn-sm' data-toggle='modal' data-target='#updateModal' id='update_HOS' name='update_HOS' type='submit' value='" + value['A3Code'] + "'><i class='fa fa-edit'></i></button>" + "</td>";
string += "<td>"+"<button class='btn btn-block btn-default btn-sm' data-toggle='modal' data-target='#uploadModal' id='upload_flag' name='upload_flag' type='submit' value='" + value['A3Code'] + "'><i class='fa fa-flag'></i></button>" + "</td>";
}
string += "</tr>";
});
string += '</table>';
$("#records").append(string);
}
);
}); // end of search function
}); //end of big function
</script>
Your help will be really appreciated. Thank you.
hi guys need help regarding how to pass a value to php using javacript without reloading the page. What i want to happen is that when i put a value in textbox name num1 that value will go to available.php.. advance thank u.
...
here is my code..
html code
<!-- Modal Staff-->
<div id="add" class="modal fade" role="dialog" tabindex="-1" >
<div class="modal-dialog">
<form action="dashboard.php" method="post">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×
</button>
<h4 class="modal-title">Set Available Student</h4>
</div>
<div class="modal-body">
<input type="text" name="num1" id="num1" class="form-control" />
</div>
<div class="modal-footer">
<input type="submit" name="submit" class="btn btn-success" value="Set">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
javascript code
<script type="text/javascript">
function availble_chair()
{
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","available.php",false);
xmlhttp.send(null);
document.getElementById("count").innerHTML=xmlhttp.responseText;
}
availble_chair();
setInterval(function(){
availble_chair();
},1000);
</script>
and here is my php code available.php
<?php
$set = '';
$connection = mysqli_connect("localhost","root","","dbattendancelibrary");
$query=mysqli_query($connection,"SELECT COUNT(Time_in)-COUNT(Time_out) as Status FROM `tbl_student_form`");
$result = mysqli_fetch_array($query, MYSQLI_NUM);
if($result) {
if($result[0] <= $set) {
$availble = $set-$result[0];
echo "<p style='font-size:50px;margin-left:240px;'> " .$availble. "
</p>";
} else {
echo "<p class='alert alert-danger'>Library Already Full</p>";
}
}
?>
Javascript:
First, you need an on submit event listener so we can detect when the form was submitted.
// get a reference to your form
var form = document.getElementsByTagName('form');
// i suggest adding a classname or ID to your form if you have more then one form on the page
// if that is the case, then select the form by ID or class instead
// add event listener to the form
form.addEventListener('submit', function(event) {
// stop form submitting by default
event.preventDefault();
// get the value from the textbox, num1
var num1 = this.querySelector('#num1').value;
// send value of num1 to available.php via ajax
var xhr = new XMLHttpRequest();
xhr.open('GET', 'available.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
console.log("I worked!");
} else {
console.log("I didn't work!");
}
};
xhr.send(encodeURI('num1=' + num1));
}
PHP
To get the num1 value from AJAX request:
<?php
$num1 = isset($_GET['num1']) ? (int) trim($_GET['num1']) : 0;
if ($num1 > 0) {
// success
}
?>
I have problem with updating modal with new data from cookie. When I select new item in table and push it to cookie. Then it wan't to update my modal view when i press button.
Can somebody figured out why it's not working.
<script>
var selVal = new Array();
$("tbody tr").click(function () {
if ($(this).hasClass('selected')) {
$(this).removeClass('selected');
var pId = $(this).find('td:first').data("id"); // Get id num from selected
//Remove item from array
var i = selVal.findIndex(x => x.pId === pId);
if (i !== -1) {
selVal.splice(i, 1);
}
} else {
$(this).addClass("selected");
var pId = $(this).find('td:first').data("id"); // Get id num from selected
var pNum = $(this).find('td:first').html(); //Get pnum from selected
var newObjArr = {pId, pNum};
selVal.push(newObjArr);
}
createCookie(selVal);
});
function createCookie(selVal) {
var json_str = JSON.stringify(selVal); // JSON Serialize
// Define/Set cookie
Cookies.set("Cookie_<?php echo $id?>", json_str, {expires: 1});
}
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="ModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="ModalLabel">XXXXXXXXXXXXXXXX</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<button type="button" id="refdata_btn" class="btn btn-info">Refresh</button>
<p><label>Airline: </label><input type="text" name='xxxxxx'></p>
<p><label>Date: </label> <input type='date'></p>
<?php
$cookie_name = 'Cookie_' . $id;
if (isset($_COOKIE[$cookie_name])) {
$decjson = json_decode($_COOKIE[$cookie_name], true);
foreach ($decjson as $d) {
echo '<p>' . $d['pNum'] . '</p>';
}
} else {
echo 'Cookie not exist';
}
?>
</div>
<div class="modal-footer">
<button type="button" id='btn_later' class="btn btn-secondary" data-dismiss="modal">Later</button>
<button type="button" class="btn btn-primary">Send</button>
</div>
</div>
</div>
</div>
When I see this it is not give me espacially logical why not it is reseting or overriding previous data.
Thanks,
ZS
So I have the code following and it all works but the on success / error I can figure it out.
This is settings.php
<li><button type="button" onclick="ApimanagementFunctioncall()" id="button1" class="btn btn-default btn-lg">Api management</button></li>
<script>
function ApimanagementFunctioncall(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("display").innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", "Apimanagement.php", true);
xhttp.send();
}
</script>
The Apimanagement.php
MySQLI table here.
<div class="container">
<div class="row text-left">
<button type="button" class="btn btn-default btn-lg" data-toggle="modal" data-target="#AddApi"><span class="glyphicon glyphicon-plus"></span>Add Api</button>
</div>
</div>
<div class="modal fade" id="AddApi" role="dialog">
<?php
include ("ApiAdd.php");
?>
</div>
this is the Addapi.php
<?php
$errorMessage = "";
$UserId = "11";
if(isset($_POST['submit'])){
$VarKeyID = $_POST["KeyID"];
$VarVCode = $_POST["VerificationCode"];
$errorMessage1 = "";
$errorMessage2 = "";
$VkeyAdd= ""; $VCodeAdd = "";
if(empty($VarKeyID) == false){
if(is_numeric($VarKeyID) == true){
if(strlen($VarKeyID) !== 8){
echo '<script type="text/javascript">alert("Key Id is not the correct length of 8 numbers!\n");</script>';}
else{ $VKeyAdd = "true";}
}else{$errorMessage1 = '<script type="text/javascript">alert("Key Id should only be numbers!");</script>';}
}else{$errorMessage1 ='<script type="text/javascript">alert("Please Enter a Key ID!");</script>';}
if(empty($VarVCode) == false){
if(ctype_alnum($VarVCode) == true){
if(strlen($VarVCode) !== 64){
$errorMessage2 = "Verification Code should be 64 characters!";
}else{$VCodeAdd = "true";}
}else{$errorMessage2 = '<script type="text/javascript">alert("Verification Code should only be letters and numbers!");</script>';}
}else{$errorMessage2 ='<script type="text/javascript">alert("Please Enter a Verification Code!");</script>';}
If($VKeyAdd == "true"){
if($VCodeAdd == "true"){
echo "Next";}else{echo $errorMessage2;}
}else{echo $errorMessage1;}
}
?>
<div id="AddApi">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<span class="glyphicon glyphicon-remove"></span>
<h2> Add Api Key </h2>
Api create key here
<form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
Key ID</br> <input type="text" name="KeyID" maxlength="8" value=""></br>
Verification Code</br> <input type="text" name="VerificationCode" maxlength="64" min="64" value=""></br>
<input type="submit" name="submit" value="Submit" formtarget="_Self">
</form>
</div>
</div>
<div>
Now I know some code i have left out but the relevant code is here and works. The issue is when I click the input submit button of the form. It opens up the addApi.php on the server instead I would like it to echo the errors on the input form and if success go to the Settings.php page where the apimanagement.php page is loaded in the div.