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;
Related
This is a commenting system using jQuery, Ajax, PHP, MySQL, and HTML. When I click the Edit button, it displays the comment of the first row of the table of MySQL instead of the row that I selected. However, once I edit it, it does correct the correct row. I can’t figure out a way to display the comment of the row that I want to edit.
I can display the correct comment_id of the row into the textarea, but it displays the comment of the first row into the textarea.
Here is the test case code:
MySQL table has two rows: comment_id as primary row and comment for text. I named the database: testcaseedit_db, and the table: tbl_comment.
index.php
<?php $connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', ''); ?>
<div id="display_comment"></div>
<div id="comment_message"></div>
<div id="display_edit"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
let count = 0;
$(document).on('click change', '.edit, .submit', function(e) {
if ($(this).is('.edit')) {
var comment_id = $(this).attr("id");
$('#comment_id').val(comment_id);
var closestDiv = $('button').closest('div.panel');
$('.div.panel').not(closestDiv.next('.div.panel')).hide();
closestDiv.next('div.panel').slideToggle(100);
var commentEdit = $('#display_comment').find('#editable').html();
++count;
const htmlString =
`<form id="comment_form${count}" class="input-group form-row" action="edit.php" method="post" enctype="multipart/form-data">
<div class="input-group-prepend">
<textarea name="comment" id="comment${count}" class="form-control" rows="30" cols="160">
${commentEdit} ${comment_id}
</textarea>
</div>
<div class="input-group-prepend">
<input type="hidden" name="comment_id" id="comment_id" value="${comment_id}" />
<input type="submit" name="submit" id="submit" class="submit btn btn-info" value="Save" form="comment_form${count}" />
</div>
</form>`;
$('#display_comment')[0].insertAdjacentHTML('afterend', htmlString);
} else if ($(this).is('.submit')) {
$.ajax({
url:"edit.php",
method:"POST",
data: new FormData(this),
contentType: false,
processData: false,
success:function(data)
{
if(data.error != '') {
$('#comment_form')[0].reset();
$('#comment_id').val(comment_id);
$('#comment').val(comment);
}
}
});
location.reload();
$(this).closest('form').submit();
e.stopPropagation();
} else {
return false;
}
});
// Fetch comment
function load_comment(){
$.ajax({
url:"fetch.php",
method:"POST",
success:function(data){
$('#display_comment').html(data);
}
})
};
load_comment();
// End of (document).ready(function){}
});
</script>
</body>
</html>
fetch.php
<?php
$connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', '');
$query = "
SELECT * FROM tbl_comment WHERE comment_id = comment_id
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row) {
$output .= '
<div class="panel panel-default">
<div class="panel-heading"> <b> comment_id: </b> '.$row["comment_id"].' </div>
<div class="panel-body"><b> Comment: </b> <br> <span id="editable"> '.$row["comment"].' </span> </div>
<div class="panel-footer" align="right">
<button type="button" class="btn btn-default edit" id="'.$row["comment_id"].'">Edit</button>
</div>
</div>
';
}
echo $output;
?>
edit.php
<?php
$connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', '');
$comment_id = $_POST["comment_id"];
$comment = $_POST["comment"];
if ( $error == '' && !empty($_POST["comment"]) ) {
$query = "UPDATE tbl_comment SET comment = :comment WHERE comment_id = :comment_id ";
$statement = $connect->prepare($query);
$statement->execute(
array(
':comment_id' => $comment_id,
':comment' => $comment
)
);
header("Location: index.php");
}
$data = array(
'error' => $error
);
echo $error;
?>
Here is the solution:
In fetch.php file, I made the id for each variable into an array as follows:
<button type="button" class="btn btn-default edit" id[1]="'.$row["comment_id"].'" id[2]="'.$row["comment"].'">Edit</button>
And in index.php file, I grabbed the value of each variable as follows:
var comment_id = $(this).attr("id[1]");
$('#comment_id').val(comment_id);
var comment = $(this).attr("id[2]");
$('#comment').val(comment);
Then I displayed the comment variable inside the textarea as follows:
<textarea name="comment" id="comment${count}" class="form-control" rows="15" cols="120">${comment}</textarea>
Here is the full code for index.php and fetch.php. I left edit.php untouched:
index.php
<?php $connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', ''); ?>
<div id="display_comment"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
let count = 0;
$(document).on('click change', '.edit, .submit', function(e) {
if ($(this).is('.edit')) {
var comment_id = $(this).attr("id[1]");
$('#comment_id').val(comment_id);
var comment = $(this).attr("id[2]");
$('#comment').val(comment);
var closestDiv = $('button').closest('div.panel');
$('div.panel').not(closestDiv.next('div.panel')).hide();
closestDiv.next('div.panel').slideToggle(100);
++count;
const htmlString =
`<form id="comment_form${count}" class="input-group form-row" action="edit.php" method="post" enctype="multipart/form-data">
<div class="input-group-prepend">
<textarea name="comment" id="comment${count}" class="form-control" rows="15" cols="120">
${comment}
</textarea>
</div>
<div class="input-group-prepend">
<input type="hidden" name="comment_id" id="comment_id" value="${comment_id}" />
<input type="submit" name="submit" id="submit" class="submit btn btn-info" value="Save" form="comment_form${count}" />
</div>
</form>`;
$('#display_comment')[0].insertAdjacentHTML('afterend', htmlString);
} else if ($(this).is('.submit')) {
$.ajax({
url:"edit.php",
method:"POST",
data: new FormData(this),
contentType: false,
processData: false,
success:function(data)
{
if(data.error != '') {
$('#comment_form')[0].reset();
$('#comment_id').val(comment_id);
$('#comment').val(comment);
}
}
});
location.reload();
$(this).closest('form').submit();
e.stopPropagation();
} else {
return false;
}
});
// Fetch comment
function load_comment(){
$.ajax({
url:"fetch.php",
method:"POST",
success:function(data){
$('#display_comment').html(data);
}
})
};
load_comment();
// End of (document).ready(function){}
});
</script>
</body>
</html>
fetch.php
<?php
$connect = new PDO('mysql:host=localhost;dbname=testcaseedit_db', 'root', '');
$query = "
SELECT * FROM tbl_comment WHERE comment_id = comment_id
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '';
foreach($result as $row) {
$output .= '
<div class="panel panel-default">
<div class="panel-heading"> <b> comment_id: </b> '.$row["comment_id"].' </div>
<div class="panel-body"><b> Comment: </b> <br> '.$row["comment"].' </div>
<div class="panel-footer" align="right">
<button type="button" class="btn btn-default edit" id[1]="'.$row["comment_id"].'" id[2]="'.$row["comment"].'">Edit</button>
</div>
</div>
';
}
echo $output;
?>
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 have this form
<form id="home" class="validate-form" method="post" enctype="multipart/form-data">
<!-- Form Item -->
<div class="form-group">
<label>How much money do you need? (Kenya Shillings)</label>
<div class="input-group">
<div class="input-group-addon">Ksh</div>
<input id="moneyAmount" type="number" id="amount" name="amount" class="form-control slider-control input-lg" value="100000" min="10000" max="1000000" data-slider="#moneySlider" required>
</div>
<div id="moneySlider" class="form-slider" data-input="#moneyAmount" data-min="10000" data-max="1000000" data-value="100000"></div>
</div>
<!-- Form Item -->
<div class="form-group">
<label>How long? (months)</label>
<div class="input-group">
<input id="monthNumber" type="number" id="duration" name="duration" class="form-control slider-control input-lg" value="10" min="6" max="12" data-slider="#monthSlider" required>
<div class="input-group-addon">months</div>
</div>
<div id="monthSlider" class="form-slider" data-input="#monthNumber" data-min="6" data-max="12" data-value="10"></div>
</div>
<div class="form-group">
<label>Telephone Number</label>
<!-- Radio -->
<input type="number" id="telephone" name="telephone" class="form-control" required/>
</div>
<!-- Form Item -->
<div class="form-group">
<label>3 Months Bank or Paypal or Mpesa Statements</label>
<!-- Radio -->
<input type="file" name="image" class="ml btn btn-primary btn-lg" /><span>Upload</span>
</div>
<!-- Form Item -->
<div class="form-group">
<label>Monthly repayment</label>
<span id="formResult" class="form-total">Ksh<span>262.99</span></span>
</div>
<div class="form-group form-submit">
<button type="submit" class="btn-submit btn-lg"><span>Send a request!
</span></button>
</div>
</form>
This is the Jquery Script.
$( "#home" ).on( "submit", function( event ) {
event.preventDefault();
alert('subsequent clicks');
function chek(fData) {
var reg = new RegExp("^[-]?[0-9]+[\.]?[0-9]+$");
return reg.test(fData)
}
var phone = $('#telephone').val();
var amount = $('#amount').val();
var duration = $('#duration').val();
var ch = chek(phone);
if(phone == ""){
alert('phone cannot be empty');
return;
}
if(amount == ""){
alert('amount cannot be empty');
return;
}
if(duration == ""){
alert('duration cannot be empty');
return;
}
if(ch == false){
alert("Phone number must be a number");
return;
}
if(phone.length < 10 || phone.length > 12 ){
alert("Phone number must have 10 digits");
return;
}
if(ch == true && phone !== "" && amount !== "" && duration !== "" && phone.length == 10){
var s = phone;
s = s.replace(/^0+/, '');
var cc = 254;
var p = cc+s;
var pn = p.toString();
$('#telephone').val(p.toString());
var formData = new FormData($(this)[0]);
$.ajax({
url: 'http://example.com/home.php', //<== just add it to the end of url ***
type: 'POST',
data: formData,
async: true,
success: function (data) {
console.log(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
}
});
This is my PHP code:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
function random_str($length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyz')
{
$str = '';
$max = mb_strlen($keyspace, '8bit') - 1;
for ($i = 0; $i < $length; ++$i) {
$str .= $keyspace[random_int(0, $max)];
}
return $str;
}
$pass = random_str(4);
/**
Generic Customer Shown Interest
*/
$servername = "localhost";
$username = "root";
$password = "123456";
$dbname = "algo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Posted Variables
$amount = $_POST['amount'];
$duration = $_POST['duration'];
$telephone = $_POST['telephone'];
$date = date('Y-m-d H:i:s');
//Check If User Exists
$result = $conn->query("select id from users where telephone=$telephone");
if($result->num_rows == 0) {
//Insert New User
$sql = "INSERT INTO users (telephone, password, service_name,date_submitted) VALUES ('$telephone', '$pass', 'loans','$date')";
if ($conn->query($sql) === TRUE) {
echo "User Is Inserted";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
} else {
//Insert New User
$sql2 = "INSERT INTO loans (amount, duration, telephone,documents,status,date)
VALUES ('$amount', '$duration','$telephone','logan2','on-hold','$date')";
if ($conn->query($sql2) === TRUE) {
echo "Loan Is Inserted";
} else {
echo "Error: " . $sql2 . "<br>" . $conn->error;
}
$conn->close();
}
?>
As you can tell the form is pretty basic and its only posting data to the server. When I load the page, I am able to insert data into the database but when I click the link again, nothing is inserted.
Is form data blocking me from posting duplicate data to the server?
change ajax part of your code and replace to this code shown below:
<script type="text/javascript">
$.ajax({
type:'POST',
url:'testing2.php',
data:new FormData($('#svf-form-4')[0]),
cache: false,
contentType: false,
processData: false,
success:function(msg){
$('#message').html(msg);
}
});
return false;
</script>
Hope it will work .
I cant explain what really worked but it seems clearing the form did allow for more post submission although i relied on this comment What does "async: false" do in jQuery.ajax()?
and this page What does "async: false" do in jQuery.ajax()? for inspiration.
This is the success callback
success: function (data) {
$("#home").trigger('reset');
console.log(data);
},
Sorry to ask it again, but I checked almost all the q&a's on the topic and still couldn't solve it. Here is my form.php and creditform.php
Edit1.Changed the .get to .post
Edit2.I'm getting errors of undefined variable "name" "email" "address" "income" etc (in short for all of them) in creditform.php
What I want to do is just insert all the inputs into the table in db.
HTML
<!-- End crumbs-->
<div class="container wrap wow fadeInUp">
<div class="row">
<div class="col-sm-5 col-md-6 left-app">
<form id="form" action="php/creditform.php" method="post">
<input type="text" placeholder="Name" name="name" required>
<input type="email" placeholder="Email" name="email" required>
<input type="text" placeholder="Address" name="address" required>
<input type="number" placeholder="Monthly income before taxes" name="income" required>
<input type="number" placeholder="Amount Needed" name="amount_needed" required>
<input type="number" placeholder="Phone" name="phone" required>
<div class="row">
<div class="container">
<input type="submit" name="submit" value="Submit" class="button"></div></div>
<div id="result"></div>
</form>
</div>
<script>
$(document).ready(function($) {
'use strict';
$('#form').submit(function(event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = $(this).serialize();
$.post(url, datos, function(resultado) {
$('#result').html(resultado);
});
});
</script>
FORM.PHP
<?php
include('db.config.php');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $email = $address = $income = $amount_needed = $phone = '';
if(isset($_POST['submit'])){
$name = addslashes($_POST['name']);
$email = addslashes($_POST['email']);
$address = addslashes($_POST['address']);
$income = addslashes($_POST['income']);
$amount_needed = addslashes($_POST['amount_needed']);
$phone = addslashes($_POST['phone']);
// check form fields
if(empty($name)){
$error .= 'Enter name <br />';
}
if(empty($email)){
$error .= 'Enter email <br />';
}
// check if errors exist
if(!empty($error)){
echo $error;
} else {
// process form as normal
$sql = "INSERT INTO `" . DBN . "`.`creditapp` (`name`, `email`, `address`, `income`, `amount_needed`, `phone`) VALUES ('$name', '$email', '$address', '$income', '$amount_needed', '$phone')";
$db->Query($sql);
}
}
}
print_r($_POST);
?>
CREDITFORM.PHP
<?php
if(isset($_POST['submit'])){
$name = $_POST['name'];
$email = $_POST['email'];
$address = $_POST['address'];
$income = $_POST['income'];
$amount_needed = $_POST['amount_needed'];
$phone = $_POST['phone'];
}
print_r($_POST);
?>
It's obvious that I'm missing something, please correct me...
Thanks for your time
You need to send a POST request for the $_POST array to have anything in it.
$.get(url, datos, function(resultado) {
$('#result').html(resultado);
});
This sends a GET request (check $_GET). You want to use $.post here instead.
$.post(url, datos, function(resultado) {
$('#result').html(resultado);
});
Here is a simple Ajax call to a Php File by an event : Click on a button.
In your example you must use POST method because you use :
$_POST['something'];
Javascript client side :
$("body").on("click", "#mybutton", function() {
var mydata = $("#form").serialize();
$.ajax({
type: "POST",
url: "/api/api.php",
data: {data : mydata},
timeout: 6e3,
error: function(a, b) {
if ("timeout" == b) $("#err-timedout").slideDown("slow"); else {
$("#err-state").slideDown("slow");
$("#err-state").html("An error occurred: " + b);
}
},
success: function(a) {
var e = $.parseJSON(a);
if (true == e["success"]) {
$("#result").html(e['message']);
// here is what you want, callback Php response content in Html DOM
}
}
});
return false;
});
Next in your Php code simply do after any success function :
if ($result) {
echo json_encode(array(
'success' => true,
'msg' => "Nice CallBack by Php sent to client Side by Ajax Call"
));
}
Okay, I practiced more on ajax - json - php and in the end this was my solution and my latest code.
Thanks for all answers and suggestions. Hope this also helps to someone.
Still open to any kind of advice to improve.
<?php
include('db.config.php');
if(isset($_POST['submit'])){
$name = addslashes($_POST['name']);
$email = addslashes($_POST['email']);
$address = addslashes($_POST['address']);
$income = addslashes($_POST['income']);
$amount_needed = addslashes($_POST['amount_needed']);
$phone = addslashes($_POST['phone']);
// process form as normal
$sql = "INSERT INTO `" . DBN . "`.`creditapp` (`name`, `email`, `address`, `income`, `amount_needed`, `phone`) VALUES ('$name', '$email', '$address', '$income', '$amount_needed', '$phone')";
$db->Query($sql);
die();
<div class="container wrap wow fadeInUp">
<div class="row">
<div class="col-sm-5 col-md-6 left-app">
<form id="form" action="creditapp.php" method="post">
<input type="text" placeholder="Name" name="name" id="name" required>
<input type="email" placeholder="Email" name="email" id="email" required>
<input type="text" placeholder="Address" name="address" id="address" required>
<input type="text" placeholder="Monthly income before taxes" id="income" name="income" required>
<input type="text" placeholder="Amount Needed" name="amount_needed" id="amount_needed" required>
<input type="text" placeholder="Phone" name="phone" id="phone" required>
<div class="row">
<div class="container">
<input type="submit" name="submit" value="Submit" class="button sub"></div>
</div>
</form>
</div>
<script>
$(document).ready(function() {
$('.sub').click(function(e){
e.preventDefault();
var name = $('#name').val(),
email = $('#email').val(),
address = $('#address').val(),
income = $('#income').val(),
amount_needed = $('#amount_needed').val(),
phone = $('#phone').val();
$.ajax({
url: "creditapp.php",
type: "POST",
data: {
name: name,
email: email,
address: address,
income: income,
amount_needed: amount_needed,
phone: phone,
submit: "submit"
}
}).done(function(msg){
$('.right-info').html('<pre>' + msg + '</pre>');
})
})
});
</script>
The problem you are having is with your javascript. You wait for the submit and than you do an ajax GET request, you need a POST.
<script>
$(document).ready(function($) {
'use strict';
$('#form').submit(function(event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = $(this).serialize();
$.post(url, datos, function(resultado) {
$('#result').html(resultado);
});
});
</script>
I need a little help to send notification to all devices at once.
I know array need to be used for that but can't get the idea. A little hint will also work
DB table design
id gcm_regid name email created_at
Currently i have to fill out the form for all the devices and send notification one by one.
PHP code:
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
});
function sendPushNotification(id){
var data = $('form#'+id).serialize();
$('form#'+id).unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
</head>
<body>
<?php
include_once 'db_functions.php';
$db = new DB_Functions();
$users = $db->getAllUsers();
if ($users != false)
$no_of_users = mysql_num_rows($users);
else
$no_of_users = 0;
?>
<div class="container">
<h1>No of Devices Registered: <?php echo $no_of_users; ?></h1>
<hr/>
<ul class="devices">
<?php
if ($no_of_users > 0) {
?>
<?php
while ($row = mysql_fetch_array($users)) {
?>
<li>
<form id="<?php echo $row["id"] ?>" name="" method="post" onsubmit="return sendPushNotification('<?php echo $row["id"] ?>')">
<label>Name: </label> <span><?php echo $row["name"] ?></span>
<div class="clear"></div>
<label>Email:</label> <span><?php echo $row["email"] ?></span>
<div class="clear"></div>
<div class="send_container">
<textarea rows="3" name="message" cols="25" class="txt_message" placeholder="Type message here"></textarea>
<input type="hidden" name="regId" value="<?php echo $row["gcm_regid"] ?>"/>
<input type="submit" class="send_btn" value="Send" onclick=""/>
</div>
</form>
</li>
<?php }
} else { ?>
<li>
No Users Registered Yet!
</li>
<?php } ?>
</ul>
</div>
</body>
send_message.php
<?php
if (isset($_GET["regId"]) && isset($_GET["message"])) {
$regId = $_GET["regId"];
$message = $_GET["message"];
include_once './GCM.php';
$gcm = new GCM();
$registatoin_ids = array($regId);
$message = array("price" => $message);
$result = $gcm->send_notification($registatoin_ids, $message);
echo $result;
}
?>
EDIT: Or can anyone tell me how do i use checkbox for select all "id"s?