PHP jQuery ajax submit button not working - php

I would like to create a dynamic form with add and remove field using jquery and ajax. but unfortunately,my insert button supposedly go to insert.php wont work.When I click insert button,nothing is happened. When the insert button clicked,it will be redirect to insert.php store data inside the database.Here is my coding
repeater.js
jQuery.fn.extend({
createRepeater: function (options = {}) {
var hasOption = function (optionKey) {
return options.hasOwnProperty(optionKey);
};
var option = function (optionKey) {
return options[optionKey];
};
var generateId = function (string) {
return string
.replace(/\[/g, '_')
.replace(/\]/g, '')
.toLowerCase();
};
var addItem = function (items, key, fresh = true) {
var itemContent = items;
var group = itemContent.data("group");
var item = itemContent;
var input = item.find('input,select');
input.each(function (index, el) {
var attrName = $(el).data('name');
var skipName = $(el).data('skip-name');
if (skipName != true) {
$(el).attr("name", group + "[" + key + "]" + "[" + attrName + "]");
} else {
if (attrName != 'undefined') {
$(el).attr("name", attrName);
}
}
if (fresh == true) {
$(el).attr('value', '');
}
$(el).attr('id', generateId($(el).attr('name')));
$(el).parent().find('label').attr('for', generateId($(el).attr('name')));
})
var itemClone = items;
/* Handling remove btn */
var removeButton = itemClone.find('.remove-btn');
if (key == 0) {
removeButton.attr('disabled', true);
} else {
removeButton.attr('disabled', false);
}
removeButton.attr('onclick', '$(this).parents(\'.items\').remove()');
var newItem = $("<div class='items'>" + itemClone.html() + "<div/>");
newItem.attr('data-index', key)
newItem.appendTo(repeater);
};
/* find elements */
var repeater = this;
var items = repeater.find(".items");
var key = 0;
var addButton = repeater.find('.repeater-add-btn');
items.each(function (index, item) {
items.remove();
if (hasOption('showFirstItemToDefault') && option('showFirstItemToDefault') == true) {
addItem($(item), key);
key++;
} else {
if (items.length > 1) {
addItem($(item), key);
key++;
}
}
});
/* handle click and add items */
addButton.on("click", function () {
addItem($(items[0]), key);
key++;
});
}
});
index.php
<?php
//session_start();
$servername = "localhost";
$username = "root";
$password = "bptm2012";
$dbname = "icompex";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "select panel_id,panel_kp,panel_nm from mem_panel";
$result = mysqli_query($conn, $sql);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Add Remove Panel Group and Category</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ"
crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="repeater.js" type="text/javascript"></script>
</head>
<body>
<div class="container">
<br/>
<h3 align="center">Kemaskini Ahli dan Kumpulan Panel Penilai</h3>
<br/>
<div style="width:100%; max-width: 600px; margin:0 auto;">
<div class="panel panel-default">
<div class="panel-heading">Menu Kumpulan dan Ahli Panel</div>
<div class="panel-body">
<span id="success_result"></span>
<div id="div1"><h2></h2></div>
<form method="post" id="repeater_form">
<div class="form-group">
<label>Pilih Group</label><br>
<select class="form-control" name="cat">
<option value="" disabled selected>Sila Pilih Kategori</option>
<option value="A">A - Rekabentuk Alam Bina & Rekabentuk Dalaman</option>
<option value="B">B - Pembinaan dan Bahan</option>
<option value="C">C - Mesin, Peralatan dan Proses Pergilangan</option>
<option value="D">D - ICT & Multimedia</option>
<option value="E">E - Elektrik, Elektronik dan Telekomunikasi</option>
<option value="F">F - Pengangkutan, Automatif & Penerbangan</option>
<option value="G">G - Pertanian, Alam Sekitar dan Tenaga Boleh Diperbaharui</option>
<option value="H">H - Pengajaran dan Pembelajaran</option>
<option value="I">I - Perkhidmatan dan Pemasaran Produk</option>
</select>
<label>Sila Pilih Kumpulan Panel</label><br>
<select name="group" class="form-control">
<option value="" disabled selected>Sila Pilih Kumpulan Panel</option>
<option value="1">Panel 1</option>
<option value="2">Panel 2</option>
<option value="3">Panel 3</option>
<option value="4">Panel 4</option>
<option value="5">Panel 5</option>
<option value="6">Panel 6</option>
<option value="7">Panel 7</option>
<option value="8">Panel 8</option>
<option value="9">Panel 9</option>
<option value="10">Panel 10</option>
<option value="11">Panel 11</option>
<option value="12">Panel 12</option>
<option value="13">Panel 13</option>
<option value="14">Panel 14</option>
<option value="15">Panel 15</option>
</select>
</div>
<div id="repeater">
<div class="repeater-heading" align="right">
<button type="button" class="btn btn-primary repeater-add-btn">Tambah Ahli</button>
</div>
<div class="clearfix"></div>
<div class="items" data-group="programming_languages">
<div class="item-content">
<div class="form-group">
<div class="row">
<div class="col-md-9">
<label>Pilih Nama Ahli Panel</label>
<select class="form-control" data-skip-name="true" data-name="skill[]"
required>
<?php
echo "<option>Sila Pilih Ahli Panel</option>";
if (mysqli_num_rows($result) > 0) {
// output data of each row
while ($row = mysqli_fetch_assoc($result)) {
echo '<option value="' . $row['panel_id'] . '">' . $row['panel_nm'] . '</option>';
}
} else {
echo "<option>Maaf Belum ada pendaftaran ahli panel dibuat</option>";
}
mysqli_close($conn);
?>
</select>
</div>
<div class="col-md-3" style="margin-top:24px;" align="center">
<button id="remove-btn" class="btn btn-danger"
onclick="$(this).parents('.items').remove()">Remove
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="clearfix"></div>
<div class="form-group" align="center">
<br/><br/>
<input type="submit" name="insert" class="btn btn-success" value="insert"/>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function () {
$("#repeater").createRepeater();
$('#repeater_form').on('submit', function (event) {
event.preventDefault();
$.ajax({
url: "insert.php",
method: "POST",
data: $(this).serialize(),
success: function (data) {
$('#repeater_form')[0].reset();
$("#repeater").createRepeater();
$('#success_result').html(data);
/*setInterval(function(){
location.reload();
}, 3000);*/
}
});
});
});
</script>
</body>
</html>
insert.php
<?php
connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
if (isset($_POST["name"])) {
$skill = implode(", ", $_POST["skill"]);
$data = array(
':panel_cat' => $_POST["cat"],
':panel_group' => $_POST["group"],
':panel_mem' => $skill
);
$query = "
INSERT INTO panel_penilai
(panel_cat, panel_group,panel_mem)
VALUES (:panel_cat, :panel_group, :panel_mem)
";
$statement = $connect->prepare($query);
if ($statement->execute($data)) {
echo '
<div class="alert alert-success">
Data Successfully Inserted
</div>
';
}
}
//?>

