I have a form with an onkeyup event.
I try to send a variable to my php script and show result in a div.
Thanks to this forum I got my test function to half work:
jQuery.post(the_ajax_script.ajaxurl,
If I continue with:
1) jQuery("#theForm").serialize(),
I get response text which is "Hello World"
If I try to pass a variable:
2) { name: "p" },
I get: -1
JavaScript
function submit_me(){
jQuery.post(
the_ajax_script.ajaxurl,
{ name: "p" },
function(response_from_the_action_function){
jQuery("#txtHint").html(response_from_the_action_function);
}
);
}
PHP
<?php
function the_action_function(){
$name = $_POST['name'];
echo "Hello World, " . $name;
die();
}
?>
FORM
<form id="theForm">
<input type="text" name="user">
<input name="action" type="hidden" value="the_ajax_hook">
<input id="submit_button" value = "Click This" type="button" onkeyup="submit_me()">
<form>
I actually want onkeyup="submit_me(this.value, 0)"
I am doing this on a WordPress through their admin-ajax.php file.
Where is the problem in this?
EDIT
Apparently I had to add action to data
{ action:'the_ajax_hook', name:"p" }
I guess its WP requirement, rather than jQuery, because I saw examples as this:
$.post("test.php", { name: "John", time: "2pm" }
everywhere.
Something like this should work:
<html>
<head>
<script>
$(document).ready(function() {
$("#my_form").submit(function(event) {
event.preventDefault() // to prevent natural form submit action
$.post(
"processing.php",
{ name: "p" },
function(data) {
var response = jQuery.parseJSON(data);
$("#txtHint").html(response.hello_world);
}
);
});
});
</script>
</head>
<body>
<form id="my_form" action="/" method="post">
<input type="text" name="user" />
<input name="action" type="hidden" value="the_ajax_hook" />
<input type="button" name="submit" value = "Click This" />
</form>
<div id="txtHint"></div>
</body>
</html>
And then in processing.php:
<?php
$name = $_POST['name'];
$response['hello_world'] = "Hello World, " . $name;
echo json_encode($response);
?>
Related
When the user submits the form, the result should be displayed without page refreshing. The PHP script is also in the same HTML page.
What is wrong withe $.post jQuery?
<!--
Submit form without refreshing
-->
<html>
<head>
<title>My first PHP page</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#btn").click(function(event) {
var myname = $("#name").val();
var myage = $("#age").val();
$.post(
"23.php", $("#testform").serialize()
);
});
});
</script>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="testform">
<!-- $_SERVER['PHP_SELF'] array -->
Name:
<input type="text" name="name" id="name" />Age:
<input type="text" name="age" id="age" />
<input type="submit" name="submit" id="btn" />
</form>
</body>
</html>
<?php
if ( isset($_POST['submit']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>
You need to use event.preventDefault in your javascript
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
$.post(
"23.php", $( "#testform" ).serialize()
);
});
Yes, you need e.preventDefault. Also, I think these var myname and myage variables are unnecessary since you're serializing the entire form in $.post.
Try this:
$(document).ready(function() {
$("#btn").click(function(e) {
e.preventDefault();
$.post(
"23.php", $("#testform").serialize()
);
});
});
Hope this helps.
Peace! xD
This is my finalized complete code after following your all suggestions. But it is still refreshing when getting results. Let's see if I have made any further error in the code. Thanks for your all helps.
UPDATE! - All these HTML and PHP scripts resides in the same file called 23.php
<!--
Submit form without refreshing
-->
<html>
<head>
<title>My first PHP page</title>
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
yourData ='myname='+myname+'&myage='+myage;
$.ajax({
type:'POST',
data:yourData,//Without serialized
url: '23.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
alert('Submitted');
}else{
return false;
}
};
});
});
});
</script>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="testform"> <!-- $_SERVER['PHP_SELF'] array -->
Name: <input type="text" name="name" id="name"/>
Age: <input type="text" name="age" id="age"/>
<input type="submit" name="submit" id="btn"/>
</form>
</body>
</html>
<?php
if ( isset($_POST['submit']) ) { //was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>
I have two page one customform.php and another is preview.php.
I want to send some data which are values of some text-fields on customform.php using jquery post method. But I dont want the page to load. So I have used some JQuery code for this work. But now working for me.
the html code on customform.php is:
<form action="#" method="post">
<input type="text" value="" id="text1">
<input type="text" value="" id="text2">
<input type="button" value="preview" id="preview">
</form>
The jQuery code on customform.php is:
$('#previewph').click( function() {
var v1 = $.('#text1').val();
var v2 = $.('#text2').val();
alert("Mail: " + v1 + " Message: " + v2);
$.post( "http://www.lexiconofsustainability.com/lex_tmp2/preview/" ,{ name : v1 , title :v2 });
window.open("http://www.lexiconofsustainability.com/lex_tmp2/preview/", '_blank');
});
And on the preview.php I want to retrieve value form post method and echo them.
<?php
echo $authorname = $_POST['name'];
echo $posttitle = $_POST['title'];
?>
Simply Try this
<form action="#" method="post" >
<input type="text" value="" id="text1">
<input type="text" value="" id="text2">
<input type="submit" value="preview" id="preview" onclick="senddata()" >
</form>
<div id="message"></div>
function senddata() {
var v1 = $.('#text1').val();
var v2 = $.('#text2').val();
$.post("http://www.lexiconofsustainability.com/lex_tmp2/preview/", { name : v1 , title :v2 },
function(data) {
document.getElementById("message").innerHTML = data;
});
}
You can use AJAX for this..
The jQuery code on customform.php should be:
$('#previewph').click( function() {
var v1 = $('#text1').val();
var v2 = $('#text2').val();
$.post("preview.php", {name:v1, title:v2}, function(data)
{
alert(data);
});
});
preview.php
<?php
if(isset($_POST['name'])&&($_POST['title']))
{
echo $authorname = $_POST['name'];
echo $posttitle = $_POST['title'];
}
?>
I have created a page called functioncalling.php that contains two buttons, Submit and Insert.
I want to test which function is executed when a button gets clicked. I want the output to appear on the same page. So, I created two functions, one for each button.
<form action="functioncalling.php">
<input type="text" name="txt" />
<input type="submit" name="insert" value="insert" onclick="insert()" />
<input type="submit" name="select" value="select" onclick="select()" />
</form>
<?php
function select(){
echo "The select function is called.";
}
function insert(){
echo "The insert function is called.";
}
?>
The problem here is that I don't get any output after any of the buttons are clicked.
Where exactly am I going wrong?
Yes, you need Ajax here. Please refer to the code below for more details.
Change your markup like this
<input type="submit" class="button" name="insert" value="insert" />
<input type="submit" class="button" name="select" value="select" />
jQuery:
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert("action performed successfully");
});
});
});
In ajax.php
<?php
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'insert':
insert();
break;
case 'select':
select();
break;
}
}
function select() {
echo "The select function is called.";
exit;
}
function insert() {
echo "The insert function is called.";
exit;
}
?>
Button clicks are client side whereas PHP is executed server side, but you can achieve this by using Ajax:
$('.button').click(function() {
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
In your PHP file:
<?php
function abc($name){
// Your code here
}
?>
You should make the button call the same page and in a PHP section check if the button was pressed:
HTML:
<form action="theSamePage.php" method="post">
<input type="submit" name="someAction" value="GO" />
</form>
PHP:
<?php
if($_SERVER['REQUEST_METHOD'] == "POST" and isset($_POST['someAction']))
{
func();
}
function func()
{
// do stuff
}
?>
You cannot call PHP functions like clicking on a button from HTML. Because HTML is on the client side while PHP runs server side.
Either you need to use some Ajax or do it like as in the code snippet below.
<?php
if ($_GET) {
if (isset($_GET['insert'])) {
insert();
} elseif (isset($_GET['select'])) {
select();
}
}
function select()
{
echo "The select function is called.";
}
function insert()
{
echo "The insert function is called.";
}
?>
You have to post your form data and then check for appropriate button that is clicked.
To show $message in your input:
<?php
if(isset($_POST['insert'])){
$message= "The insert function is called.";
}
if(isset($_POST['select'])){
$message="The select function is called.";
}
?>
<form method="post">
<input type="text" name="txt" value="<?php if(isset($message)){ echo $message;}?>" >
<input type="submit" name="insert" value="insert">
<input type="submit" name="select" value="select" >
</form>
To use functioncalling.php as an external file you have to include it somehow in your HTML document.
Try this:
if($_POST['select'] and $_SERVER['REQUEST_METHOD'] == "POST"){
select();
}
if($_POST['insert'] and $_SERVER['REQUEST_METHOD'] == "POST"){
insert();
}
You can write like this in JavaScript or jQuery Ajax and call the file
$('#btn').click(function(){
$.ajax({
url:'test.php?call=true',
type:'GET',
success:function(data){
body.append(data);
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<form method='get' >
<input type="button" id="btn" value="click">
</form>
<?php
if(isset($_GET['call'])){
function anyfunction(){
echo "added";
// Your funtion code
}
}
?>
The onclick attribute in HTML calls JavaScript functions, not PHP functions.
I was stuck in this and I solved it with a hidden field:
<form method="post" action="test.php">
<input type="hidden" name="ID" value"">
</form>
In value you can add whatever you want to add.
In test.php you can retrieve the value through $_Post[ID].
Use a recursive call where the form action calls itself. Then add PHP code in the same form to catch it. In foo.php your form will call foo.php on post
<html>
<body>
<form action="foo.php" method="post">
Once the form has been submitted it will call itself (foo.php) and you can catch it via the PHP predefined variable $_SERVER as shown in the code below
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "caught post";
}
?>
</form>
</body>
</html>
Here is an example which you could use:
<html>
<body>
<form action="btnclick.php" method="get">
<input type="submit" name="on" value="on">
<input type="submit" name="off" value="off">
</form>
</body>
</html>
<?php
if(isset($_GET['on'])) {
onFunc();
}
if(isset($_GET['off'])) {
offFunc();
}
function onFunc(){
echo "Button on Clicked";
}
function offFunc(){
echo "Button off clicked";
}
?>
Calling a PHP function using the HTML button: Create an HTML form document which contains the HTML button. When the button is clicked the method POST is called. The POST method describes how to send data to the server. After clicking the button, the array_key_exists() function called.
<?php
if(array_key_exists('button1', $_POST)) {
button1();
}
else if(array_key_exists('button2', $_POST)) {
button2();
}
function button1() {
echo "This is Button1 that is selected";
}
function button2() {
echo "This is Button2 that is selected";
}
?>
<form method="post">
<input type="submit" name="button1" class="button" value="Button1" />
<input type="submit" name="button2" class="button" value="Button2" />
</form>
source: geeksforgeeks.org
You can simply do this. In php, you can determine button click by use of
if(isset($_Post['button_tag_name']){
echo "Button Clicked";
}
Therefore you should modify you code as follows:
<?php
if(isset($_Post['select']){
echo "select button clicked and select method should be executed";
}
if(isset($_Post['insert']){
echo "insert button clicked and insert method should be executed";
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<body>
<form action="functioncalling.php">
<input type="text" name="txt" />
<input type="submit" name="insert" value="insert" onclick="insert()" />
<input type="submit" name="select" value="select" onclick="select()" />
</form>
<script>
//This will be processed on the client side
function insert(){
window.alert("You click insert button");
}
function select(){
window.alert("You click insert button");
}
</script>
</body>
</html>
I have the following HTML code:
<form method="post" action="the_file.php" id="the-form">
<input type="text" name="the_input" value="<?php if ( isset( $_POST['the_input'] ) echo $_POST['the_input]; ?>">
<button type="submit" name="eat_something" value="TRUE">Eating</button>
<button type="submit" name="eat_something" value="FALSE">Don't Eat</button>
</form>
<textarea id="result"></textarea>
Followed by this JS:
$('#the-form').bind('submit', submitForm);
function submitForm(evt) {
jQuery.post(
$(this).attr('action'),
$(this).serialize(),
function(data) {
$('#result').empty().append(data).slideDown();
});
evt.preventDefault();
}
I also have a PHP script that receives the $_POST value from the input on submit and runs a conditions to test which submit button was clicked.
Like this:
$input = $_POST['the_input'];
$eating = $_POST['eat_something'];
if ( $eating == 'TRUE' ) {
// Do some eating...
} else {
// Don't you dare...
}
If I don't use the jQuery.post() function the submit values from the button are posted. However, for some reason, I can't manage to pass the button value to PHP $_POST with the jQuery.post() function. If I don't use jQuery.post() the output doesn't get appended to the textarea but rather in a text format on a separate page, like a document. I've also tried calling the submit function on the button $('button[type=submit]').bind('submit', submitForm); but this doesn't solve my problem either.
Thanks in advance for you help.
You forget signle quote and ) in the_name input.
<input type="text" name="the_input" value="<?php if (isset($_POST['the_input'])) { echo $_POST['the_input'] ; } ?>">
and for getting form button pressed value you need to append it value manually to serialize.
$form.serialize() + "&submit="+ $('button').attr("value")
Example
<script type="text/javascript">
$(function()
{
$('button[type="submit"]').on('click',function(e)
{
e.preventDefault();
var submit_value = $(this).val();
jQuery.post
(
$(this).attr('action'),
$(this).serialize()+ "&submit="+ submit_value,
function(data)
{
$('#result').empty().append(data).slideDown();
}
);
});
});
</script>
Complete Tested Code
<?php
if(isset($_POST['the_input']))
{
$input = $_POST['the_input'];
$eating = $_POST['eat_something'];
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title>StackOverFlow</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function()
{
$('button[type="submit"]').on('click',function(e)
{
e.preventDefault();
var submit_value = $(this).val();
jQuery.post
(
$('#the-form').attr('action'),
$('#the-form').serialize()+ "&eat_something="+ submit_value,
function(data)
{
$('#result').empty().append(data).slideDown();
}
);
});
});
</script>
</head>
<body>
<form method="post" action="random.php" id="the-form">
<input type="text" name="the_input" value="<?php if (isset($_POST['the_input'])) { echo $_POST['the_input'] ; } ?>">
<button type="submit" name="eat_something" value="TRUE">Eating</button>
<button type="submit" name="eat_something" value="FALSE">Don't Eat</button>
</form>
<textarea id="result"></textarea>
</body>
</html>
Simplest answer would be:
<form method="post" action="the_file.php" id="the-form">
<input type="text" name="the_input" value="<?php if ( isset( $_POST['the_input'] ) echo $_POST['the_input']; ?>">
<input type="submit" name="eat_something" value="Eating" />
<input type="submit" name="eat_something" value="Don't Eat" />
</form>
Of course, this won't give exactly what you're looking for.
You can also do something like this:
<form method="post" action="the_file.php" id="the-form">
<input id="theInput" type="text" name="the_input" value="<?php if ( isset( $_POST['the_input'] ) echo $_POST['the_input']; ?>">
<button type="button" name="eat_something" data-value="TRUE">Eating</button>
<button type="button" name="eat_something" data-value="FALSE">Don't Eat</button>
</form>
$('#the-form button').bind('click', function(){
jQuery.post($('#the-form').attr('action'),
{
the_input: $('#theInput').val(),
eat_something: $(this).attr('data-value')
},
function(data) { $('#result').empty().append(data).slideDown() },
'json'
});
Change the buttons to this (change w/your form names)..
<input type="hidden" name="eat_something" value="" />
<input type="button" onclick="$('input[name=eat_something]').val('TRUE')" />
<input type="button" onclick="$('input[name=eat_something]').val('FALSE')" />
The Javascript function and the PHP are fine.
Thanks!
#leo
I wanted to show textbox content without refreshing,so I used Jquery
I have problem with this part: name:form.name.value what does this exactly do?And why I have problem?when entering it will show nothing
<html>
<head>
<script type="text/javascript" src="./jquery.js"></script>
<script type="text/javascript">
function get(){
$.post('msql.php',{name:form.name.value},
function(output){
$('#mydiv').html(output).show();
}
);
}
</script>
</head>
<body>
<form name="name">
<input type="text" name="name">
<input type="button" name="but" value="Check" onclick="get();">
<div name="mydiv"></div>
</form>
</body>
</html>
msql.php:
<?php
echo $_POST['name'];
?>
try this:
$(document).ready(function() {
$('input[name="but"]').click(function() {
alert("start");
$name = $('input[name="name"]').val();
$.post('msql.php', {
name: $name
}, function(output) {
alert(output);
$('#mydiv').html(output).show();
});
return false;
});
})
html:
<form id="form_name">
<input type="text" name="name">
<input type="button" name="but" value="Check">
</form>
<div id="mydiv"></div>
I think your problem lies in the period (.) just after html.
it should be $('#mydiv').html(output);
Also, you'll be better off using mgraph's solution but remove the period I just told you about.
I don't think jquery understand what form.name.value is unless you provide it with a proper selector like mgraph suggested.