I am having a difficult time trying to make the Ajax request $.post() from Jquery work. I would like to send data from a form with $.post() and retrieve it as php variables in order to further process them into an SQL database.
Below, I put a simplified version of my problem in a one page code (the Jquery posts to the same page when the function is triggered). I wish to use this method in order to not trigger a page reload when submitting the form.
The problem : my post() function works, I get the correct alert stating the data posted, BUT, print_r($_POST) check method stays empty after I submit my request.
My question : how can I get the posted data into php variables ($_POST['name'] & $_POST['email'] ?
<!DoCType html>
<html lang="fr-CH">
<head>
<title> TEST </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="/JS/jquery-3.3.1.min.js"></script>
</head>
<body>
<?php
print_r($_POST); // always returns an empty array, even after clicking the submit button
if (isset($_POST['name'])) {
echo "PHP received data";
} else {
echo "It did not work";
}
?>
<div class='caseform'>
<form id="form" method="post">
Name:<br> <input type="text" name="name"> <br>
Email:<br> <input type="text" name="email"> <br>
<button id="button"> Submit </button>
</form>
</div>
<script>
$( document ).ready(function() {
$("#button").click(function( event ) {
event.preventDefault();
var postData = $('#form').serialize();
// the $.post goes to the same php file "test.php"
var jqxhr = $.post("test.php", postData ,function() {
}).done(function() {
// this works, I get an alert with postData from my form (name=&email=)
alert(postData);
}).fail(function() {
alert("Error submitting the form.");
})
});
});
</script>
</body>
</html>
The issue is you haven't got anything to prevent the post handling code from running for a GET request. When you initially load the page it is a GET request, and it is running your print_r($_POST) which of course is empty.
Wrap that code in a check like this, and move it to the top of the file.
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST'){
print_r($_POST); // always returns an empty array, even after clicking the submit button
if (isset($_POST['name'])) {
echo "PHP received data";
} else {
echo "It did not work";
}
exit();
}
?><!DoCType html>
...
...
Related
i'm new in PHP i don't know howto use this function...output is a button but when i click on button function not run. i want to get data from database.
<?php include('config.php');
if (isset($_POST['submit'])) {
$sql = "SELECT book_name from books";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "book name: " . $row["book_name"]. "<br>";
}
} else {
echo "0 results";
}
}
$conn->close();
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<form action="check.php" method="post">
<input type="submit" name="btn">
</form>
</body>
</html>
Just change isset($_POST['submit']) by isset($_POST['btn']).
When you submit your form, you send all the input name with $_POST method.
Here you have only ONE input with name = 'btn'.
I do this test :
<?php
if (isset($_POST['btn'])) {
echo 'IT WORKS !';
}
?>
And it works for me, after clicking on "Valider" I got my echo :
Here is an example of how you can try to do it using jQuery and Ajax. I tried to explain how it works and made an example that edit your book list without reloading the page on submit. Hope it helps !
$(document).ready(function() {
// When the form with id 'get_book_list' is sumbit, I will do something :
$("#get_book_list").on('submit', function(e) {
e.preventDefault();
// This is how an ajax call looks like (one example) :
// $.ajax({
// type: "POST", // the method you will use to send the data
// url: "yourfile.php", // the php file you want to call
// data : /* the data you want to send in your php file */,
// dataType: "json", // the data type you want to receive from the php file
// success: function(response){
// // Do something if the ajax call works : here you will edit your book list
// // 'response' is what the php will return, here imagine it's a JSON (dataType = 'json')
// },
// error: function(x,e,t){
// // Do something if the ajax call return error
// }
// });
//I will do the same but without the Ajax :
// 1/ Imagine you are in the success part of the ajax call
// 2/ This is the "response" you get from the php after the select :
var response = [{"book_name" : "title1"}, {"book_name" : "title2"}, {"book_name" : "title3"}];
// 3/ Now just edit your book_list to get what you want :
// I will build a list with each title
var book_list = "<ul>";
$.each(response, function(key, book) {
book_list += "<li>"+book.book_name+"</li>";
});
book_list += "</ul>";
// I add my list in my div
$('.book-list').html(book_list);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<div class="book-list">
<!-- here you will update the list of book -->
</div>
<form action="" method="post" id="get_book_list">
<input type="submit" name="btn">
</form>
</body>
</html>
your form actions says "check.php". As a result, when you hit the submit button, you get redirected to check.php page.
your form should simply be like
<form action="" method="post">
<input type="submit" name="btn">
</form>
when action="", the if part of your php will get executed for your current case
isset($_POST['submit']) is false, you should submit some info. you can add <input type="text" name="submit" value="1" />, lets your form have info.
I have an index.php page that I want to receive information from a user in a textArea, and, upon hitting save, the variable should be posted to another page called changePage.inc.php. Once the post variable has been set onto the other page, the changePage.inc.php should redirect away from the original index.php to a page called secondPage.php.
variable in jquery on index.php -> same variable as a post on changePage.inc.php
-> user is redirected off of index.php to secondPage.php, as instructed by changePage.inc.php
File named index.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<script>
$(document).ready(function(){
$('#saveForm').submit(function(event){
event.preventDefault();
var message = "";
var changeText = function(){
message = "You wrote: " + $('#text').val();
};
var send = function(){
if(message !== ""){
$.post("includes/changePage.inc.php", {message: message});
window.location.href = "includes/changePage.inc.php";
}
};
changeText();
send();
});
});
</script>
<body>
<textArea id="text"></textArea>
<form id="saveForm" action="includes/changePage.inc.php" method="POST">
<button type="submit" id="saveButton">Save!</button>
</form>
</body>
</html>
File name changePage.inc.php
<?php
session_start();
if(isset($_POST['message'])){
header("Location: ../secondPage.php");
}
exit();
File named secondPage.php
<?php
echo 'Hello World';
?>
With the code as it is right now, it gets to changePage.inc.php, but not secondPage.php. I believe that the post variable is either not being set at all, or being set too late (maybe this is because of a race condition).
I have asked this question before and thought that an answer using function(data) within the $.post() method to create an object with $.parseJSON(data) was going to work. But upon running the code, errors were generated, so now I am asking it again. This is the previous attempt: POST variable from jquery redirecting but is not set
Redirect to secondPage.php in the Javascript, not PHP. And do it in the callback function of $.post so it waits for the script to complete.
var send = function(){
if(message !== ""){
$.post("includes/changePage.inc.php", {message: message}, function() {
window.location.href = "includes/secondPage.php";
});
}
};
But much simpler would be to just add message as an input in the form, and let the form submit normally.
$("#saveForm").submit(function() {
$("#message").val("You wrote: " + $("#text").val());
}
<textArea id="text"></textArea>
<form id="saveForm" action="includes/changePage.inc.php" method="POST">
<input type="hidden" name="message" id="message">
<button type="submit" id="saveButton">Save!</button>
</form>
Don't leave the page just after triggering an AJAX request, wait for the result using the callback.
$.post("includes/changePage.inc.php", {message: message}, function (data) {
// here you see 'Hello World' in your browser console
console.log(data);
// here you don't see anything in your browser window because it is no POST
window.location.href = "includes/changePage.inc.php";
});
But why to trigger an ajax request and redirect to the same page afterwards...
Maybe this is what's intended (second try):
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
</head>
<body>
<script>
$(document).ready(function(){
$('#saveForm').submit(function(event){
// NO: event.preventDefault();
var message = "";
var changeText = function(){
message = "You wrote: " + $('#text').val();
};
changeText();
// Check for text as message can't be empty here
if (!$('#text').val()){
// preventDefault() here if text is empty
event.preventDefault();
}
});
});
</script>
<form id="saveForm" action="includes/changePage.inc.php" method="POST">
<!-- put textarea inside your form, and write tags in lowercase -->
<textarea id="text"></textarea>
<button type="submit" id="saveButton">Save!</button>
</form>
</body>
</html>
This site has been really helpful while writing this program. Unfortunately, I hit a snag at some point, and have boiled the problem down quite a bit since. At this point, I am looking at three files, a .html that contains a form, a .js that contains my event handlers, and a .php that receives my post variables and contains new content for the form.
I am getting the post data from the initial text input just fine. The new form content is set as I would expect. However, after this form content is set to a new input of type button with a class of button, the post method in my button class handler is not setting post data on login.php as I expect it to.
Here is my code:
Contents of interface.html page:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<form id="interface" action="login.php" method="post">
<input type="text" value="enter username here" name="user"/>
<button id="submit">submit</button>
</form>
<script src='events.js'></script>
</body>
</html>
Contents of events.js file:
$("#submit").click(function(){
$.post(
$("#interface").attr("action"),
$(":input").serialize(),
function(info){$("#interface").html(info);}
);
});
$(".button").click(function(){
var $this=$(this);
$.post(
$("#interface").attr("action"),
{data:$this.val()},
function(info){$("#interface").html(info);}
);
});
$("#interface").submit(function(){
return false;
});
Contents of login.php file:
<?php
if(isset($_POST['user'])){
echo '<input type="button" class="button" value="set data"/>';
}else if(isset($_POST['data'])){
echo 'data is set';
}
?>
You need to wait until the button exists to bind an event to it. Additionally, i'd switch from click to submit and drop the click event binding on .button completely.
//$("#submit").click(function () {
$("#interface").submit(function (e) {
e.preventDefault();
var $form = $(this), data = $form.serialize();
if ($form.find(".button").length && $form.find(".button").val() ) {
data = {data: $form.find(".button").val()};
}
$.post($form.attr("action"), data, function (info) {
$form.html(info);
});
});
//$("#interface").submit(function () {
// return false;
//});
Since the form is not being replaced, and the event is on the form, you no longer need to re-bind anything.
I`m trying to make somethig like login with jquery. There should be a validation on text fields to echo error message. If the form is completely validated then function in jquery should update the div, where there is the input form and change it to the session name. But There is a problem, when posted form is validated then div remains empty, there is no session name.
HTML:
<html>
<head>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script type="text/javascript">
jQuery(function(){
jQuery('#form').submit(function(){
jQuery.ajax({
type: 'POST',
url: jQuery('#form').attr('action'),
data: jQuery('#form').serialize(),
success: function(data){
if(data == 'success'){
jQuery('#user').load(location.href+' #user>*');
}else{
jQuery('#info').html(data);
}
}
});
return false;
});
});
</script>
</head>
<body>
<div id="user">
<div id="info"></div>
<?php
session_start();
if(isset($_SESSION['user'])){
echo $_SESSION['user'];
}else{
echo '
<form method="post" action="session.php" id="form">
<input type="text" name="user" />
<input type="submit" name="do" value="ok" />
</form>
';
}
?>
</div>
</body>
</html>
PHP:
<?php
$user = mysql_real_escape_string($_POST['user']);
if(empty($user)){
echo 'psc';
}else{
echo 'success';
session_start();
$_SESSION['user'] = $user;
}
?>
I think type: 'POST' in your ajax call is usually done in lower case: type: 'post'. I am not sure if this is the issue, but you may want to try it.
Aside from that, the other problem with your code is that you are not preventing the form from being submitted. So basically you are sending an ajax message, but then immediately loading a new page with the default submit that occurs when clicking the submit button. I would think that this has the effect of loading a blank page?
To fix this you could add to your submit handler the following lines:
jQuery('#form').submit(function(event){
event.preventDefault();
Notice I have added event to the handlers arguments, and then called the preventDefault() method to stop the form from actually submitting. Returning false in the handler does not do this for you.
this a simple example in how to submit form using the Jquery form plugins and retrieving data using html format
html Code
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#htmlForm').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#htmlExampleTarget',
// success identifies the function to invoke when the server response
// has been received; here we apply a fade-in effect to the new content
success: function() {
$('#htmlExampleTarget').fadeIn('slow');
}
});
});
</script>
</head>
<body>
<form id="htmlForm" action="post.php" method="post">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>
PHP Code
<?php
echo '<div style="background-color:#ffa; padding:20px">' . $_POST['message'] . '</div>';
?>
this just work fine
what i need to know if what if i need to Serialize the form fields so how to pass this option through the JS function
also i want show a loading message while form processed
how should i do that too
thank you
To serailize and post that to a php page, you need only jQuery in your page. no other plugin needed
$("#htmlForm").submit(function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData}, function(data) {
//do whatever with the response here
});
});
If you want to show a loading message, you can do that before you start the post call.
Assuming you have div with id "divProgress" present in your page
HTML
<div id="divProgress" style="display:none;"></div>
Script
$(function(){
$("#htmlForm").submit(function(){
$("#divProgress").html("Please wait...").fadeIn(400,function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData},function(data) {
//do whatever with the response here
});
});
});
});
The answer posted by Shyju should work just fine. I think the 'dat' should be given in quotes.
$.post("post.php", { 'dat': serializedData},function(data) {
...
}
OR simply,
$.post("post.php", serializedData, function(data) {
...
}
and access the data using $_POST in PHP.
NOTE: Sorry, I have not tested the code, but it should work.
Phery library does this behind the scenes for you, just create the form with and it will submit your inputs in form automatically. http://phery-php-ajax.net/
<?php
Phery::instance()->set(array(
'remote-function' => function($data){
return PheryResponse::factory('#htmlExampleTarget')->fadeIn('slow');
}
))->process();
?>
<?php echo Phery::form_for('remote-function', 'post.php', array('id' => ''); ?> //outputs <form data-remote="remote-function">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>