You can use XMLHTTP request to send the request. It is easier than your function and fully working. Check a sample request here XMLHTTP REQUEST
Let me know if you were successfull

Remove event.preventDefault(); .
preventDefault() method is used to stop submitting the form. Removing it will allow the form to submit the data to insert.php

first in insert.php your code will run if there is a "name" parameter that is posted, whereas in the index.php form there is no field with the name "name".
so the insert.php file doesn't display any results when you post with the current form
And as reminder you forget about $ and there is a database difference between insert.php and index.php
connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
should be
$connect = new PDO("mysql:host=localhost;dbname=icompex", "root", "bptm2012");
and in ajax you better add error handling so that you can see the error information in the console browser
$.ajax({
url:"insert.php",
method:"POST",
data:$(this).serialize(),
success:function(data)
{
$('#repeater_form')[0].reset();
$("#repeater").createRepeater();
$('#success_result').html(data);
/*setInterval(function(){
location.reload();
}, 3000);*/
},
// like this
error : function(err){
console.log(err);
}
});

You just change the submit button type to button
<input type="submit" name="insert" class="btn btn-success" value="insert" />
change to
<input type="button" id="submit" name="insert" class="btn btn-success" value="insert" />
And event must be click not submit
$('#repeater_form').on('submit', function(event){}
change to
$('#submit').on('click', function(event){}
so page will not redirect, data post throw ajax.

Related

trouble using ajax to send form values to php file

I am trying to send the form values to another php file. After confirming to send the data, I will not receive the alert notification from the php file.
What i tried doing: I tried creating a test file with the shortened down version of the code, surprisingly that works
This is the first file.
<!DOCTYPE html>
<?php
include('../class/Appointment.php');
include('../main/databaseConnection.php');
$object = new Appointment;
if(!$object->is_Adminlogin()){
header("Location: ../main/error.php");
}
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Doctor's Schedule</title>
<link rel="stylesheet" href="../css/add_schedule_popup.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<button id="add_schedule_button" >Add Doctor Schedule</button>
<div id="add_schedule_popup" class="modal">
<div class="modal-content">
<div class="form-header">
<span class="close">×</span>
<h2>Add Doctor Schedule</h2>
</div>
<div class="form-body">
<form method="POST" action="" id="doctor_schedule_form">
<input type="hidden" name="action_type" id="action_type" value="add">
<div class="form-group">
<label>Select Doctor</label>
<select name="doctor_id" id="doctor_id" class="form-control" required>
<option value="">Select Doctor</option>
<?php
$object->query = "SELECT * FROM doctor_info ";
$result = $object->get_result();
foreach($result as $row){
echo '
<option value="'.$row["doctor_id"].'">'.$row["doctor_firstname"].' '.$row["doctor_lastname"].'</option>';
}
?>
</select>
</div>
<div class="form-group">
<label>Select Schedule Date</label>
<input type="date" name="schedule_date" id="schedule_date" required><br>
</div>
<div class="form-group">
<label>Select Timeslot</label>
<select name="schedule_timeslot" id="schedule_timeslot" class="form-control" required>
<option value="">Select Timeslot</option>
<?php
$object->query = "SELECT * FROM timeslot";
$result = $object->get_result();
foreach($result as $row){
echo '
<option value="'.$row["schedule_timeslot"].'">'.$row["starting_time"].'-'.$row["ending_time"].' ('.$row["duration"].')</option>';
}
?>
</select>
</div>
<div>
<label>Select Availability</label>
<select name="schedule_status" id="schedule_status" class="form-control" required>
<option value="1">Available</option>
</select>
</div>
</div>
<br><br>
<div class="form-footer">
<button type="button" id="close_button">Close</button>
<input type="submit" id="submit_button" value="Confirm" name="submit_button">
</div>
</form>
</div>
</div>
<script>
var modal = document.getElementById("add_schedule_popup");
var btn = document.getElementById("add_schedule_button");
var span = document.getElementsByClassName("close")[0];
var close_button = document.getElementById("close_button");
btn.onclick = function() {
modal.style.display = "block";
}
function closeModal() {
modal.style.display = "none";
document.getElementById("doctor_schedule_form").reset();
}
span.onclick = closeModal;
close_button.onclick = closeModal;
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
document.getElementById("doctor_schedule_form").reset();
}
}
$(document).ready(function() {
$("#submit_button").click(function(){
e.preventDefault();
var doctor_id = $("#doctor_id").val();
var schedule_date = $("#schedule_date").val();
var schedule_timeslot = $("#schedule_timeslot").val();
var schedule_status = $("#schedule_status").val();
var action_type = $("#action_type").val();
console.log(doctor_id, schedule_date, schedule_timeslot, schedule_status, action_type);
$.ajax({
url: "modify_schedule_action.php",
type: "POST",
data: {doctor_id:doctor_id,schedule_date:schedule_date,schedule_timeslot:schedule_timeslot,schedule_status:schedule_status,action_type:action_type},
success: function(data) {
alert(data);
// Refresh the page or show a success message
},
success: function(data) {
console.log("Success", data);
},
error: function(data) {
console.log(jqXHR.responseText);
}
});
});
});
</script>
</body>
</html>
And this is the php file that i am trying to send the values to
<?php
include('../class/Appointment.php');
$object = new Appointment;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo 'Received form data: ' . var_export($_POST, true);
}
if($_POST['action_type'] == 'add')
{
$data = array(
':schedule_date' => $_POST['schedule_date'],
':schedule_day' => date('l', strtotime($_POST["schedule_date"])),
':schedule_status' => $_POST['schedule_status'],
':schedule_timeslot' => $_POST['schedule_timeslot'],
':doctor_id' => $_POST['doctor_id'],
);
$object->query = "INSERT INTO `schedule` (`schedule_date`, `schedule_day`, `schedule_status`, `schedule_timeslot`, `doctor_id`)
VALUES (:schedule_date,:schedule_day,:schedule_status,:schedule_timeslot,:doctor_id)";
$object->execute($data);
$output = 'Data added successfully';
}
until now, the php file does not react to anything i do inthe first file. can anyone help me troubleshoot this error?
You have e.preventDefault(); in your event handler but e is not defined.
This will cause an error preventing your ajax code from running and your form will submit normally to itself as its action is blank.
$("#submit_button").click(function(e){// define the event parameter
e.preventDefault();

How to pass a dropdown menu value in a Ajax JsonList in order to save the values in the database?

I want to pass a dropdown value to a JsonList and save it to the DB. Json list is first sent to the controller file and then it'll call the relevant Model and class. It works when the input type is a text. But doesn't work when it's a dropdown. Below are my codes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<meta name="description" content="Psychlarity">
<!--<link rel="shortcut icon" href="../images/favicon.png" type="image/png">-->
<title>Psychlarity</title>
</head>
<body>
<form method="POST" id="add_article_station" data-toggle="validator">
<div class="panel-heading">
<h4 class="panel-title"><i aria-hidden="true" class=""></i>Add New Question </h4>
<p>Use this form to add a new question to the system</p>
</div>
<div class="panel-body">
<div class="row">
<div class="form-group col-md-4">
<label>Age Category <span class="text-danger"></span></label>
<select name="age" id="age" class="select-css" >
<option disabled="disabled" selected="selected" >Select Age Category</option>
<option value="t">Teen</option>
<option value="a">Adult</option>
<option value="e">Elder</option>
<option value="">Any</option>
</select>
</div>
<div class="row">
<div class="form-group col-md-4">
<label>Relationship Status Category <span class="text-danger"></span></label>
<select name="RS" id="RS" class="select-css" >
<option disabled="disabled" selected="selected">Select Relationship Status Category</option>
<option value="m">Married</option>
<option value="n">Single</option>
<option value="">Any</option>
</select>
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label>Employement Status Category <span class="text-danger"></span></label>
<select name="ES" id="ES" class="select-css" >
<option disabled="disabled" selected="selected" >Select Employement Status Category</option>
<option value="e">Employed</option>
<option value="s">Student</option>
<option value="u">Unemployed</option>
<option value="">Any</option>
</select>
</div>
</div> <br> <br>
<div class="row pull-right">
<div class="col-md-12">
<button class="btn btn-success btn-quirk btn-wide mr5">Submit</button>
<button class="btn btn-quirk btn-wide btn-default" type="reset">Reset</button>
</div>
</div>
</div></div></div></div></div></div></form></div></section>
<script>
$("#add_article_station").validator().on('submit', function (event) {
if (!event.isDefaultPrevented()) {
var formData = new FormData($('#add_article_station')[0]);
console.log(formData);
$.ajax({
url: "../../Controller/AddquestionController.php",
type: 'POST',
data: formData,
async: false,
success: function (data) {
try {
var json = JSON.parse(data)
if (json.code == 200) {
window.location = "?msg=suc";
// alert(json.message);
} else {
window.location = "?msg=err";
}
} catch (e) {
window.location = "?msg=err";
}
}, error: function (data) {
toastr.error("Error In Saving");
},
cache: false,
contentType: false,
processData: false
});
}
return false;
});
$(document).ready(function () {
'use strict';
function getParam(name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results == null) {
return null;
} else {
return results[1] || 0;
}
}
$(function () {
if (getParam("msg") == "suc") {
toastr.success("Sucssfully saved.");
} else if (getParam("msg") == "err") {
toastr.success("Question saved.");
}
});
</script>
<?php include '../includes/notificationJS.php'; ?>
</body>
</html>
The below is my Model where the DB query is.
public static function Addquestion($article, $logedUser) {
if (TokenValidationModelClass::TokenValidate($logedUser)) {
$dbh = dbconnect::Connection();
$addquestionStmtStmt = $dbh->prepare("INSERT INTO questions
(age_cat,employment_status,relationship_status)
VALUES
(:age_cat,:employment_status,:relationship_status); ");
$addquestionStmtStmt->bindParam(':age_cat', $article->age);
$addquestionStmtStmt->bindParam(':employment_status', $article->es);
$addquestionStmtStmt->bindParam(':relationship_status', $article->rs);
if ($addquestionStmtStmt->execute()) {
return HttpStatusMessageRest::getHttpStatusMessage(200);
}
}
return HttpStatusMessageRest::getHttpStatusMessage(401);
}
If anyone needs, below is the controller file of it.
<?php
include '../Model/session_include.php';
require_once("../Model/articleModelClass.php");
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$data = (object) $_POST;
// print_r($data);
if (!empty($data)) {
if (!empty($data->token)) {
echo articleModelClass::Addquestion($data, $data->token);
} else {
$token = (object) $_SESSION;
// print_r($token);
echo articleModelClass::Addquestion($data, $token);
}
} else {
$error["error"] = "Empty field.";
echo json_encode($error);
}
}
?>

Remove / disable selected option[selected from first dropdown] from second dropdown on clicking add button php

index.php
<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=test", "root", "");
function fill_unit_select_box($connect)
{
$output = '';
$query = "SELECT * FROM tbl_unit ORDER BY unit_name ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output .= '<option value="'.$row["unit_name"].'">'.$row["unit_name"].'</option>';
}
return $output;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Add Remove Select Box Fields Dynamically using jQuery Ajax in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container">
<h3 align="center">Add Remove Select Box Fields Dynamically using jQuery Ajax in PHP</h3>
<br />
<h4 align="center">Enter Item Details</h4>
<br />
<form method="post" id="insert_form">
<div class="table-repsonsive">
<span id="error"></span>
<table class="table table-bordered" id="item_table">
<tr>
<th>Enter Item Name</th>
<th>Enter Quantity</th>
<th>Select Unit</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
</table>
<div align="center">
<input type="submit" name="submit" class="btn btn-info" value="Insert" />
</div>
</div>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_name[]" class="form-control item_name" /></td>';
html += '<td><input type="text" name="item_quantity[]" class="form-control item_quantity" /></td>';
html += '<td><select name="item_unit[]" class="form-control item_unit"><option value="">Select Unit</option><?php echo fill_unit_select_box($connect); ?></select></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
});
$(document).on('click', '.remove', function(){
$(this).closest('tr').remove();
});
$('#insert_form').on('submit', function(event){
event.preventDefault();
var error = '';
$('.item_name').each(function(){
var count = 1;
if($(this).val() == '')
{
error += "<p>Enter Item Name at "+count+" Row</p>";
return false;
}
count = count + 1;
});
$('.item_quantity').each(function(){
var count = 1;
if($(this).val() == '')
{
error += "<p>Enter Item Quantity at "+count+" Row</p>";
return false;
}
count = count + 1;
});
$('.item_unit').each(function(){
var count = 1;
if($(this).val() == '')
{
error += "<p>Select Unit at "+count+" Row</p>";
return false;
}
count = count + 1;
});
var form_data = $(this).serialize();
if(error == '')
{
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data)
{
if(data == 'ok')
{
$('#item_table').find("tr:gt(0)").remove();
$('#error').html('<div class="alert alert-success">Item Details Saved</div>');
}
}
});
}
else
{
$('#error').html('<div class="alert alert-danger">'+error+'</div>');
}
});
});
</script>
insert.php
<?php
//insert.php;
if(isset($_POST["item_name"]))
{
$connect = new PDO("mysql:host=localhost;dbname=test", "root", "");
$order_id = uniqid();
for($count = 0; $count < count($_POST["item_name"]); $count++)
{
$query = "INSERT INTO tbl_order_items
(order_id, item_name, item_quantity, item_unit)
VALUES (:order_id, :item_name, :item_quantity, :item_unit)
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':order_id' => $order_id,
':item_name' => $_POST["item_name"][$count],
':item_quantity' => $_POST["item_quantity"][$count],
':item_unit' => $_POST["item_unit"][$count]
)
);
}
$result = $statement->fetchAll();
if(isset($result))
{
echo 'ok';
}
}
?>
What I need is:
I don't want to show bags option selected in the first row inside the Select Unit dropdown of the second row.
That is, I want the user to select only one option from the Select Unit dropdown. The selection of the same option from the Select unit dropdown must be restricted.
Have a look at jquery fiddle link: https://jsfiddle.net/fyxog73t/3/
HTML Code:
<div class="row">
<div class="col-md-6">1st Row</div>
<div class="col-md-6">
<select id="select_1">
<option value="">Choose</option>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
<option value="d">D</option>
<option value="e">E</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">2st Row</div>
<div class="col-md-6">
<select id="select_2">
<option value="">Choose</option>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
<option value="d">D</option>
<option value="e">E</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">3st Row</div>
<div class="col-md-6">
<select id="select_3">
<option value="">Choose</option>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
<option value="d">D</option>
<option value="e">E</option>
</select>
</div>
</div>
JS Code:
$(document).on('change', '[id^="select_"]', function(){
var dropdown_value = $(this).val();
var dropdown_id = $(this).attr('id');
// code to update options from other dropdowns excluding currently selected dropdown
if(dropdown_value != "") {
$('[id^="select_"]:not([id="'+dropdown_id+'"])').find("option[value='"+dropdown_value+"']").attr('disabled', true);
}
// code to check, if any disabled option is present with it's value not present in other dropdown as selected option. If so then removing disabled option for that dropdown
$('[id^="select_"]:not([id="'+dropdown_id+'"])').find("option[value!='"+dropdown_value+"']:disabled").each(function(){
dropdown_value = $(this).val();
dropdown_id = $(this).parent().attr('id');
if($('[id^="select_"]:not([id="'+dropdown_id+'"])').find("option[value='"+dropdown_value+"']:selected").length == 0) {
$(this).removeAttr('disabled');
}
});
});
Had used below steps to achieve the required output:
1) On change method written for each dropdown.
2) In that on change method, disabling other dropdown's option whose value is same as selected option from current dropdown.
3) Then checked, is their any disabled option in other dropdown's(excluding currently selected dropdown). Checking whether that disabled value is present as selected value in other dropdown's or not. If not selected then remove it's disabled attribute.

