Submit Form Without Reloading Page and Get Output [PHP, jQuery] - php

Hellow,
I've been trying to submit a form without reloading and getting PHP output on the same page. The main objective is to submit the form values to a PHP file and get the output sent by the PHP file.
To understand it better, let's take a look on following code snippet:
HTML & jQuery Code:
<html>
<head>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'on.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
</head>
<body>
<form>
<input id="name" name="name"><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
PHP Code:
<?php
if (isset($_POST['submit'])){
$name=$_POST['name'];
if($name == 'Johny'){
echo "Welcome Johny";
}
else{
echo "I Dont Know You";
}
}
?>
What I Want:
When user enter value in the Input box and submit it, the page should display output value e.g ECHO value without reloading the webpage.

To be more specific on my first comment, you have to put an exit statement after you echo the response so the rest of the code doesn't execute, also to check whether the form was sent or not you can add a hidden input in your form with the value "1" (<input name="formSent" type="hidden" value="1">) that gets checked in your PHP :
<?php
if (isset($_POST['formSent'])){
$name=$_POST['name'];
if($name == 'Johny'){
echo "Welcome Johny";
exit;
}
else{
echo "I Dont Know You";
exit;
}
}
?>
and then get the response from the ajax request in the success's callback parameter, also specify the method: 'POST' because jQuery's $.ajax function uses the method GET by default:
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'on.php',
method: 'POST',
data: $('form').serialize(),
success: function (message) {
alert(message);
}
});
});
});
</script>

Related

How to pass data from a PHP file back to the original without page refresh?

