I have a form in PHP am sending via AJAX Jquery. The form is sent successfully via AJAX JQuery but the webpage is shown when the success message shows or the form is sent. What might be the exact problem causing this.
<? php include_once 'config.php'; if(isset($_POST) && !empty($_POST)) { $staff_number=$ _POST[ 'staff_number']; $department=$ _POST[ 'department']; $stmt=$ link->prepare("INSERT INTO `staffs` (`staff_name`,`department`) VALUES (?,?)"); $stmt->bind_param('ss',$staff_name, $staff_number, $designation, $department); if ($stmt->execute()){ echo "<span style='background-color:#69d052;
padding:6px;
color:white; font-size:13px;border-radius:5px;'>Staff created
successfully. </span>"; } else{ echo "
<p align=center>Error inserting data.</p>"; echo mysqli_error($link); } } ?>
<!DOCTYPE html>
<body>
<div class="container">
<div class="col-md-7 col-md-offset-3">
<form action="" method="post" autocomplete="off" id="my_form">
<div class="form-group">
<label>Staff Name</label>
<input type="text" required="true" name="staff_name" class="form-control" value="">
</div>
<div class="form-group">
<label>Department</label>
<input input="text" name="department" class="form-control" value="">
</div>
<div class="message_box" style="margin:50px 0px;">
</div>
<br>
<input type="submit" class="btn btn-success" value="Add">
</form>
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/ libs/jquery/1.3.0/jquery.min.js"></script>
<script>
$(function() {
$('form').on('submit', function(e) {
e.preventDefault();
$('.message_box').html('Processing...');
$.ajax({
type: 'post',
data: $('form').serialize(),
success: function(data) {
$('.message_box').html(data).fadeIn('slow');
$("#my_form")[0].reset();
}
});
});
});
</script>
</body>
</html>
You might be Redirecting the request after success from the server side (PHP). That's why a page is showing.
In you ajax call you are not setting your url property, by default this will be set to the current page, that is why you might be getting the page instead.
try adding your url, to your ajax...
$.ajax({
url: '..my ajax url.....',
type: 'post',
data: $('form').serialize(),
success: function(data) {
$('.message_box').html(data).fadeIn('slow');
$("#my_form")[0].reset();
}
});
Related
So I'm making a form that puts info into my local mysql db. But I stuck when I try to POST it. I getting "405 method not found" when try to debbug. I'm sing xampp for my virtual DB, maybe it's because of that?
The code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Kasmetinių atostogų prašymas</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="title">
<h1>Kasmetinių atostogų prašymas</h1>
</div>
<div class="form">
<form id="requestForm" method="POST" target="_blank">
<input type="date" name="request_date" id="input_field" placeholder="Prašymo data" required></br></br>
<input type="text" name="first_name" placeholder="Vardas" id="input_field" required></br></br>
<input type="text" name="last_name" placeholder="Pavardė" id="input_field" ></br></br>
<input type="number" name="personal_code" placeholder="Asmens kodas" id="input_field" min="11" max="11" ></br></br>
<input type="text" name="p_address" placeholder="Jūsų adresas" id="input_field" ></br></br>
<input type="date" name="requestDateFrom" id="input_field" placeholder="Atostogos nuo" ></br></br>
<input type="date" name="requestDateTo" id="input_field" placeholder="Atostogos iki" ></br></br>
<input type="number" name="daysNumber" placeholder="Atostogų dienų skaičius" id="input_field" ></br></br>
</br>
<Input type="button" name="submit_button" id="buttonLast" value="Patvirtinti">
</form>
</div>
<script>
$(document).ready(function(){
$("#buttonLast").click(function(){
$.ajax({
url:"http://127.0.0.1:5500/insert.php",
type: "POST",
data:$("#requestForm").serialize(),
success:function(response)
{
alert("Well done!");
}
});
});
});
</script>
</body>
</html>
And this is php code to connect db and post info into specific columns.
For the purpose of test I trying to post just from the 3 cols.
PHP:
<?php
$con = mysqli_connect("localhost","root","","test");
if(!$con)
{
echo 'Connection problems';
}
else
{
echo 'Ok';
}
if(isset($_POST['submit'])){
$date = $_POST['requestDate'];
$name=$_POST['firstName'];
$lname = $_POST['lastName'];
$query = "insert into info (date,name,lname) values ('$date','$name','$lname')";
if($con->query($query) === true )
{
echo 'Duomenys išsaugoti!';
}
else{
echo 'Duomenų nepavyko išsaugoti!';
}
}
header("refresh:2; url=index.html");
?>
Change
type: "POST"
to
method:"POST"
Other error you might encounter:
You are using requestDate in php but request_date in html. Similar for other params.
Update:
Add cors header to Ajax call
url:"http://127.0.0.1:5500/insert.php",
method: "POST",
headers: {
'Access-Control-Allow-Origin': '*'
},
data:$("#requestForm").serialize(),
success:function(response)
{
alert("Well done!");
}
$(document).on("submit", "#requestForm", function (event) {$.ajax({
url:"https://127.0.0.1:5500/insert.php",
type: "POST",
data:$(this).serialize(),
success:function(response)
{
alert("Well done!");
}
});
});
Try this Jquery Code.
I'm having some difficulties with uploading an image from an html form. the form should be able to send the image name with other data to php page.
I used formData instead of serialized function, since it can't handle files data.
$(document).on('click', '#btn_add', function(){
var formData = new FormData($(this)[0]);
$.ajax({
url:"includes/widgets/insert.php",
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false
success: function (data) {
alert(data);
},
});
return false;
});
html form
<form id="insert_post" action="includes/widgets/insert.php" method="post" enctype="multipart/form-data" >
<div class="row">
<div class="medium-6 columns">
<label>First name
<input type="text" name="first_name" id="first_name" contenteditable>
</label>
</div>
<div class="medium-6 columns">
<label>Last name
<input type="text" name="last_name" id="last_name" contenteditable>
</label>
</div>
<div class="medium-12 columns">
<label>Last name
<input type="file" name="file" id="image" multiple contenteditable>
</label>
</div>
</div>
<button type="button" name="btn_add" id="btn_add" class="button btn btn-xs btn-success" >Submit</button>
</form>
php page
<?php
$connect = mysqli_connect("localhost", "root", "", "myaddboard");
echo $_POST['first_name'];
echo $_POST['last_name'];
echo $image = $_FILES['file']['name'];
echo $image_tmp = $_FILES['file']['tmp_name'];
/*
if(empty($image)){
echo 'error';
}
move_uploaded_file($image_tmp,"img/$image");
//$sql = "INSERT INTO posts(post_content, post_author) VALUES('".$_POST["first_name"]."', '".$_POST["last_name"]."')";
if(mysqli_query($connect, $sql))
{
echo 'Data Inserted';
} else {
echo 'error';
}
*/
?>
The php form is just to test if the ajax send the data correctly.
When I click on the button I always get errors that the php variables is not defined
The errors i get each time I submit the form
undefined index: frist_name in c:xampp\htdocs\unv\includes\widgets\insert.php on line 4
undefined index: last_name in c:xampp\htdocs\unv\includes\widgets\insert.php on line 5
undefined index: file in c:xampp\htdocs\unv\includes\widgets\insert.php on line 8
undefined index: file in c:xampp\htdocs\unv\includes\widgets\insert.php on line 9
what should I do to make the ajax send the data to the php page ?
This won't work because of how your selector is created.
$(document).on('click', '#btn_add', function(){
var formData = new FormData($(this)[0]);
In the above scenario, $(this)[0] is getting you the raw HTML interpretation of the button.
What you actually want is to change your button to a submit type, capture the form submit event, and then process your request.
button type="submit" <-- change
$(document).on('submit', '#insert_post', function(e){
e.preventDefault(); //stop default form submission
//do the rest of your stuff here
});
Now $(this)[0] is actually the form and not the button.
How to execute Jquery Ajax post data on multiple pages.
For Example, I am using three pages named Page1,Page2,Page3. I need to post data from Page 1 -> Page2 and,from Page2 -> Page 3. User initiates only on Page1, all other function should performed in background. Is that possible?
This is the code used.
Page1.php:
<html>
<head><title>Page1</title></head>
<script src="/path to/jquery.min.js"></script>
<body>
<button type="button" class="btn" id="bt">SEND</button>
<script>
var a1="Hello";
var b1="Testing Ajax";
$(function(){
$('#bt').click(function(){
$.ajax({
url: 'Page2.php',
type: 'POST',
data: {'w1': a1,'w2':b1},
alert("Data Sent...");
},
error: function() {
alert("Unable to send data now.");
}
});}); });
</script>
</body>
</html>
Page2.php:
<html>
<head><title>Page 2 </title></head>
<body>
<?
$r1 = $_POST['w1'];
$r2 = $_POST['w2'];
?>
<div id="dom1" style="display: none;">
<?php
$r1 = $_POST['w1'];
echo htmlspecialchars($r1);
?>
</div>
<div id="dom2" style="display: none;">
<?php
$r2= $_POST['w2'];
echo htmlspecialchars($r2);
?>
</div>
<script>
var div1 = document.getElementById("dom1");
var m1 = div1.textContent;
//alert(m1);
var div2 = document.getElementById("dom2");
var m2 = div2.textContent;
//alert(m2);
$.ajax({
url: 'Page3.php',
type: 'POST',
data: {'x1': m1,'x2':m2},
alert("Data Sent...");
},
error: function() {
alert("Unable to send data now.");
}
});
</script>
</body>
</html>
Page3.php:
<html>
<head>
<title>Page3</title></head>
<body>
<div id="dom3">
<?php
$r1 = $_POST['x1'];
echo htmlspecialchars($r1);
?>
</div>
<div id="dom2">
<?php
$r2 = $_POST['x2'];
echo htmlspecialchars($r2);
?>
</div>
</body>
</html>
There are several ways you can solve your problem.
PHP Sessions
You can easily start a session in every of your pages and post
<?php
// every page needs to start the session
session_start();
// after submission or posting
$_SESSION['data'] = $your_data;
?>
So on your next page you can easily access your data via session.
<div>
<?= $_SESSION['data']['var1'] ?>
</div>
Use Forms and send them via jQuery ajax requests and put the form values on the next page into hidden input elements.
<!-- example for page 2 -->
<form id="your_form" method="post" action="">
<input type="hidden" name="var1" value="<?= $var1 ?>">
<input type="hidden" name="var2" value="<?= $var2 ?>">
<input type="submit" id="submit" name="submit" value="submit">
</form>
<script type="text/javascript">
$('#submit').on('click', function( event ) {
event.preventDefault();
$.ajax({
url : your_url,
type : 'POST',
data : $('#your_form').serialize();
});
});
</script>
Just don 't use ajax. You really don 't need it, wenn you jump from page to page. Look the example below.
<!-- on page1.php just a quick form -->
<form id="form1" method="post" action="page2.php">
<label for="var1">Var 1</label>
<input type="text" name="var1" id="var1" value="">
<input type="submit" name="submit" value="submit">
</form>
<!-- on page2.php just another quick form with hidden elements -->
<form id="form2" method="post" action="page3.php">
<label for="var2">Var 2</label>
<input type="text" name="var2" id="var2" value="">
<input type="hidden" name="var1" value="<?= $_POST['var1'] ?>">
<input type="submit" name="submit" value="submit">
</form>
In every 3 given examples you should consider the securty stuff like escaping post vars, etc.
I have a registration form and want to check if registered user will try to register again to show a alert window already registered using ajax function.
i have used codeigniter framework.
my function is working properly but when alert popup and press ok page is reloaded. i want to disable
my form code:
<form class="modal-content" name="form2" action="<?= $this->config->base_url();?>home/register_user" method="post" onSubmit="return ValidateRegister()">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Create your account</h4>
</div>
<div class="page-content vertical-align-middle" style="display:block;">
<div class="form-group has-error">
<label class="control-label" for="inputTokenfieldError-tokenfield"> <?php echo validation_errors(); ?></label>
</div>
<div class="form-group form-material floating">
<input type="text" class="form-control " id="inputName" name="username" value="<?php echo set_value('username'); ?>" autocomplete="off">
<label class="floating-label">Username</label>
</div>
<div class="form-group form-material floating">
<input type="email" class="form-control " id="my_email" name="email" value="<?php echo set_value('email'); ?>" autocomplete="off">
<label class="floating-label">Email</label>
</div>
<div class="form-group form-material floating">
<input type="password" class="form-control " id="inputPassword" name="password" autocomplete="off">
<label class="floating-label">Password</label>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Join Now - It's Free</button>
</div>
</form>
my javascript function:
function checkRegistrations()
{
var email = $('#my_email').val();
$.ajax({
url: "<?= base_url() ?>home/checkRegistration",
async: false,
type: "POST",
data: "email="+email,
dataType: "html",
success: function(data) {
// alert(data);
if(data==1)
{
//event.preventDefault();
alert('Email already registered');
return false;
window.location.reload(false);
}
else{
return true;
}
}
})
}
Just add an id to the submit button, say #submitbutton.
and use the .prop() method of jQuery to set the disabled attribute of the button.
$("#submitbutton").prop("disabled", true);
IMP: This will only work if you are keeping the same page on ajax success, But if you are reloading the page then you need to check it on php side whether this form has been submitted in this current $_SESSION.
So inside your php ajax handler, you can do the check as follows.
session_start();
if(!empty($_POST) && empty($_SESSION['post'])) {
$_SESSION['post'] = true;
... do your code
unset($_SESSION['post']);
}else{
// send the json encoded error message
}
And on the html form just add a hidden input with the name post and set value to 1 or something whatever you deem fit, so once the form is submitted, the post key will be set inside the $_SESSION SuperGlobal Array, and if the same form is submitted twice by the same user then php wont accept it.
You are returning true/false from inside an annon. function i.e. success handler. But parent function is not returning true/false.
Modify your code like this :
function checkRegistrations()
{
var email = $('#my_email').val();
var isValid = true;
$.ajax({
url: "<?= base_url() ?>home/checkRegistration",
async: false,
type: "POST",
data: "email="+email,
dataType: "html",
success: function(data) {
if(data==1)
{
alert('Email already registered');
isValid = false;
}
}
});
return isValid;
}
I have a code here of inserting and displaying record without refreshing web page using ajax and plain php but I don't know how to set this up using codeigniter. Please help. Here are the codes
inserting.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".comment_button").click(function() {
var test = $("#content").val();
var dataString = 'content='+ test;
if(test=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax-loader.gif" align="absmiddle">
<span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "demo_insert.php",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
document.getElementById('content').value='';
document.getElementById('content').focus();
$("#flash").hide();
}
});
} return false;
});
});
</script>
// HTML code
<div>
<form method="post" name="form" action="">
<h3>What are you doing?</h3>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Update" name="submit" class="comment_button"/>
</form>
</div>
<div id="flash"></div>
<div id="display"></div>
demo_insert.php
PHP Code display recently inserted record from the database.
<?php
include('db.php');
if(isSet($_POST['content']))
{
$content=$_POST['content'];
mysql_query("insert into messages(msg) values ('$content')");
$sql_in= mysql_query("SELECT msg,msg_id FROM messages order by msg_id desc");
$r=mysql_fetch_array($sql_in);
}
?>
<b><?php echo $r['msg']; ?></b>
In your wellcome controller you can add the following:
public function inserting()
{
$this->load->view('inserting');
}
public function process()
{
$content=$this->input->post('content');
if($this->db->insert('mytable', array('msg' => $content))){
echo "<b>{$content}</b>";
}
You should then use inserting.php as your view, in application/views, and the ajax url would be /process.
Didn't test it, but this should do the trick. Also, you should check this example http://runnable.com/UXczcazDrMMiAAGl/how-to-do-ajax-in-codeigniter-for-php