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.
Related
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();
}
});
UPDATE
Objective post data (age and name) from www.domain1.com to www.domain2.com/try.php
Problem
am getting this on domain2.com/try.php
Undefined index: name
Undefined index: age
Index.html on domain1
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#clickMe").click(function () {
$.ajax({
type: 'post',
contentType: "application/json; charset=utf-8",
url: 'www.domain2.com/try.php',
dataType: "json",
data: {
name: "tom",
age: "30"
},
complete:
function (data) {
window.location = "www.domain2.com/try.php";
}
})
})
})
</script>
</head>
<body>
<input id="clickMe" type="button" value="clickme123"/>
</body>
</html>
try.php on domain2
<?php
$name = $_POST['name'];
$age = $_POST['age'];
echo 'name:'.$name;
echo 'age:'.$age;
On the first domain just use a form and post to the second domain:
<html>
<head>
</head>
<body>
<form action="http://two.example.com/foo.php" method="POST">
<input type="hidden" name="name" value="tom">
<input type="hidden" name="age" value="30">
<input type="submit" value="Go">
</form>
</body>
</html>
I want to display jquery sweet alert after php insert query successfully executed.. but whenever i tried to call jquery function after if condition, didn't work..or alert appear for 1-2 sec before page reload for form submit and disappear immediately..it only works with button onclick method..
<html>
<head>
<script src="lib/sweet-alert.js"></script>
<link rel="stylesheet" href="lib/sweet-alert.css">
</head>
<body>
<form method="post">
<label for="name">name</label>
<input type="text" name="name" id="name" />
<input type="submit" value="submit" name="submit" class="sub" id="sub" />
<?php
$a=mysql_connect("localhost","root","");
$a1=mysql_select_db("test",$a);
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$i=mysql_query("insert into student (name) values ('$name')");
if($i)
{
echo "<script>a();</script>";
}
}
?>
<script type="text/javascript">
function a(){
swal("Here's a message!");
};
</script>
</body>
</html>
You are trying to mix two incompatiable languages, PHP is Server side, JQuery is Client Side. The PHP script is already finished processing once your Browser displays the page so you can not then decide to interact with the browser from a PHP script.
You need to use Ajax from a javascript page if you want this kind of functionality.
Put javascript function declaration before your php script.
<script type="text/javascript">
function a(){
swal("Here's a message!");
};
</script>
<?php
$a=mysql_connect("localhost","root","");
$a1=mysql_select_db("test",$a);
if(isset($_POST['submit']))
{
$name=$_POST['name'];
$i=mysql_query("insert into student (name) values ('$name')");
if($i)
{
"<script>a();</script>";
}
}
?>
<?php
if($_REQUEST['submit']){
$i = "yes";
if($i == "yes"){
echo "<script>alert('hiii');</script>";
}
}
?>
<form action="" method="post">
<input type="submit" name="submit" value="submit">
</form>
I have 1 demo.php file for form and alert. And demo1.php file for php query.
I have to use Ajax for this.
demo.php:
<html>
<head>
<script src="lib/sweet-alert.js"></script>
<link rel="stylesheet" href="lib/sweet-alert.css">
<script src="js/jquery-1.8.0.min.js"></script>
</head>
<body>
<form method="post" class="frm" id="myform" onSubmit="j1">
<label for="name">name</label>
<input type="text" name="name" id="name" />
<input type="submit" value="submit" name="submit" class="sub" id="sub" />
</form>
<script>
function j1(){
var query = $('#myform').serialize();
var url = 'demo1.php';
$.post(url, query, function (response) {
swal({
title: "Thank You!",
type: "success",
confirmButtonColor: '#DD6B55',
confirmButtonText: 'Okay'
},
function(isConfirm){
if (isConfirm){
window.location.replace('demo.php');
}
});
});
}
$("#myform").submit(function(){
return false;
});
</script>
</body>
</html>
demo1.php:
<?php
$a=mysql_connect("localhost","root","");
$a1=mysql_select_db("test",$a);
$name=$_POST['name'];
$i=mysql_query("insert into student (name) values ('$name')");
?>
Hi i am trying to save value and alert them using ajax which i am insert using php in my sql table but my alert is not working
Here is my code
demo.php
<html>
<head>
<script>
function my(){
var name = document.getElementById("name").value;
var last_name = document.getElementById("last_name").value;
document.getElementsById('div1').style.backgroundColor = green;
var dataString = 'name='+name+'&last_name='+last_name;
$.ajax({
type:'POST',
data:dataString,
url:'demo.php',
success:function(data) {
alert(data);
}
});
} </script>
</head>
<body>
<form action="" method="post">
<input type="text" name="name" id="name" value="" />
<input type="text" name="last_name" id="last_name" value="" />
<input type="submit" name="Update" id="update" value="Update" onclick="my();" />
</form>
<div id="div1" style="width:300px;height: 50px;background-color: yellow;" >
</div>
</body>
</html>
<?php
include('conn.php');
if (isset($_POST['Update'])) {
$name = $_POST['name'];
$last_name = $_POST['last_name'];
echo $name;
$insert = "insert into ajaxsave values('$name','$last_name')";// Do Your Insert Query
if(mysql_query($insert)) {
echo "Success";
} else {
echo "Cannot Insert";
}
}?>
demo.html
<html>
<head>
</head>
<body>
<div id="div2" style="width:300px;height: 50px;background-color: yellow;" >
</div>
</body>
</html>
here i want when i submit form them div color should change which is in demo.html
where i am wrong in this code
and how can i achieve my goal
Any help will be appreciated
changes you need to make:
add jquery as a dependency as you are using $.ajax utility function which is provided by Jquery.
As you are using Jquery, you could use its selectors for getting values of elements and binding functions to dom elements. I have commented it in the source code.
You are using a form with a submit button and executing the ajax call on click of it. But you need to prevent the page from submitting the form by preventing the default behavior of the submit button. Refer event.preventDefault();
Move the php ajax response part to the top and call exit() once your response is complete. Else your ajax response will include the whole page html source also.
.
<?php
include('conn.php');
if (isset($_POST['Update'])) {
$name = $_POST['name'];
$last_name = $_POST['last_name'];
$insert = "insert into ajaxsave values('$name','$last_name')";// Do Your Insert Query
if(mysql_query($insert)) {
echo "Success";
} else {
echo "Cannot Insert";
}
//Call exit as your ajax response ends here. You dont need the html source along with it.
exit();
}
?>
<html>
<head>
</head>
<body>
<form action="" method="post">
<input type="text" name="name" id="name" value="" />
<input type="text" name="last_name" id="last_name" value="" />
<input type="submit" name="Update" id="update" value="Update" />
</form>
<div id="div1" style="width:300px;height: 50px;background-color: yellow;" >
</div>
<!-- include jquery dependeny before your js code block -->
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script>
$("#update").on("click",function(event) {
//Prevent Default submit button behavour. Prevent the form from submission.
event.preventDefault();
// using Jquery selectors for better readability of code.
var name = $("#name").val();
var last_name = $("#last_name").val();
$("#last_name").css("background-color","green");
$.ajax({
type:'POST',
data:{name:name,last_name:last_name,Update:true},
url:'demo.php',
success:function(data) {
alert(data);
}
});
});
</script>
</body>
</html>
You send two parameters in "dataString" variable, and then in php check undefined variable "Update"
So, just replace string
if (isset($_POST['Update'])) {
to
if (isset($_POST['name']) && isset($_POST['name'])) {
And add this line to tag
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
I'm very new to anything outside of PHP, so forgive me if this comes off as simple.
I'm trying to create a simple registration form, which then calls a PHP function, which inserts the data.
The problem is, the data doesn't seem to be going to the page.
My form:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(function () {
$('#register').on('submit', function (e) {
$.ajax({
type: 'POST',
url: 'http://warofman.com/actions.php?type=register',
data: $('#register').serialize(),
success: function () {
alert('Form was submitted.');
console.log(e);
}
});
e.preventDefault();
});
});
</script>
</head>
<body>
<form id="register">
Username: <input type="text" name="login"><br>
Email: <input type="text" name="email"><br>
Password: <input type="password" name="password"><br>
Confirm Password: <input type="password" name="confpass"><br>
<input type="submit" name="submit" value="Register">
</form>
</body>
</html>
And then, the PHP:
function register()
{
$login = $_POST['login'];
$email = $_POST['email'];
$password = $_POST['password'];
$confpass = $_POST['confpass'];
do_reg($login, $email, $password, $confpass);
}
Where do_reg() calls the process of registering.
Make the following changes, (follow good practice)
<form id="register" action="" method="post">
<label for="login">Username:</label>
<input id="login" type="text" name="login"><br>
<label for="email">Email:</label>
<input type="email" name="email" id="email" /><br>
<label for="password">Password:</label>
<input type="password" name="password" id="password"><br>
<label for="confpass">Confirm Password:</label>
<input type="password" name="confpass" id="confpass"><br>
<input type="submit" name="submit" value="Register">
</form>
On php side:
You are writing everything inside a function(register) and not calling it, instead do something like this,
if(isset($_POST['submit'])){
$login = $_POST['login'];
$email = $_POST['email'];
$password = $_POST['password'];
$confpass = $_POST['confpass'];
do_reg($login, $email, $password, $confpass);
}
You can't pass a query string in the URL using POST. Add the "type=register" to your data:
$.ajax({
type: 'POST',
url: 'http://warofman.com/actions.php',
data: "type=register&" + $('#register').serialize(),
success: function () {
alert('Form was submitted.');
console.log(e);
}
});
e.preventDefault();
});