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!
}
Related
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.
I'm trying to send a form to php for validation before inserting data into mySQL. I'm trying to use AJAX to do it. I am unable to get through the validation process when sending a <select> <option>. If I remove the validation for the <select <option> the form processes as expected. When sending via AJAX I get the following response in console:
When I process the form by just sending it without AJAX, the validation works fine. Below is my code:
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<title>Validate SelectWith Ajax</title>
<meta charset="UTF-8">
</head>
<body>
<form id="frm" action="process.php" method="post" novalidate>
<label for="yourOptions">Your Options</label>
<select id="yourOptions" name="yourOptions" required>
<option value="" hidden selected>Select One</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
<option value="5">Option 5</option>
</select>
<input type="submit" value="Submit" name="Submit">
<?php echo "hello"; ?>
</form>
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous">
</script>
<script src="ajax.js"></script>
</body>
</html>
PHP
<?php
$errors = array();
$data = array();
if($_SERVER["REQUEST_METHOD"] === "POST") {
if($_POST["yourOptions"] == "") {
$errors["yourOptions"] = "Please Select One";
}
if(!empty($errors)) {
$data["success"] = false;
$data["errors"] = $errors;
} else {
$data["success"] = true;
$data["message"] = "Success!";
}
echo json_encode($data);
}
?>
jquery AJAX
alert("loaded");
$(document).ready(function() {
$("#frm").submit(function(event) {
alert("sub");
event.preventDefault();
console.log(typeof document.getElementById("yourOptions"));
$(".form-group").removeClass("is-invalid");
$(".text-muted").remove();
var formData = {
"yourOptions" : $("input[name=yourOptions]").val()
};
$.ajax({
type : "POST",
url : "process.php",
data : formData,
dataType : "json",
encode : true
})
.done(function(data) {
console.log(data);
if(!data.success) {
if(data.errors.yourOptions) {
$("#yourOptions").addClass("is-invalid");
$("#frm").append("<span class='text-muted'>" + data.errors.yourOptions + "</span>");
}
} else {
$("form").append("<span class='alert alert-success'>" + data.message + "</span>");
}
})
.fail(function(data) {
alert("failed");
console.log;
});
});
});
The data-type is object, but then again, so were the other fields. How do I get php to process the selected option?
Replace
$("input[name=yourOptions]").val()
with
$( "#yourOptions" ).val()
Serialize ajax will post all data you want
$(document).ready(function(){
$('#frm').submit(function(event){
event.preventDefault();
var formValues = $(this).serialize();
$.ajax({
url:"process.php",
method:"POST",
data:formValues,
dataType:"JSON",
success:function(data){
if(data === 'ok'){
$('#result').html(data);
} else {
$('#result').html(data);
$('#frm')[0].reset();
}
}
});
});
});
How you show result :
<div id="result"></div>
See this question for detailed explanition and more : Jquery ajax setTimeout after form succes not redirecting?
In my project, I use jqpagination. And I want to define the records of each page, so I use select tag in my web page.
The problem is when I change select tag, the value returned from lstajax.php is not the same. sometimes it is xie1, but sometimes it is xie2.
I have tested, the returned value is random. For example, when i chosed 30 first, the value is xie1. When i chosed 30 next time, the value maybe xie1 or maybe xie2.
My js code:
<link rel="stylesheet" href="jsui/jqpagination.css" />
<script src="jsui/jquery-3.2.1.min.js"></script>
<script src="jsui/jquery.jqpagination.js"></script>
<script>
$(document).ready(function()
{
var rtnv = "<?php session_start();echo $_SESSION['rtNum']?>";
var pgrNum=$('#pgnId').val();
var mpn=Math.ceil(rtnv/pgrNum);
$('.pagination').jqPagination({
max_page:mpn,
page_string:'Page {current_page} of {max_page}',
paged:function(page){
$.ajax({
dataType:'html',
type:"POST",
url:"lstajax.php",
data:{pageNum:page,pgrNum:pgrNum},
success:function(data)
{
$('#div2').html(data);
}
});
}
});
$('#pgnId').change(function(){
var pages="1";
$('.pagination').jqPagination('option','current_page',pages);
var rtnvs = "<?php session_start();echo $_SESSION['rtNum']?>";
var pgrNums=$('#pgnId').val();
var mpns=Math.ceil(rtnvs/pgrNums);
$('.pagination').jqPagination('option','max_page',mpns);
$.ajax({
dataType:'html',
type:"POST",
url:"lstajax.php",
data:{pageNums:pages,pgrNums:pgrNums},
success:function(data)
{
$('#div2').html(data);
}
});
});
});
</script>
My lstajax.php code:
<?php
if(isset($_POST['pageNum']))
{
echo "xie1";
}
if(isset($_POST['pageNums']))
{
echo "xie2";
}
?>
My html code:
<div class="pagination" style="clear:both;display:block;margin-left:40%">
«
‹
<input type="text" readonly="readonly" data-max-page="80"/>
›
»
<label>eachpage:</label>
<select name="pgNum" id="pgnId">
<option value="10">10</option>
<option value="15">15</option>
<option value="20" selected="selected">20</option>
<option value="30">30</option>
<option value="40">40</option>
<option value="50">50</option>
</select>
</div>
var options={'trigger':false}
in the method:
base.cassMthod=function(method,key,value)
in the file:
jquery.jqPagination.js
I have 2 select box option, item and part number. I'm using php and ajax to get part number when I pick an item.
The issue is that, the html and php all work but for the ajax. Nothing populates in the part number select-box when an item is selected.
Here is my html and ajax side (index.php):
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
function fetch_select(val)
{
$.ajax({
type: 'post',
url: 'get_state.php',
success: function (response) {
document.getElementById("partno").innerHTML=response;
}
});
}
</script>
</head>
<body>
<div id="select_box">
<form action="" method="post">
Item:
<select name="item" id="item" onchange="fetch_select(this.value);">
<option value="">select item</option>
<option value="item1">Item 1</option>
<option value="item2">Item 2</option>
</select>
<br>
Part:
<select name="partno" id="partno">
<option value="">select part</option>
</select>
</form>
</body>
</html>
Here is the php file (get_state.php):
<?php
//Connection to DB
//Select data from Table based on item selection
$query="SELECT partno FROM Table";
$params = array($_REQUEST['query']);
$results = sqlsrv_query($conn, $query, array(), array( "Scrollable" => 'static' ));
if($results===false)
{ die( FormatErrors( sqlsrv_errors() ) ); }
while($row = sqlsrv_fetch_array($results, SQLSRV_FETCH_ASSOC))
{
echo "<option>".$row['partno']."</option>";
}
exit;
?>
Help is greatly appreciated. Thank you.
With this code I can see each option value printed but the page is refreshed every time I select an option. The server get the post data correctly, so I just need to do it without refreshing.
Thanks. Regards.
<form action="" method="post">
<select name="day" onchange="this.form.submit();">
<option>Please select a date</option>
<option value="Mon">Monday</option>
<option value="Tue">Tuesday</option>
<option value="Wed">Wednesday</option>
<option value="Thu">Thursday</option>
<option value="Fri">Friday</option>
</select>
</form>
<script type="text/javascript">
$('#day').change(function()
{
$.ajax({
type: 'post',
url: "day.php",
data: $("form.day").serialize(),
});
return false;
});
</script>
<?php
include 'day.php'; ?>
day.php
<?php
$day = $_POST['day'];
echo $day;
?>
I think you need this:
e.preventDefault();
//add your id="day"
<select name="day" id="day" onchange="this.form.submit();">
$('#day').change(function(e)
{
e.preventDefault();
$.ajax({
type: 'post',
url: "day.php",
data: $("form.day").serialize(),
});
return false;
});
Update the onchange to call a Javascript function that copies the data to a hidden field in another form, and use Ajax to submit that one instead.
Optionally, you could also submit the data through Ajax directly, without the additional form, but for things that might be done with high frequency, I find it useful to minimize the bandwidth as much as possible.
I could see every option value printed by the <p id=..> without refreshing the page. But the post data is not passed to day.php..
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<html>
<head>
<script>
function postSelection(selectObject) {
var day = window.dateForm.day.value = selectObject.options[selectObject.selectedIndex].value;
var dataString = "day=" + day;
$.ajax ({
type:"post",
url: "day.php",
data:dataString,
success: function (response) {
$("#list").html(response);
}
});
return false;
}
</script>
</head>
<body>
<form name="displayForm">
<select name="day" onchange="return postSelection(this)">
<option>Please select a date</option>
<option value="Mon">Monday</option>
<option value="Tue">Tuesday</option>
<option value="Wed">Wednesday</option>
<option value="Thu">Thursday</option>
<option value="Fri">Friday</option>
</select>
</form>
<form action="" method="post" name="dateForm">
<input type="hidden" name="day">
</form>
<?php include 'day.php'; ?>
</body>
</html>