For some reason, my form won't post, any ideas as to why(I already know that everything else on my server is operational)? Code below:
PHP
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "<br>";
$ret = file_put_contents('user.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
}
?>
https://pastebin.com/hHeMD4Mq
HTML/AJAX JS
<form id ="form">
<p>Name:</p>
<input name="field1" type="text" id ="name" />
<h3> </h3>
<p>Message:</p>
<textarea name="field2" type="text" id ="message"></textarea><br/>
<button onclick="pos();">reply</button>
</form>
</td>
</table>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function pos(){
var values=$("form").serialize();
$.post('form.php', values, function(response) {
console.log("Response: "+response);
});}
</script>
https://pastebin.com/eAVE8EGS
demo on my site:
jakesandbox.com/dnd/
(any info not provided above will be provided upon request in the comments)
The problem is your button is actually submitting the form (Which is essentially reloading the page, as it's submitting to itself). You need to do one of 2 things:
Change your button to a type="button" to prevent it from submitting (A button inside of a form element automatically becomes a submit button):
<button type="button" onclick="pos();">reply</button>
Prevent the click action from taking place (Thus preventing the submit):
<button type="button" onclick="pos(event);">reply</button>
<script type="text/javascript">
function pos(e){
e.preventDefault();
var values=$("form").serialize();
$.post('form.php', values, function(response) {
console.log("Response: "+response);
});}
</script>
-OR-
<button type="button" onclick="pos(); return false;">reply</button>
It turns out your form is actually sent normally with GET request (you can probably see the page reload). It occurs when a button inside a form has no specified type (default being submit).
A button of type "submit" inside a form submits the form while a button of type "button" doesn't.
Just add the attribute type="button" to your button and your problem should be solved.
<button type="button" onclick="pos();">reply</button>
On your php end to debug if the data actually came
<?php
header('Content-Type: application/json');
echo json_encode($_POST);
Then on your js
$.post('form.php', values, function(response) {
console.log(response); // return json
});}
Related
My code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form>
<button id="test" value="123" name="test" >ok</button>
</form>
<script>
$(document).ready(function () {
$("#test").click(function() {
var combinedData = $("#test").serialize();
$.post(
"element_submit.php",
combinedData
).done(function(data) {
//alert("Successfully submitted!");
$("#result").html(data);
}).fail(function () {
//alert("Error submitting forms!");
})
});
});
</script>
<div id="result" ></div>
The element_submit.php file
<?php
//just to test it should output in the #result div
echo $_POST['test'];
?>
What I am trying to do is submit the with the value="attribute" so the data is serialized and send the post request, it's not like a submit when user insert a value and submit,What I need is to get the value attribute and submit to the php, this code is only for To simplify and illustrate what I am trying to do, because in this page I have the following buttons with ids #follow #unfollow so I need a way to get the button value to make the user follow and unfollow.
you need to serialize the form - not the elements within it .You can also have the triggering button outside the form which will prevent hte form from submitting on the button click.
<form id="testForm">
<input type="hidden" name="testInput" value="123"/>
</form>
<button name="test" id="testButton">submit</button>
...
<script>
$(document).ready(function () {
$("#testButton").click(function() {
var combinedData = $("#testForm").serialize();...
$(document).ready(function () {
$("#testButton").click(function() {
var combinedData = $("#testForm").serialize();
console.log(combinedData);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="testForm">
<input type="hidden" value="123" name="testinput"/>
</form>
<button id="testButton">Click</button>
Straight JS might help you out. Include a function that sends the id and get the value of that id. Then just send a regular post of the value without serialize... easier.
<script>
function fetchButtonValue(theId){
var p = document.getElementById(theId).value;
alert (p);
}
</script>
<button id="myFormBtn" value ="woo"
onclick="fetchButtonValue(this.id)">My Button</button>
this works...
You could also put a class on the button let's say class="followBTN" then on a click you could just snag the value by $(this).val() I'd use this method if I had more than one button per page.
Form :
<form method="post" id="loginForm">
<div class="form-group">
<label for="email-signin">Email address:</label>
<input type="email" class="form-control" id="email-signin" name="email-signin">
</div>
<div class="form-group">
<label for="pwd-signin">Password:</label>
<input type="password" class="form-control" id="pwd-signin" name="pwd-signin">
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Remember me</label>
</div>
<button type="submit" class="btn btn-default" id="signIn" name="signIn">Sign In</button>
<div id="error">
<!-- error will be shown here ! -->
</div>
</form>
jquery :
$("#signIn").on("click", function(e) {
e.preventDefault();
var values = $("#loginForm").serialize();
console.log( values );
$.ajax({
type: "POST",
url: "../php/BusinessLayer/User.php",
data: values,
beforeSend: function() { $("#error").fadeOut() },
success : function(response)
{
console.log("Success");
if(response=="ok"){
}
else{
$("#error").fadeIn(1000, function(){
$("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> '+response+' !</div>');
});
}
}
});
php:
<?php
session_start();
include ("../DataLayer/VO/UserVO.php");
include ("../DataLayer/DAO/UserDAO.php");
// Database Execution for User Related Request
$userDAO = new UserDAO();
print_r($_POST);
if(isset($_POST['signIn']))
{
echo 'test2';
$user = new UserVO();
$user->setEmail(trim($_POST['email-signin']));
$user->setPassword(trim($_POST['pwd-signin']));
// Request signin
$userDAO->signIn($user);
}
Using this code, my if(isset($_REQUEST['signIn'])) in my php file never returns true. I have tried multiple things, and nothing seems to work.
PS : I am using Jquery 1.12.4
Also, my print_r($_POST); returns an empty Array.
jQuery's serialize function does not encode the values of buttons. Taken from here
NOTE: This answer was originally posted by slashingweapon
jQuery's serialize() is pretty explicit about NOT encoding buttons or submit inputs, because they aren't considered to be "successful controls". This is because the serialize() method has no way of knowing what button (if any!) was clicked.
I managed to get around the problem by catching the button click, serializing the form, and then tacking on the encoded name and value of the clicked button to the result.
$("button.positive").click(function (evt) {
evt.preventDefault();
var button = $(evt.target);
var result = button.parents('form').serialize()
+ '&'
+ encodeURIComponent(button.attr('name'))
+ '='
+ encodeURIComponent(button.attr('value'))
;
console.log(result);
});
As far as the var dump being empty on the PHP side, try using jQuery's .click instead of the .on event.
$('#signIn').click(function(){});
Also, remove the method from your form. It looks like the form may be submitting as soon as you click the button. Also, remove
e.preventDefault();
and place
return false;
at the VERY END of the on click function. return false does 3 things
e.preventDefault()
e.stopPropigation();
return immdediatly
This question already has answers here:
JavaScript: Inline Script with SRC Attribute?
(3 answers)
Closed 6 years ago.
I tested my update.php file and it works perfect and there is not any error when i checked my script via console . Only problem in here . Ajax can't send values "id" "comment_area" to update.php file . What is the mistake in here ?
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.6.2.min.js">
$(document).ready(function() {
$("#b_news").submit(function(evt) {
evt.preventDefault();
var text = $('#breaking_news_text').val();
var id = 21;
$.ajax({
type: "POST",
url: "update.php",
data: {
comment_area: text,
id: id
},
success: function() {
alert("sucess");
}
});
});
});
</script>
<form id="b_news" method="post" action="">
<div>
<div>
<textarea id="breaking_news_text" class="breaking_news_text" rows="6" cols="50" placeholder="Add text here..." required></textarea>
</div>
</div>
<div>
<input type="button" id="save" value="Save Changes" />
</div>
</form>
<?php
include("./inc/connect.inc.php");
$id=$_POST['id'];
$update = $_POST['comment_area'];
$sql = "update comments set comment_area='$update' Where id='$id'";
$result = mysqli_query($mysqli, $sql)or die("error");
?>
Seems to me that your button simply can't submit the form because of its type.
Try to change the type attribute of the button to submit this way :
<input type="submit" id="save" value="Save Changes"/>
You have two problems.
First you can only have one script per script element. The script can either be referenced by the src attribute or it can be between the start and end tags.
If you try to do both, as you are here, then only the src will be respected.
Use separate <script> elements for your two scripts.
Second, you have no way to trigger the submit event. The submit event will trigger when the form is submitted, but you can't do that from a textarea or a button. Replace the button with a submit button.
first post. PHP noob. I'm surprised at how difficult this has been...
I have an html form (index.html) with a submit button that posts to a php file (sendemail.php).
The php file is set to collect form data and send it via email to an address I specify.
I would like to display a success icon next to the submit button when this email is sent. (Honestly, there is no fail condition, so I would be happy with just displaying the success icon when the user clicks Submit, so they know not to keep clicking Submit).
I have tried a number of approaches after reading this and many other forums. I've been at this for two days and could use some help.
Here's some snippets below. I'm basically just trying to detect the email being sent in the php file, then sending a flag ($val) using echo json_encode back to the HTML page. I'm trying to capture it using the javascript with an onload trigger, and then trying to use the javascript to manipulate the DIV visbility when the page is refreshed after the submit action is completed.
It processes the php but it doesn't seem to reach the Header line to reload the html page. It just refreshed the screen and shows the word "inline" and nothing else.
I'm stumped. Please help! Thanks
sendmail.php
// Check, if message sent to your email
// mark success or fail then refresh page
if($send_contact){
$val="inline";
echo json_encode($val);
}
else {
echo "Error";
}
if($send_contact){
header('location:index.html');
}
else {
echo "Error";
}
?>
javascript in html
<script type="text/javascript">
function success(){
var val = <?php echo json_encode($val); ?>;
document.getElementById('success').setAttribute('display', val);
}
window.onload = success;
</script>
HTML DIV I'm trying to control
<div style="text-align: left; font-weight: bold; color:#000000; display:val;"
class="success" id="success" name="success"><img src="success.png"
height="25px">Event added! It may take 20 minutes to appear on
the calendar. </div>
UPDATE:
Ok I tried manRo's suggestion and was able to get the behavior I wanted out of the green checkmark...it would be hidden on page load and then appear when it received the 200 status message from the PHP file.
However when I try to build this logic into my ajax something is breaking and the form data is no longer submitting, and the green checkmark logic stops working.
Allow me to run through my updates:
Currently my script header looks like this:
<script type="text/javascript" src="util-functions.js"></script>
<script type="text/javascript" src="clear-default-text.js"></script>
<script src="https://code.jquery.com/jquery-2.2.2.min.js"></script>
I've got an onload in the body to call a function to set the green checkmark to "hidden", just to keep things tidy:
<body onload="setdisplay()">
Calling this function:
<script>
function setdisplay();
document.getElementById("success").style.display = "none";
</script>
I get my form started like this now:
<form id="main" name="main" action="">
Here's an example input:
<td style="text-align: right; "> <br>
</td>
<td><input id="title" name="title" value="Event title" class="cleardefault rounded"
required="true" type="text"> </td>
The form submit button, which currently is type=button
<input style="background-color: #99d6ff; text-align:center;
font-weight: bold;" value="Add event" id="addevent" name="addevent" onclick="processmain();"
class="button" type="button">
This is the DIV I need to make visible or hidden depending on success:
<div style="text-align: left; font-weight: bold; color:#000000; display:none;"
class="success" id="success" name="success"><img src="success.png"
height="25px"></div>
Now the beefy part....I've tried integrating your manRo's suggestions into my main form processing script, as part of the ajax "success" state:
<script>
}
function processmain()
{
// event.preventDefault();
var title = $("input#title").val();
var location = $("input#location").val();
var startdate = $("input#startdate").val();
var starttime = $("input#starttime").val();
var enddate = $("input#enddate").val();
var endtime = $("input#endtime").val();
var other = $("input#other").val();
$.ajax({
url: "sendemail.php",
type:'POST',
data:
{
title: "title",
location: "location",
startdate: "startdate",
starttime: "starttime",
enddate: "enddate",
endtime: "endtime",
other: "other"
},
success: function(event)
{
$.get('sendmail.php', function(data) {
document.getElementById("success").style.display = "inline";
})
}
});}
</script>
At the moment:
The form data is not passed to the php
The green checkmark does not show
The screen is no longer refreshing (because button type=button now, instead of submit).
I feel like I am close. I need to get the form data sent to the php so the email is sent. I need the page to not refresh so I can properly introduce the green checkmark.
Please take a look at how I'm implementing your solution in my code and let me know what I'm doing wrong. Thank you!!
What you want is HTML form with ajax call to php script that will return 200 http status code on success.
I will try to explain you that on very simple example.
Please take a look at below html file:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.2.min.js"></script>
</head>
<body>
<form action="sendmail.php">
<input type="email" name="email"/>
<input type="submit"/>
</form>
<script>
$(document.forms[0]).submit(function(event) {
event.preventDefault();
$.get('sendmail.php', function(data) {
alert('all good');
});
});
</script>
</body>
</html>
sendmail.php in that case should contain code responsible for sending email eg:
<?php
//code here...
if ($email_sent) {
http_response_code(200);
} else {
http_response_code(400);
}
Using the below form 1, i'm generating a goo.gl short url inline in #shortUrlInfo area. I want to use the generated short url in 2nd form to save it in wordpress custom field.
Form 1:
<form method="post" action="">
<input style="display:none;" type='text' id='longUrl' value='<?php echo get_post_meta( get_the_ID(), 'longurl', true ); ?>' />
<input name="shorturlinput" type="button" id="shortIt" value="Short It" /></form>
<div class="info" id="shortUrlInfo"></div>
Form 2:
<?php
global $post;
if( isset($_POST['submit_meta']) ) {
if( ! empty($_POST['change_meta']) ) {
update_post_meta($post->ID, 'shorturl', $_POST['change_meta']);
}}
?>
<form method="post" action="">
<input type="text" name="change_meta" value="" />
<input type="submit" name="submit_meta" value="Submit" />
</form>
How can i submit the first form and pass the generated short url to 2nd form and submit that short url value in custom field with one click?
Or atleast, how can we display the generated short url in 2nd form input, which if we click on submit button, it should save in database.
It's my first question here & I've tried my best to find answer before posting here with no luck.
Well its all ajax . you need to post your data with ajax function to the controller which save the shortened url in data base , how ? like this :
give your second form + the first input of your second form 2 ids
$("#shortIt").click(function(){
var longUrl = $('#longUrl').val()
$.post("ur_url.php",
{
"longUrl": longUrl // here the url will be sent to your server and server communicates
// with goo.gl url shorter by its api and respond you with a variable called data
},
function(data, status){ // your server send here the shorturl and this function calls it
//also this function will be run after the server respond is completed
$('#inputID').val(data) // data will be set inside the input value
document.getElementById("#SecondForm").submit(); // your second form submits and your
// server needs to get the data and save it in your data base
});
});
all will be done with a single click .
also you can do many things when the process is going on . but i hope i gave you some clue :P
Try this in HTML:
<form (return to script)>
<input 1>
</form>
<input 2>
Then in script:
get input 1 and input 2
Next example code shows how to achieve what I believe you want (with one click!). Explanation first: one form (file #1) sends a text to a script (file #2), this script redirects to another form (file #3), this form gets the original text and automatically resend it to another script (file #4) that inserts it in database, next image explains it better:
As you can see, the text in the first form becomes a value for the second form.
Now the code. In order to test next code, you will have to create four text files and give them the given names (if you change the filenames, you will have to change the "action" property in the forms), copy-paste my code in your files, then, open you browser and run only the first file like this) :
http://localhost/form_sequence_1.php
These are the files:
form_sequence_1.php
<html>
<body>
FORM 1
<br/>
<form method="post" action="form_sequence_2.php">
Enter a text
<input type="text" name="my_text" />
<br/>
<input type="submit" value="Send text" />
</form>
</body>
</html>
form_sequence_2.php
<?php
session_start();
$_SESSION[ "my_text" ] = $_POST[ "my_text" ];
header( "Location: form_sequence_3.php" );
?>
form_sequence_3.php
<?php
session_start();
?>
<html>
<head>
<script type="text/javascript">
function autosendform () {
setTimeout( "sendform()","3000" );
}
function sendform () {
document.getElementById( "my_form" ).submit();
}
</script>
</head>
<body onload="autosendform();">
FORM 2
<br/>
<form method="post" action="form_sequence_4.php" id="my_form">
Text entered in previous form
<input type="text" name="my_text" value="<?php echo $_SESSION[ "my_text" ]; ?>"/>
<br/>
<input type="submit" value="AUTOSENDING FORM IN 3 SECONDS" />
</form>
</body>
</html>
form_sequence_4.php
<?php
session_start();
echo $_SESSION[ "my_text" ] . " succesfully inserted into database.";
?>
More explanations:
Value in form 1 sends the text to form 2.
In the middle of form 1 and form 2 we need a script to capture the value.
Form 2 automatically resends the value thanks to a timer in JavaScript.
The last script gets the value and insert it in database (not for real).
The advantage of this approach is that the scripts allow you to do many things with the value or values, like validating or conversion.
Next is your code with my JavaScript timer code adapted :
<?php
global $post;
if ( isset($_POST['submit_meta']) )
if ( ! empty($_POST['change_meta']) )
update_post_meta( $post->ID, 'shorturl',$_POST['change_meta'] );
?>
<html>
<head>
<script type="text/javascript">
function autosendform () {
setTimeout( "sendform()","3000" );
}
function sendform () {
document.getElementById( "my_form" ).submit();
}
</script>
</head>
<body onload="autosendform();">
<form method="post" action="" id="my_form">
<input type="text" name="change_meta" value="" />
<input type="submit" name="submit_meta" value="Submit" />
</form>
</body>
</html>