Insert into Ajax php

Hello i need help in this code,i am new in ajax and php. this code dont work and idk why.
I want insert the form on database without refresh.
here is the code
All html of the site with the script
Im using boostrap
<!DOCTYPE html>
<html>
<head>
<title>CS INICIO</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</head>
<body style="background-color: #13171a">
<div class="container container-table">
<div class="row vertical-center-row">
<div class="text-center col-md-4 col-md-offset-4">
<form id="formulario" method="post">
<div class="form-group">
<input class="form-control" type="text" name= "nome" required="true" placeholder="Nome">
<input class="form-control" type="text" name= "link" required="true" placeholder="Link Steam">
<select class="form-control" name="rank">
<option value="silver1">Silver 1</option>
<option value="silver2">Silver 2</option>
<option value="silver3">Silver 3</option>
<option value="silver4">Silver 4</option>
<option value="silver5">Silver Elite</option>
<option value="silverElite">Silver Elite Master</option>
<option value="silverEliteMaster">Silver 1</option>
<option value="goldnova1">Gold Nova 1</option>
<option value="goldnova2">Gold Nova 2</option>
<option value="goldnova3">Gold Nova 3</option>
<option value="goldnovamaster">Gold Nova Master</option>
<option value="ak1">Master Guardian 1</option>
<option value="ak2">Master Guardian 2</option>
<option value="akcruzada">Master Guardian Elite</option>
<option value="eximio">Eximio</option>
<option value="le">Legendary Eagle</option>
<option value="lem">Legendary Eagle Master</option>
<option value="supreme">Supreme</option>
<option value="global">Global Elite</option>
</select>
<button class="btn btn-default" onclick="addData()" id="submit">Button</button>
</div>
</form>
</div>
</div>
</div>
<script type="text/javascript">
function addData() {
dataString = $("#formulario").serialize();
$(".text-danger").hide();
$.ajax({
type: "POST",
url: "enviar.php",
data: dataString,
cache: false,
dataType: 'json',
success: function(resp){
if(resp.status == '0') {
alert("insert error");
} else {
clearInput();
alert("insert success");
}
}
});
return false; //stop the actual form post !important!
}
</script>
</body>
</html>
here is the enviar.php i dont know here is the error
Im new in code
ficheiro php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$host = "localhost";
$root = "root";
$pass = "";
$tabela = "cssite";
$conexao = mysqli_connect($host, $root, $pass, $tabela) or die("Erro Na base de dados") ;
mysqli_connect_error($conexao);
$nome = $_POST['nome'];
$link = $_POST['link'];
$rank = $_POST['rank'];
$sql = "INSERT INTO utilizadores('nome','rank','link') VALUES ('".$nome."','".$rank."','".$link."')";
$sql_result = mysqli_query($conexao,$sql);
if ($sql_result) {
echo 1;
}
else{
echo 0;
}
?>
Thanks all for the help
dsadsasafsafasfas
Need to change you data object to use curly brackets, not normal ones:
data:{nome:nome,link:link,rank:rank},
Also need to change your condition in the success callback to a comparison operator as opposed to an assigned operator:
if (value == 1) {
In your PHP, you need to change return 1; and return 0; to echo 1; and echo 0; if you want them to output to the page.
You are also only listening for the click event, you should listen for the submit event so you can prevent the default action. Change:
$('#submit').click(function(){
To:
$('#yourform').on("submit", function(e){
e.preventDefault(); //Prevents submission of the form through normal means.
This would help in the "Undefined index error":
if(isset($_POST['submit'])){
// your code
}
Call this function on button click
function addData() {
dataString = $("#formulario").serialize();
$(".text-danger").hide();
$.ajax({
type: "POST",
url: "enviar.php",
data: dataString,
cache: false,
dataType: 'json',
success: function(resp){
if(resp.status == '0') {
alert("insert error");
} else {
clearInput();
alert("insert success");
}
});
return false; //stop the actual form post !important!
}

HTML form GET results show up in target div, then immediately disappear

I've found 5-6 similar questions on StackOverflow, but I wasn't able to see the correlation to my code — theirs seems to be a different approach — so I wasn't able to squeeze a solution out of them.
Essentially, when I call up my report.html page, and enter in valid dates, like 2015-06-01 and 2015-06-12, choose Deal "A" and hit Submit ... a table of results briefly appears in the target div at the bottom ... then promptly disappears.
An additional strange thing, is when I hit the back button on the browser, there's my result (and it stays put)!
One other thing: If I add action="ajaxFunction()" to the , the results show up and stay (although I also get a nice big jQuery Mobile error message box in the middle of my screen for a few seconds).
Anyway, I think I'm CLOSE. Code below. Thanks!
report.html
<html>
<head>
<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0" />
<title> Report</title>
<link rel="stylesheet" href="css/style_report.css" type="text/css">
<link rel="stylesheet" href="../../../jquery-mobile/demos/css/themes/default/jquery.mobile-1.4.5.min.css">
</head>
<body>
<div data-role="page" id="pageone">
<div data-role="panel" id="myPanel">
<form name="sqlForm" method="" action="" id="sqlForm" >
<div class="date-range">
<p>Choose a date range</p>
<div><input type="text" id="startDate" name="startDate" data-role="date" data-date-format="yy-mm-dd"></div>
<p>to</p>
<div><input type="text" id="endDate" name="endDate" data-role="date" data-date-format="yy-mm-dd"></div>
</div>
<div class="deal_type">
<p>Choose one or more deals</p>
<select name="dealCode" id="dealCode">
<option value="*">Select a deal</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="E">E</option>
<option value="F">F</option>
<option value="G">G</option>
<option value="H">H</option>
<option value="I">I</option>
<option value="J">J</option>
<option value="K">K</option>
<option value="L">L</option>
<option value="M">M</option>
<option value="N">N</option>
<option value="O">O</option>
</select>
</div>
<input data-rel="close" type="submit" id="submit" value="Submit" onclick="ajaxFunction()" value="Query MySQL" >
</form>
<!-- BUTTON HERE TO GO TO RESULTS AND CLOSE PANEL -->
</div><!-- PANEL ENDS -->
<div class="wrapper">
<h1>REPORTS</h1>
<div data-role="main" class="ui-content">
<!-- PANEL BUTTON -->
<a href="#myPanel" class="ui-btn ui-shadow ui-corner-all ui-btn-inline ui-btn-icon-left ui-icon-bars">
Filter results</a>
<div id="sqlTable" style="background-color:yellow; height:auto;">Person info will be listed here...</div>
</div>
</div>
</div>
<script src="../../../jquery-mobile/demos/js/jquery.js"></script>
<script src="../../../jquery-mobile/demos/js/jquery.mobile-1.4.5.min.js"></script>
<script src="http://cdn.rawgit.com/jquery/jquery-ui/1.10.4/ui/jquery.ui.datepicker.js"></script>
<!-- JQuery datepicker -->
<!--Datepicker relevant external files-->
<script src="https://rawgithub.com/arschmitz/jquery-mobile-datepicker-wrapper/v0.1.1/jquery.mobile.datepicker.js"></script>
<script src="https://rawgithub.com/jquery/jquery-ui/1.10.4/ui/jquery.ui.datepicker.js"></script>
<link rel="stylesheet" href="https://rawgithub.com/arschmitz/jquery-mobile-datepicker-wrapper/v0.1.1/jquery.mobile.datepicker.css">
<!-- SCRIPT TO SET UP THE DATEPICKER CORRECTLY -->
<script>
$(document).ready(function () {
$.datepicker.setDefaults({
dateFormat: 'yy-mm-dd'
});
$(document).on("click", "#date1", function () {
var viewportwidth = $(window).width();
var datepickerwidth = $("#ui-datepicker-div").width();
var leftpos = (viewportwidth - datepickerwidth) / 2;
$("#ui-datepicker-div").css({
left: leftpos,
position: 'absolute'
});
});
$("#date1").datepicker({
onSelect: function () {
alert("HAHA");
}
});
}
);
</script>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('sqlTable');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var startDate = document.getElementById('startDate').value;
var endDate = document.getElementById('endDate').value;
var dealCode = document.getElementById('dealCode').value;
var queryString = "?startDate=" + startDate + "&endDate=" + endDate + "&dealCode=" + dealCode;
ajaxRequest.open("GET", "getReport.php" + queryString, true);
ajaxRequest.send(null);
}
console.log("ffff", "startDate="+str1+"&endDate="+str2+"&dealCode="+str3);
</script>
</body>
</html>
getReport.php
<?php
// MAKE THE MAIN CONNECTION, AND GIVE IT A NAME, 'CON'
$con = mysqli_connect("URL", "USERNAME", "PASSWORD", "DB");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
// THE INFO AFTER THE COMMA, "MAIN_REPORT", APPEARS TO BE USELESS, BUT HAS TO BE THERE.
mysqli_select_db($con,"MAIN_REPORT");
//GRAB THE STUFF FROM THE HTML FORMS
$startDate = $_REQUEST['startDate'];
$endDate = $_REQUEST['endDate'];
$dealCode = $_REQUEST['dealCode'];
// MAKE YOUR OVERALL QUERY HERE.
$sql="SELECT * FROM `oasis_bagels` WHERE `dealDate` > '$startDate' AND `dealDate` < '$endDate' ORDER BY `dealDate`";
$result = mysqli_query($con,$sql);
// THIS TESTS YOUR QUERY, OFTEN GIVING YOU A HELPFUL ERROR MESSAGE
if (!$result) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
?>
<?php /*?> $all = mysqli_query(
$con,
//"SEL
SELECT * FROM `oasis_bagels` WHERE `dealCode` = ' "$q" ';
// SELECT * FROM `oasis_bagels` WHERE `dealDate` > '$startDate' AND `dealDate` < '$endDate'
// SELECT * FROM `oasis_bagels` WHERE `dealDate` > '2015-01-01' AND `dealDate` < '2100-01-01'
// WHERE dealCode=*"
);
<?php */?>
<!-- ////////////////////////////////////////////////////////// -->
<!-- THE CODE BELOW GIVES ME THE DATE AND TIME RESULTS I WANT.
NONE OF THIS SHOULD CHANGE, AS IT'S ONLY FORMATTING THE RESULTS. -->
<!-- ////////////////////////////////////////////////////////// -->
<table border="1" cellpadding="4" cellspacing="4" bordercolor="#CFCBCB">
<tr class="header">
<th>Purchased</th>
<th>Code</th>
<th>Name</th>
<th>Value</th>
</tr>
<?php while ($row = mysqli_fetch_array($result)): ?>
<?php $date = $row['dealDate']; ?>
<?php $code = $row['dealCode']; ?>
<?php $name = $row['dealName']; ?>
<?php $value = $row['dealValue']; ?>
<tr>
<td>
<span class="date">
<?php
$PhpDate = strtotime($date);
$FormattedPhpDate = date('m/d/y', $PhpDate );
echo $FormattedPhpDate;
?></span><br>
<span class="time"><?php
$PhpDate = strtotime($date);
$FormattedPhpDate = date('(g:i A)', $PhpDate );
echo $FormattedPhpDate;
?></span>
</td>
<td class="code"><?php echo $code; ?></td>
<td><?php echo $name; ?></td>
<td><?php echo $value; ?></td>
</tr>
<?php endwhile; ?>
</table>
<?php mysqli_close($con); ?>
change your submit button to ...
<button type="button" data-rel="close" id="submit" value="Query MySQL" >
<input style="display: none;" type="submit" id="realsubmit">
and add this ...
$("#submit").on('click', function() {
// do some stuff
$("#realsubmit").trigger('click');
return false;
});

Categories