I am trying to prompt a loading gif while the POST data and Files are being uploaded to the database. I did a research online and I saw couple of examples with my same issue which was solved but when I tried for example this Ajax and Jquery code, it just loads the gif and it just keeps spinning. I don't know if there is another way to do it without using Ajax but just php.
Here is the Ajax code I tried just below my form
<div id="loader"></div>
<script src="http://code.jquery.com/jquery.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script>
var spinner = $('#loader');
$(function() {
$('form').submit(function(e) {
e.preventDefault();
spinner.show();
$.ajax({
url: 't2228.php',
data: $(this).serialize(),
method: 'post',
dataType: 'JSON'
}).done(function(resp) {
spinner.hide();
alert(resp.status);
});
});
});
and the t2228.php file to call my php code
<?php
include '../lib/session.php';
Session::checkSession();
include '../config/config.php';
include '../lib/database.php';
include '../helpers/format.php';
$db = new Database();
$fm = new Format();
define("DOCROOT", filter_input(INPUT_SERVER, "DOCUMENT_ROOT", FILTER_SANITIZE_STRING));
$pet = new Pet();
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submit'])){
$addPet = $pet->petAdd($_POST, $_FILES);
}
?>
Here is the HTML Form
<form action="" method="post" enctype="multipart/form-data">
<table class="form">
<tr>
<td>
<label>Pet Name</label>
</td>
<td>
<input type="text" name="name" placeholder="Enter Pet Name..." class="medium" />
</td>
</tr>
<tr>
<td>
<label>Pet Price</label>
</td>
<td>
<input type="text" name="price" placeholder="Enter Pet Price..." class="medium" />
</td>
</tr>
<tr>
<td>
<label>Pet Serie</label>
</td>
<td>
<input type="text" name="serie" placeholder="Enter Pet Serie..." class="medium" />
</td>
</tr>
<tr>
<td>
<label>Pet Sex</label>
</td>
<td>
<select id="select" name="sex">
<option>Select Pet Sex</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</td>
</tr>
<tr>
<td>
<label>Pet Age</label>
</td>
<td>
<input type="text" name="age" placeholder="Enter Pet Age..." class="medium" />
</td>
</tr>
<tr>
<td>
<label>Upload Image</label>
</td>
<td>
<div class="post-image-collection">
<label id="list">
</label>
<label class="post-image post-image-placeholder mrm mts empty">
<input type="file" id="Photofile" name="images[]" required="required" multiple />
<span class="icon-camera"><img src="../img/608815-200.png"></span>
<p class="uppercase">Photo</p>
</label>
</div>
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="submit" Value="Add Pet" />
</td>
</tr>
</table>
</form>
Here is My PHP code
public function petAdd($data, $file){
$name = mysqli_real_escape_string($this->db->link, $data['name']);
$price = mysqli_real_escape_string($this->db->link, $data['price']);
$serie = mysqli_real_escape_string($this->db->link, $data['serie']);
$sex = mysqli_real_escape_string($this->db->link, $data['sex']);
$age = mysqli_real_escape_string($this->db->link, $data['age']);
foreach($file["images"]["tmp_name"] as $key=>$tmp_name)
{
$file_name = $file["images"]["name"][$key];
$file_size = $file["images"]["size"][$key];
$file_temp = $file["images"]["tmp_name"][$key];
$file_size_preview = $_FILES['preview']['size'];
$div = explode('.', $file_name);
$file_ext = strtolower(end($div));
$permited = array('jpg', 'jpeg', 'png', 'gif');
if($tmp_name == ""){
$msg = "<span class='error'>Fields must not be empty!</span>";
return $msg;
}
elseif ($file_size > 1048567 || $file_size_preview > 1048567) {
$msg = "<span class='error'>Image Size should be less then 1MB! </span>";
return $msg;
}
elseif (in_array($file_ext, $permited) === false) {
$msg = "<span class='error'>You can upload only:-".implode(', ', $permited)."</span>";
return $msg;
}
}
if($name == "" || $price == "" || $serie == "" || $sex == "" || $age == "") {
$msg = "<span class='error'>Fields must not be empty!</span>";
return $msg;
} else{
$query = "INSERT INTO pets(name, price, serie, sex, age, status, details, shipping, type) VALUES('$name','$price','$serie', '$sex', '$age','$status', '$details','$shipping','$type')";
$inserted_row = $this->db->insert($query);
$last_id = $this->db->link->insert_id;
foreach($file["images"]["tmp_name"] as $key=>$tmp_name)
{
$div = explode('.', $file_name);
$file_ext = strtolower(end($div));
$unique_image = substr(md5(time()), 0, 10).'.'.$file_ext;
$uploaded_image = "../uploads/".$unique_image;
$saveToFolder = DOCROOT . "/dallasfrenchies/uploads/$unique_image";
$saveToDatabase = "uploads/$unique_image";
move_uploaded_file($tmp_name, $saveToFolder);
$query = "INSERT INTO images(petId, path) VALUES('$last_id','$saveToDatabase')";
$this->db->insert($query);
sleep(3);
}
$msg = "<span class='success'> Your Pet has been added Successfully. </span>";
return $msg;
}
}
Any one with a suggestion on what to modify or add?
<div id="loader"></div>
<script src="http://code.jquery.com/jquery.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script>
var spinner = $('#loader');
$(function() {
$('form').submit(function(e) {
e.preventDefault();
spinner.show();
$.ajax({
url: 't2228.php',
data: $(this).serialize(),
method: 'post',
dataType: 'JSON',
success: function(resp) {
spinner.hide();
alert(resp.status);
},
error: function(resp) {
spinner.hide();
alert(resp);
}
})
});
});
Rather than .done() i used the attributes for success and error
Try below code and make few changes in ajax code. Add below parameters in your code.
processData: false,
contentType: false,
And add var formData = new FormData($(this)); line before ajax starts.
Or Check below code and make changes according to you code.
<script type="text/javascript">
$('form').submit(function (e) {
e.preventDefault();
var spinner = $('#loader');
var formData = new FormData($(this));
$.ajax({
url: 't2228.php',
type: "POST",
data: formData,
processData: false,
contentType: false,
beforeSend: function () {
spinner.show();
},
success: function (data)
{
spinner.hide();
},
error: function (resp) {
spinner.hide();
alert(resp);
}
});
});
</script>
Related
I have this code from index.php :
<?php
require("../inc/config.php");
$url = $_GET['url'];
?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<body>
<form method="" action="">
<textarea type="text" class="form-control" id="ketqua" name="ketqua" value="" required="" placeholder="Name|Url" rows="6"></textarea>
<input type="text" class="form-control" id="link" name="link" required="" value="<?php echo $url ?>">
<button type="button" class="btn btn-success" name="insert-data" id="insert-data" onclick="ThemTap()">Add</button>
</form>
<script type="text/javascript">
function ThemTap() {
var ketqua = $("#ketqua").val();
var link = $("#link").val();
$.ajax({
type: "POST",
url: "api.php",
data: {
action: 'ThemTap',
ketqua: ketqua,
link: link
},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("p").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
</script>
This is my api.php .I think my code is missing or missing in this section and I don't know how to solve it:
<?php
include('../inc/config.php');
if($_POST['action'] == 'ThemTap') {
$ketqua=$_POST['ketqua'];
$string = $ketqua;
$HuuNhan = explode('|',$string);
$link=$_POST['link'];
$stmt = $DBcon->prepare("INSERT INTO tap(tap,link,player) VALUES(N'".$HuuNhan[0]."', N'$link',N'".$HuuNhan[1]."')");
mysqli_query($conn,"UPDATE phim SET updatephim = updatephim + 1 WHERE link = '$link'");
if($stmt->execute())
{
if (mysqli_query($conn, $sql)) {
}
$res="<div class='alert alert-success'>Đã thêm tập <b>".$HuuNhan[0]."</b> thành công !</div>";
echo json_encode($res);
}
else {
$error="<div class='alert alert-danger'>Thêm không thành công</div>";
echo json_encode($error);
}
}
?>
I tried running it as follows:
From text area
EP1|Link1
EP2|Link2
EP3|Link3
But it only inserts a row:
EP1|Link
And not insert EP2|Link2 and EP3|Link3
Please correct my source code so I can add many different rows, thank you very much!
I want to organize the selection query from index.php to action, so i can be able to call the file with ajax to show the data on the page.(index.php). So, the activity I want to do is to able to submit data of the form to the database and to display result on the same page(index.php) without refreshing the page. Help please
Here's my files
1.action.php
2.index.php
3.maker.js
//-----------------------action.php-----------------------------
<?php
include ("db_connect.php"); // Connecting to the database
$user = $_REQUEST['user'];
$text = $_REQUEST['text'];
$ParentId = $_REQUEST['ParentId'];
$action = $_REQUEST['action'];
if ($action=="add")
{
$query="INSERT into `comments` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW())";
$result = mysqli_query($conn,$query);
}
if ($action=="delete")
{
$delete = "DELETE FROM `comments` WHERE id=$text";
$result = mysqli_query ($conn,$delete);
}
?>
//index.php
<div id="table_content"></div>
<script type="text/javascript" src="maker.js">
<?php
function ShowForm($AnswerCommentId)
{ ?>
<form id="myForm">
<input type="hidden" name="comment_on" id="comment_on" readonly="readonly" value="<?php print md5($_SERVER['PHP_SELF']); ?>" />
<input id="user" name="user" value="name" autocomplete="off" onfocus="if(this.value == 'name'){this.value = ''}" onblur="if(this.value == ''){this.value = 'name'}"/>
<textarea id='text' name='text' value="comment" onfocus="if(this.value == 'comment'){this.value = ''}" onblur="if(this.value == ''){this.value = 'comment'}" ></Textarea>
<input id="ParentId" name="ParentId" type="hidden" value="<?php echo($AnswerCommentId);?>"/>
<button type='button' OnClick=SendComment()>Comment</button>
</form>
<?php
}
$query="SELECT * FROM `comments` ORDER BY id ASC";
$result = mysqli_query($conn,$query);
if (isset($_REQUEST['AnswerId']))
{ $AnswerId = $_REQUEST['AnswerId']; }
else
{ $AnswerId = 0; }
$i=0;
while ($mytablerow = mysqli_fetch_row($result))
{
$mytable[$i] = $mytablerow;
$i++;
}
function tree($treeArray, $level, $pid = 0)
{
global $AnswerId;
if (! $treeArray)
{ return; }
foreach($treeArray as $item){
if ($item[1] == $pid)
{
?>
<div class="CommentWithReplyDiv" style="margin-left:<?php echo($level*60);?>px">
<div class="CommentDiv">
<pre class="Message"><?php echo($item[3]) ; ?></pre>
<div class="User"><?php echo($item[2]) ; ?></div>
<div class="Date"><?php echo($item[4]) ; ?></div>
<?php
if ($level<=4) { echo 'Reply'; }
echo 'Delete';
?> </div> <?php
if ($AnswerId == $item[0])
{
?><div id="InnerDiv"><?php ShowForm($AnswerId); ?></div>
<?php
}
?> </div> <?php
tree($treeArray, $level+1, $item[0]); // Recursion
}
}
}
tree($mytable, 0);
?>
//maker.js
function DeleteComment(number){
$.ajax({
type: "POST",
url: "action.php",
data: "user=1"+"&text="+number+"&ParentId=1"+"&action=delete",
success: function(html){
$("#table_content").html(html);
}
});
}
function AnswerComment (id){
$.ajax({
type: "POST",
url: "index.php",
data: "AnswerId="+id,
success: function(html){
$("#table_content").html(html);
}
});
}
function SendComment (){
var user1 = $("#user").val();
var text1 = $("#text").val();
var ParentId1 = $("#ParentId").val() + "";
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",
success: function(html){
$("#table_content").html(html);
clean_form();
}
});
return false;
}
So you are basically trying to make ajax based comment system, From what i see, your code organization is not clear based on there tasks, specifically your index.php file so here is what you can do to simplify things :
your action.php should hanlde all php database releted tasks
Move your html code to some other file (Create Template)
Here is the modified code that i have come up with (This is just for your reference, you should modify this accoring to you needs, and as Xorifelse suggested in comment you should always use prepared statements in production system because of security concerns):
Action.php
<?php
include ("db_connect.php"); // Connecting to the database
$action = $_REQUEST['action'];
if ($action=="add")
{
$user = $_REQUEST['user'];
$text = $_REQUEST['text'];
$ParentId = $_REQUEST['ParentId'];
$query="INSERT into `comments` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW())";
$result = mysqli_query($conn,$query);
}
if ($action=="delete")
{
$text = $_REQUEST['text'];
$delete = "DELETE FROM `comments` WHERE id=$text";
$result = mysqli_query ($conn,$delete);
}
if ($action=="get")
{
$query="SELECT * FROM `comments` ORDER BY id ASC";
$result = mysqli_query($conn,$query);
if (isset($_REQUEST['AnswerId']))
{ $AnswerId = $_REQUEST['AnswerId']; }
else
{ $AnswerId = 0; }
$i=0;
$mytable = array();
while ($mytablerow = mysqli_fetch_row($result))
{
$mytable[$i] = $mytablerow;
$i++;
}
tree($mytable, 0, $AnswerId);
}
function tree($treeArray, $level, $ansId, $pid = 0)
{
$AnswerId = $ansId;
if (! $treeArray)
{ return; }
foreach($treeArray as $item){
if ($item[1] == $pid)
{
include('comments.template.php');
tree($treeArray, $level+1,$AnswerId, $item[0]); // Recursion
}
}
}
?>
index.php
<html>
<head>
<title>Test page</title>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script type="text/javascript" src="maker.js"></script>
</head>
<body onload="loadComments();">
<div id="table_content">
</div>
</body>
</html>
comments.template.php
<div class="CommentWithReplyDiv" style="margin-left:<?php echo($level*60); ?>px">
<div class="CommentDiv">
<pre class="Message"><?php echo($item[3]) ; ?></pre>
<div class="User"><?php echo($item[2]) ; ?></div>
<div class="Date"><?php echo($item[4]) ; ?></div>
<?php
if ($level<=4) {
echo 'Reply';
}
echo 'Delete';
?>
</div>
<?php if ($AnswerId == $item[0]) { ?>
<div id="InnerDiv"><?php include('commentForm.template.php'); ?></div>
<?php } ?>
commentForm.template.php
<form id="myForm">
<input type="hidden" name="comment_on" id="comment_on" readonly="readonly" value="<?php print md5($_SERVER['PHP_SELF']); ?>" />
<input id="user" name="user" value="name" autocomplete="off" onfocus="if(this.value == 'name'){this.value = ''}" onblur="if(this.value == ''){this.value = 'name'}"/>
<textarea id='text' name='text' value="comment" onfocus="if(this.value == 'comment'){this.value = ''}" onblur="if(this.value == ''){this.value = 'comment'}" ></Textarea>
<input id="ParentId" name="ParentId" type="hidden" value="<?php echo($AnswerId);?>"/>
<button type='button' OnClick="SendComment()">Comment</button>
</form>
marker.js
function DeleteComment(number){
$.ajax({
type: "POST",
url: "action.php",
data: "user=1"+"&text="+number+"&ParentId=1"+"&action=delete",
success: function(html){
$("#table_content").html(html);
loadComments();
}
});
}
function AnswerComment (id){
$.ajax({
type: "POST",
url: "action.php",
data: "AnswerId="+id+"&action=get",
success: function(html){
$("#table_content").html(html);
}
});
}
function SendComment (){
var user1 = $("#user").val();
var text1 = $("#text").val();
var ParentId1 = $("#ParentId").val() + "";
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",
success: function(html){
$("#table_content").html(html);
loadComments();
}
});
return false;
}
function loadComments (){
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "action=get",
success: function(html){
$("#table_content").html(html);
//clean_form();
}
});
return false;
}
Hello frndz i need a help i am trying to add detail by my form but no getting any value..and error is reflecting as "add request fails"..can anyone solve my error i am not getting what to do for this.. ther is my code
webapp.js
// Add company button
$(document).on('click', '#add_employee', function(e){
e.preventDefault();
$('.lightbox_content h2').text('Add Employee');
$('#form_employee button').text('Add');
$('#form_employee').attr('class', 'form add');
$('#form_employee').attr('data-id', '');
$('#form_employee .field_container label.error').hide();
$('#form_employee .field_container').removeClass('valid').removeClass('error');
$('#form_employee #ID').val('');
$('#form_employee #Name').val('');
$('#form_employee #Lastname').val('');
$('#form_employee #Email').val('');
$('#form_employee #Username').val('');
$('#form_employee #Password').val('');
$('#form_employee #Mobile').val('');
$('#form_employee #Website').val('');
show_lightbox();
});
// Add company submit form
$(document).on('submit', '#form_employee.add', function(e){
e.preventDefault();
// Validate form
if (form_employee.valid() == true){
// Send company information to database
hide_ipad_keyboard();
hide_lightbox();
show_loading_message();
var form_data = $('#form_employee').serialize();
var request =
$.ajax({
url: 'data.php',
cache: false,
data: {job:"add_employee",form_data},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
request.done(function(output){
if (output.result == 'success'){
// Reload datable
table_employee.api().ajax.reload(function(){
hide_loading_message();
var Name = $('#Name').val();
show_message("Employee Name '" + Name + "' added successfully.", 'success');
}, true);
} else {
hide_loading_message();
show_message('Add request failed', 'error');
}
});
request.fail(function(jqXHR, textStatus){
hide_loading_message();
show_message('Add request failed: ' + textStatus, 'error');
});
}
});
data.php
<?php
// Database details
$db_server = 'localhost';
$db_username = 'root';
$db_password = '';
$db_name = 'example1';
// Get job (and id)
$job = '';
$id = '';
if (isset($_GET['job'])){
$job = $_GET['job'];
if ($job == 'get_employee' ||
$job == 'get_employee_detail' ||
$job == 'add_employee' ||
$job == 'edit_employee' ||
$job == 'delete_employee'){
if (isset($_GET['id'])){
$id = $_GET['id'];
if (!is_numeric($id)){
$id = '';
}
}
} else {
$job = '';
}
}
// Prepare array
$mysql_data = array();
// Valid job found
if ($job != ''){
// Connect to database
$db_connection = mysqli_connect($db_server, $db_username, $db_password, $db_name);
if (mysqli_connect_errno()){
$result = 'error';
$message = 'Failed to connect to database: ' . mysqli_connect_error();
$job = '';
}
if ($job == 'add_employee'){
// Add company
$query = "INSERT INTO employees SET ";
if (isset($_GET['ID'])) { $query .= "ID = '" . mysqli_real_escape_string($db_connection, $_GET['ID']) . "', "; }
if (isset($_GET['Name'])) { $query .= "Name = '" . mysqli_real_escape_string($db_connection, $_GET['Name']) . "', "; }
if (isset($_GET['Lastname'])) { $query .= "Lastname = '" . mysqli_real_escape_string($db_connection, $_GET['Lastname']). "', "; }
if (isset($_GET['Email'])) { $query .= "Email = '" . mysqli_real_escape_string($db_connection, $_GET['Email']) . "', "; }
if (isset($_GET['Username'])) { $query .= "Username = '" . mysqli_real_escape_string($db_connection, $_GET['Username']). "', "; }
if (isset($_GET['Password'])) { $query .= "Password = '" . mysqli_real_escape_string($db_connection, $_GET['Password']). "', "; }
if (isset($_GET['Mobile'])) { $query .= "Mobile = '" . mysqli_real_escape_string($db_connection, $_GET['Mobile']) . "', "; }
if (isset($_GET['Website'])) { $query .= "Website = '" . mysqli_real_escape_string($db_connection, $_GET['Website']) . "'"; }
$query = mysqli_query($db_connection, $query);
if (!$query){
$result = 'error';
$message = 'add Employee error';
} else {
$result = 'success';
$message = 'Employees added success';
}
// Close database connection
mysqli_close($db_connection);
}
// Prepare data
$data = array(
"result" => $result,
"message" => $message,
"data" => $mysql_data
);
// Convert PHP array to JSON array
$json_data = json_encode($data);
print $json_data;
?>
**index.html**
<!doctype html>
<html lang="en" dir="ltr">
<head>
<title>Table</title>
<meta charset="utf-8">
<meta name="viewport" content="width=1000, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Oxygen:400,700">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel="stylesheet" href="design.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script charset="utf-8" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script charset="utf-8" src="//cdn.datatables.net/1.10.0/js/jquery.dataTables.js"></script>
<script charset="utf-8" src="http://cdn.jsdelivr.net/jquery.validation/1.13.1/jquery.validate.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"> </script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>
<script charset="utf-8" src="webapp.js"></script>
</head>
<body>
<div id="page_container">
<h1>Details of Employees</h1>
<button type="button" class="button" id="add_employee">Add Employees</button>
<table class="datatable" id="table_employee">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Lastname</th>
<th>Email</th>
<th>Username</th>
<th>Password</th>
<th>Mobile No</th>
<th>Website</th>
<th>Functions</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="lightbox_bg"></div>
<div class="lightbox_container">
<div class="lightbox_close"></div>
<div class="lightbox_content">
<h2>Add Employees</h2>
<form class="form add" id="form_employee" data-id="" novalidate>
<div class="input_container">
<label for="Name">Name: <span class="required">*</span></label>
<div class="field_container">
<input type="text" class="text" name="Name" id="Name" value="" required>
</div>
</div>
<div class="input_container">
<label for="Lastname">Lastname: <span class="required">*</span></label>
<div class="field_container">
<input type="text" class="text" name="Lastname" id="Lastname" value="" required>
</div>
</div>
<div class="input_container">
<label for="Email">Email: <span class="required">*</span></label>
<div class="field_container">
<input type="text" class="text" name="Email" id="Email" value="" required>
</div>
</div>
<div class="input_container">
<label for="Username">Username: <span class="required">*</span></label>
<div class="field_container">
<input type="text" class="text" name="Username" id="Username" value="" required>
</div>
</div>
<div class="input_container">
<label for="Password">Password: <span class="required">*</span></label>
<div class="field_container">
<input type="password" class="text" name="Password" id="Password" value="" placeholder="eg. X8df90EO" required>
</div>
</div>
<div class="input_container">
<label for="Mobile">Mobile: <span class="required">*</span></label>
<div class="field_container">
<input type="text" class="text" name="Mobile" id="Mobile" maxlength="10" pattern="[7-9]{1}[0-9]{9}" placeholder="Only 10 digit Mobile no"required>
</div>
</div>
<div class="input_container">
<label for="Website">Website: <span class="required">*</span> </label>
<div class="field_container">
<input type="text" class="text" name="Website" id="Website" value="" placeholder="https://www.domain.com" required>
</div>
</div>
<div class="button_container">
<button type="submit">Add Employees</button>
</div>
</form>
</div>
</div>
<div id="message_container">
<div id="message" class="success">
<p>This is a success message.</p>
</div>
</div>
<div id="loading_container">
<div id="loading_container2">
<div id="loading_container3">
<div id="loading_container4">
Loading, please wait...
</div>
</div>
</div>
</div>
</body>
</html>
Change your submit HTML code to <input type="submit" value="Add Employees"></input>
And use my javascript source
<script type="text/javascript">
$( "#form_employee" ).submit(function( event ) {
var data = $(this).serializeArray();
data.push(
{name: "job", value: "add_employee"}
);
data = JSON.stringify(data);
$.ajax({
type: "POST",
url: "jsOnChange.php", //Set-Your-URL-Here
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
error: function(e)
{
alert(JSON.stringify(e, null, 4));
},
success: function(strDrivers){
alert(JSON.stringify(strDrivers, null, 4));
}
});
});
</script>
In .php listener
<?php
ini_set("allow_url_fopen", true);
$jsonStr = file_get_contents("php://input"); //read the HTTP body.
echo $jsonStr;
?>
You will get
Hope this help!!!
I think you code have some mistake at this place
var form_data = $('#form_employee').serialize();
var request =
$.ajax({
url: 'data.php',
cache: false,
data: {job:"add_employee",form_data},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
Replace it with
var form_data = $('#form_employee').serialize();
form_data.job='add_employee';
var request =
$.ajax({
url: 'data.php',
cache: false,
data: form_data,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
type: 'get'
});
Also in PHP side before print json_encode string add ob_clean() because you have mentioned dataType: json in ajax request.
ob_clean();
// Convert PHP array to JSON array
$json_data = json_encode($data);
print $json_data;
I am trying to upload multiple files with different title but unable to get uploaded file names.
Here is my html code.
<div class="nav-md" ng-app="fileuploadModule">
<div class="container body" ng-controller="fileuploadController as parentCtrl">
<div class="form-group">
<div class="col-sm-6" style="padding:0px 10px 0px 0px;">
<label class="control-label">ID-NO</label>
<input type="text" class="form-control" id="idno" ng-model="idno" />
</div>
<div class="col-sm-6" style="padding:0px 10px 0px 0px;">
<label class="control-label" >Name</label>
<input type="text" class="form-control" id="pname" ng-model="pname" />
</div>
</div>
<div class="form-group" ng-controller="ChildController as childCtrl">
<div class="col-md-12" style="padding:0px 10px 0px 0px;">
<table ng-table="tableParams" class="display table table-striped table-bordered">
<thead>
<tr>
<th width="5%">Sr.No</th>
<th width="35%">Title</th>
<th width="35%">Upload Report</th>
<th width="25%"></th>
</tr>
</thead>
<tbody>
<tr ng-repeat="cap in data">
<td>{{$index+1}}</td>
<td>
<input class="form-control" id="tags" type="text" ng-model="cap.name" placeholder="Title" typeahead="drug.name for drug in drugArray | filter:$viewValue | limitTo:4">
</td>
<td>
<input type="file" id="i_file" name="file" ng-model="cap.file" ng-file-select="onFileSelect($files)" />
<input type="hidden" ng-model="cap.message" value={{message}} />
</td>
<td>
<input type="submit" ng-click="addFormField()" class="btn btn-default" value="Add Items" />
<input type="submit" value="Remove" class="btn btn-primary" ng-click="removeRow(cap.name)" />
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
Here is the angularjs Script.
//reports upload
var infu = angular.module('fileuploadModule',['angularFileUpload','angularUtils.directives.dirPagination','ui.bootstrap'])
infu.controller('fileuploadController', function ($scope, $http)
{
/*Add & Remove Script Starts Here*/
//to remove the row
$scope.removeRow = function(name) {
var index = -1;
var comArr = eval( $scope.data );
for( var i = 0; i < comArr.length; i++ ) {
if( comArr[i].name ==name ) {
index = i;
break;
}
}
if( index === -1 ) {
}
$scope.data.splice( index, 1 );
};
//dynamic row creation
$scope.data = [{}];
//Autocomplete for title
$scope.drugArray = [];
$http({method: 'GET',url: 'get_test_name.php',data: { applicationId: 3 }}).success(function (data) {
$scope.drugArray = data;
});
$scope.addFormField = function() {
$scope.data.push({});
}
/*Add & Remove Script Ends Here*/
//Updated Investigation
$scope.submitData = function()
{
var comArr = eval( $scope.data );
var name=new Array();
var file=new Array();
var message=new Array();
for( var i = 0; i < comArr.length; i++ )
{
name.push(comArr[i].name);
file.push(comArr[i].file);
message.push(comArr[i].message);
}
var answer = confirm("Do you want to Submit?")
if (!answer)
{
}
else
{
$http.post('update_details.php', {
'idno': $scope.idno,
'pname': $scope.pname,
'name': name,
'file': file,
'message': message,
/*'filename': $scope.parentCtrl.childCtrl.message //If i give like getting only last upload file name*/
})
.success(function (data, status, headers, config)
{
alert("Data has been Added Successfully");
window.location.href="list_investigation_reports.php";
})
.error(function(data, status, headers, config)
{
});
}
}
});
//ChildController For file Upload
infu.controller('ChildController',function ($scope, $http, $upload) {
$scope.parentCtrl.childCtrl = $scope.childCtrl;
$scope.onFileSelect = function($files) {
$scope.message = "";
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
console.log(file);
$scope.upload = $upload.upload({
url: 'upload.php',
method: 'POST',
file: file
}).success(function(data, status, headers, config) {
$scope.message = data;
$scope.message=$scope.message.replace('\"', '');
$scope.childCtrl.message=$scope.message.replace('\"', '');
}).error(function(data, status) {
$scope.message = data;
});
}
};
});
Here is php code for file upload
<?php
$target_dir = "uploadfiles/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
$result = array("filename" => $_FILES["file"]);
$filename = $result['filename']['name'];
echo json_encode($filename);
?>
Here is the final code to insert details into database.
$data = json_decode(file_get_contents("php://input"));
$idno = $data->idno;
$pname = $data->pname;
$tname = $data->name;
$filename = $data->file;
$message = $data->message;
$date=date('Y-m-d');
foreach($tname as $index => $value)
{
$name1 = $tname[$index];
$filename1 = $filename[$index];
$message1 = $message[$index];
$qry_ress = $dbConnection->prepare("INSERT INTO tablename(idno,pname,testname,filename,cts) VALUES (?,?,?,?,?)");
$qry_ress->execute(array($idno,$pname,$name1,$filename1,$cts));
$arr = array("idno" => "$idno","pname" => "$pname","TestName" => "$name1","FileName" => "$filename1");
$jsn = json_encode($arr);
echo $jsn;
}
Getting Result as below
{"idno":"20","pname":"Vijay","TestName":"OCT","FileName":"","Message":""}{"idno":"25","pname":"Salim","TestName":"FFA","FileName":"","Message":""}
Getting above result data except uploaded file. Please help me to solve this issue.
Thanks in advance.
JS
var app = angular.module('br', []);
app.controller('LoginCtrl', function($scope, $http) {
$scope.valid = function() {
var request = $http({
method: "post",
url: "php_files/login.php",
data: {
em: $scope.em,
pw: $scope.pw
},
});
request.success(function(data) {
if (data == "invalid") {
$scope.message = "Invalid email id or password!"
}
});
}
});
HTML
<body ng-controller="LoginCtrl">
<form method="post">
<table>
<tr>
<td>Email</td>
<td><input type="email" required="required" ng-model="em"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" required="required" ng-model="pw" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Login" ng-click="valid()"/></td>
</tr>
<tr>
<td colspan="2" align='center' style="color: red">{{message}}</td>
</tr>
</table>
</form>
</body>
PHP script
include './include_db.php';
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$em = $request->em;
$pw = $request->pw;
$query = "select em,pw from users where em='$em' and pw='$pw'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$got_em = $row["em"];
$got_pw = $row["pw"];
if ($em != $got_em && $pw != $got_pw) {
echo "invalid";
} else {
session_start();
$_SESSION["em"] = $em;
header("Location:home.html");
}
Now what I want is if the email id and password is wrong it should return invalid which is working but if they are correct it should redirect to home page which is not working.
in php_files/login.php:
if(!valid($username,$password)){
die("invalid");
} else {
die("https://logged_in_address");
}
in your javascript
request.success(function(data) {
if (data == "invalid") {
$scope.message = "Invalid email id or password!"
} else {
window.location.replace(data);
/*redirect to the logged in page provided by login.php */
}
});