I am trying to have the output from a PHP file display in the original page containing the form, without having to refresh the page.
I am currently using AJAX to do so but I am not able to pass the value of the submitted PHP file back to the index.php page - this needs to be done without having the page refreshed.
Overall
User enters some data and submits the form
That data is passed to a PHP file through AJAX
Some pieces of data, which were manipulated through the PHP file, are then echoed out onto the original index.html file without the page refreshing
Below you will find the code that I am currently using to try and achieve this.
index.php
<form>
<input type="text" name="hi">
<input type="submit">
</form>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
});
});
});
</script>
post.php
<?php
echo "Hello";
$name = $_POST['hi'];
echo $name . "This is a test";
?>
I would appreciate any help, thanks!
How about this simple solution. Just copy and paste this code into a file called index.php and whatever text you enter in the input field will be outputted by PHP. Hope it helps!.
<?php
$data = array();
if(isset($_POST['userText']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH'])){
$data = 'The data you entered is: ' . $_POST['userText'];
echo json_encode($data);
die();
}
?>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form>
<input type="text" name="hi" id = "someID">
<input type="submit" id = "sendInfo">
</form>
<div id = "random"></div>
<script type = "text/javascript">
$("#sendInfo").click(function(){
var someText = document.getElementById("someID").value;
var userText = JSON.stringify(someText);
$.ajax({
url: "index.php",
method: "POST",
dataType: "json",
data: {userText: userText},
success: function (result) {
console.log(result);
$("#random").html(result);
}
});
return false;
});
</script>
</body>
</html>
Add 'success' to your object and pass in a parameter to the function. That will hold the results from the php file.
$.ajax({
type: 'post',
url: 'post.php',
data: $('form').serialize(),
success: function(results) {
console.log(results);
}
});
What this does is, on a successful ajax call, stores all of the content sent from the post.php file into the results variable.' In this case it will be whatever $name is and 'This is a test.'

Form submit supposed to refresh only Div, but instead refreshes Page

I have a PHP page included called 'leaguestatus.php'. This page allows the user to post a message/status update and the intent is to have only this part of the div refreshed; however, on submit, the entire page is reloaded.
In the current implementation I'm simply printing all the $_POST variables to the div so I can see what's coming through. The MsgText textarea DOES get posted, however, it's only after the whole page loads. I'm trying to get just the div and that included file to reload.
div id="statusupdates"><? include 'leaguestatus.php'; ?></div>
leaguestatus.php
<form id="statusform" method="POST">
<textarea name=MsgText rows=5 cols=40></textarea><BR>
<input type=submit value=Post id=uhsbutton>
</form>
<BR>
<BR>
<div id='formbox'>
<? print "<pre>POST Variables:<BR>";
print_r ($_POST);
print "</pre>";
$MsgText = $_POST["MsgText"];
?>
</div>
The jQuery I'm running in the header is:
$(document).ready(function() {
$("#statusform").submit(function(e) {
e.preventDefault();
var formData=$(this).serialize();
var pUrl="leaguestatus.php";
submitFormSave(formData, pUrl);
});
function submitFormSave(formData, pUrl) {
$.ajax({
url: pUrl,
type: 'POST',
data:formData,
success: function(response) {
$("#formbox").html(response);
}
}).success(function(){
});
}
});
Here are my includes:
html header
<link rel="stylesheet" href="css/jquery-ui.css">
<script src="js/jquery-1.9.1.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
Edit: updated code to reflect use of #sazedul's response. Only issue now is on first click page acts as expected (no page refresh). On second click the entire page reloads. On third click we're back to normal.
Use this following code for ajax submit hope it will work.
$("#statusform").submit(function(e) {
e.preventDefault();
var formData=$(this).serialize();
var pUrl="leaguestatus.php";
submitFormSave(formData, pUrl);
});
function submitFormSave(formData, pUrl)
{
$.ajax({
url: pUrl,
type: 'POST',
data:formData,
success: function(response)
{
$("#formbox").html(response);
}
});
}
Made the following changes in your leaguestatus.php remembar to put double quote in the name="MsgText" in text area.
<form id="statusform" method="POST">
<textarea name="MsgText" rows=5 cols=40></textarea><BR>
<input type=submit value=Post id=uhsbutton>
</form>
<BR>
<BR>
<div id='formbox'>
</div>
<?php
if(isset($_POST['MsgText'])){
$message=$_POST['MsgText'];
echo $message;
}
?>
check for .load() like the code below....
$(document).ready(function() {
$("#statusform").submit(function() {
$("div").load();
});
});
You have to preventDefault of submit then other thing
so,you have to use e.preventDefault() to prevent submit.then do what ever you want
$("#statusform").submit(function(e) {
e.preventDefault();
......

Callback message for php form

I just want to know how i can send a "callback" message for "success" or "error".
I really don't know much about jquery/ajax, but, i tried to do this:
I have a basic form with some informations and i sent the informations for a "test.php" with POST method.
My send (not input) have this id: "#send". And here is my JS in the index.html
$(document).ready(function() {
$("#send").click(function(e) {
e.preventDefault();
$(".message").load('teste.php');
});
});
And, in my PHP (test.php) have this:
<?php
$name = $_POST['name'];
if($name == "Test")
{
echo "Success!";
}
else{
echo "Error :(";
}
?>
When i click in the button, the message is always:
Notice: Undefined index: name in /Applications/XAMPP/xamppfiles/htdocs/sites/port/public/test.php on line 3
Error :(
Help :'(
This is your new JS:
$(document).ready(function()
{
$("#send").click(function(e) {
e.preventDefault();
var form_data = $("#my_form").serialize();
$.post('teste.php', form_data, function(data){
$(".message").empty().append(data);
});
});
});
This is your new HTML:
<form id="my_form">
<input type="text" name="name" value="" />
<input type="button" id="send" value="Send" />
</form>
The problem is you have not passed name data to your PHP Use My Javascript Code.
Problem in understanding please reply
$(document).ready(function() {
$(document).on('click','#send',function(e)
{
var params={};
params.name="Your Name ";
$.post('test.php',params,function(response)
{
e.preventDefault();
alert(response); //Alert Response
$(".message").html(response); //Load Response in message class div span or anywhere
});
});
});
This is somewhat more complicated by you can use it more generally in your project. just add a new callback function for each of the forms that you want to use.
<form method="POST" action="test.php" id="nameForm">
<input name="name">
<input type="submit">
</form>
<script>
// wrap everything in an anonymous function
// as not to pollute the global namespace
(function($){
// document ready
$(function(){
$('#nameForm').on('submit', {callback: nameFormCallback },submitForm);
});
// specific code to your form
var nameFormCallback = function(data) {
alert(data);
};
// general form submit function
var submitForm = function(event) {
event.preventDefault();
event.stopPropagation();
var data = $(event.target).serialize();
// you could validate your form here
// post the form data to your form action
$.ajax({
url : event.target.action,
type: 'POST',
data: data,
success: function(data){
event.data.callback(data);
}
});
};
}(jQuery));
</script>

Sending form value using ajax, jquery,php

I am new to ajax and jQuery. I am trying get html form value using ajax and jQuery. I am getting the value but i can not pass that value to another php file. I don't know what i am missing.. can someone help me please..
Here is my form.php file code:
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Form</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var srt = $("#input").serialize();
// alert is working perfect
alert(srt);
$.ajax({
type: 'POST',
url: 'database.php',
data: srt,
success: function(d) {
$("#someElement").html(d);
}
});
});
});
</script>
</head>
<body>
<form id="input" method="post" action="">
First Name:<input type="text" name="firstName" id="firstName">
Last Name: <input type="text" name="lastName" id="lastName">
<input type="submit" id="submit" value="submit " name="submit">
</form>
<div id="someElement"></div>
</body>
</html>
Here is my database.php file code:
<?php
if(isset($_POST['submit']))
{
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
echo $firstName;
echo $lastName;
}
You need to add:
return false;
to the end of your click handler. Otherwise, the default submit button action takes place, and the page is refreshed.
Also, remove the line:
if (isset($_POST['submit']))
Submit buttons aren't included when you call .serialize() on a form, they're only sent when the submit button is performing normal browser submission (in case there are multiple submit buttons, this allows the server to know which was used).
You need to do the following
$('#submit').click(function(){
var srt = $("#input").serialize();
// alert is working perfect
alert(srt);
$.ajax({
type: 'POST',
url: 'database.php',
data: srt,
success: function(d) {
$("#someElement").html(d);
}
return false;
});
Form default event will fire if you dont use return false.
You can use as below
$("#input").submit(function(event) {
var srt = $("#input").serialize();
// alert is working perfect
alert(srt);
$.ajax({
type: 'POST',
url: 'database.php',
data: srt,
success: function(d) {
$("#someElement").html(d);
}
})
return false;
});
You need to prevent the default action of click event or the form will be processed using the default form action and your ajax call will never be complete.
$("#input").submit(function(event) {
event.preventDefault(); // prevent default action
var srt = $("#input").serialize();
// alert is working perfect
alert(srt);
$.ajax({
type: 'POST',
url: 'database.php',
data: srt,
success: function(d) {
$("#someElement").html(d);
}
});
});

Pass javascript variable to php with ajax and the result doesn't show anything

This is my code and i want to pass javascript variable with ajax to php when i click submit button then the result doesn't show var_data variable from javascript What code is wrong?
This is edit order one before everybody help me
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/ajax/PassVariable.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<?php
$test = $_GET['var_PHP_data'];
echo $test;
?>
</body>
</html>
and this is source code now
<?php
if (isset($_GET['var_PHP_data'])) {
echo $_GET['var_PHP_data'];
} else {
?>
<!DOCTYPE html>
<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>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/test.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
$('#result').html(data)
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<div id="result">
</body>
</html>
<?php } ?>
this statement if(isset($_GET['var_PHP_data'])) output false and then show Hello World What should i do to do for isset($_GET['var_PHP_data']) is true?
Your solution has PHP issues: you don't check if the data exists, and also, you don't do anything with the result. I've modified the script to do the following:
Check if the var_PHP_data var is set (in PHP, on the server).
If yes, just send a blank text response containing that data.
If no, then draw the form and everything else.
In the form, I've created a #result div.
Ajax response will be shown in this div.
Also make sure that you host the script at localhost and that it is called test.php. To make sure this is resilient, you can change the Ajax URL to
<?php echo $_SERVER['PHP_SELF'];?> to make sure that you'll hit the correct script.
<?php
if (isset($_GET['var_PHP_data'])) {
echo $_GET['var_PHP_data'];
} else {
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js">
<script>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/test.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
$('#result').html(data)
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<div id="result">
</body>
</html>
<?php } ?>
Try jQuery Form its this will help to solve many problems.
For you question: try url without domain name, add tags 'form', change event click to submit, add data type
what are the contents of PassVariable.php ? if is the same where you have they jquery bit wont work coz php will print all the page again, if the file is different try
success: function(data) {
alert('databack = '+ data);
}
Try placing your input into a form and attaching the ajax call to the form onsubmit event. The way it happens in the provided happen is when you click in the field, in which case it submits before you can write anything really.
$(document).ready(function() {
$('#brn').click(function() {
var var_data = "Hello World";
alert("click works");
$.ajax({
url: 'http://localhost/ajax/PassVariable.php',
type: 'GET',
data: { x: var_data },
success: function(data) {
alert(data);
}
});
});
});
change it to this code
then in PassVariable.php put
make button
<input type="button" id="btn" value="click me" />
it should work because it is very basic example. If it doesn't work check your console if there are any JavaScript errors and remove them.

Categories