Input button and ajax not submitting POST - php

I have a pretty simple form. I am submitting with Ajax. The form works fine. However when I try to use php to check if an input button was pressed before I execute the code, It does not seem to pick up the button.
Any advice on what to do would be great. I have added a sam[le of the code below
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="Email-student" method= "post">
<input class="form-control" type="text" name="Email-subject" placeholder="Email Subject">
<textarea class="form-control" id="message" name="Email-message" placeholder="Enter messages"></textarea>
<input type="submit" id="btnSubmit" name="btnSubmit" value="Save Changes" />
</form>
<script>
$(document).ready(function(){
$('.Email-student').submit(function(e){
e.preventDefault();
var url = "mysql.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(), // serializes the form's elements.
success: function(data) {
//$('.Email-student').html(data);
alert(data);
}
});
})
})
</script>
This is a simplified version of my Php file
if (isset($_POST['btnSubmit'])) {
echo 'btnSubmit';
}

serialize() will not include any submit buttons in the form. They are only successful controls if used to submit the form, and serialize():
isn't really part of the form submission process
can't know which, if any, submit button was used to submit the form
Consequently, isset($_POST['btnSubmit']) will not be true.
Use some other mechanism to determine if there is form data that you are interested in (such as the existence of the Email-subject field).

Related

Sending Input from a Form via Ajax Request

After following the example and answers by the following threads
jQuery AJAX submit form
submitting a form via AJAX
I have built a similar test form to get to learn the ajax request on submit. Your guess was right, it doesn't work for me (no alert popping up).
My testajax.php with the form:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="../test.js"></script>
<form name="feedback" id="idForm" action="(myurl)/testajax.php" method="post">
<input id="name" type="text">
<input type="submit" name="feedbacksent" value="Send" />
</p>
</form>
My test.js:
// this is the id of the form
$("#idForm").submit(function(e) {
var url = "(myurl)/testajaxinput.php"; // the script where you handle the form input.
e.preventDefault(); // avoid to execute the actual submit of the form.
alert("bla"); // does not work either
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
My testajaxinput.php that should handle the input:
if (isset($_POST['feedbacksent'])){
echo "<h1>".WORKS."</h1>";
}
Try this :
if (isset($_POST['feedbacksent'])){
echo "<h1>".WORKS."</h1>";
return true;
}
Then try your alert and also check have you got any error in console.

jQuery submit function doesn't send input submit

I was looking for answer for my question but I didn't found solution. Here is similar topic link but I have different code and I don't know how to fit answer from this topic to my code.
Here is my problem. I'm sending my form with id order_form to test.php.
Every form value is sending proper except input submit. My script is based on checking that <input id="sendform" type="submit" value="ORDER PRODUCT" name="sendform"/> is send.
Below is code that I use to send form.
$("#order_form").submit(function() {
$.ajax({
type: "POST",
url: "includes/test.php",
data: $("#order_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});
return false; // avoid to execute the actual submit of the form.
});
And here is content of test.php
echo '<pre>';
print_r($_POST);
echo '</pre>';
Here is examle form because my form is extremaly big.
<form id="order_form">
<input type="text" name="w2b" value="abc"/>
<input id="sendform" type="submit" value="ZAMAWIAM" name="sendform"/>
</form>
In HTML5 forms when you are passing through parameters and variables to the ajax functions the value data from "Submit Inputs" isn't passed through. So if you have a form set up as :
<form>
<input type="text" name="foo" value="bar">
<input type="submit" name="submitTest" value="Hello World!">
</form>
The value of "submitTest" isn't being sent through. The only thing that gets sent through is the parameter "foo" with the value of "bar". "submitTest" only submits the form and executes your ajax call in this case.
To fix this just add a hidden element in the form.
Now it would look this
<form>
<input type="text" name="foo" value="bar">
<input type="hidden" name="sendform" value="ZAMAWIAM">
<input type="submit" name="submitTest" value="Hello World!">
</form>
This will send through the value to your ajax call and you can use it for whatever you might need it for.
Make sure you wrap your jquery code in
$(function(){
//code here
});
Again Dont forget to prevent Default Event , Below is a rewrite of your jquery code
$(function(){
$("#order_form").submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "includes/test.php",
data: $("#order_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});//end ajax
});//end on submit
});//end jquery

To make html form run two actions

Is it possible to submit two forms using a single submit button?
like if a user clicks submit on a form, that form runs test.php and form.php with the variables still intact?
If not then is it possible when the user clicks submit on a form it runs only test.php then test.php runs form.php with the variables still intact.
I don't think this is possible on a normal form submission, but you can try to utilize an AJAX request on both forms on demand. (This is just an example, not tested, just a guide or an idea.).
<!-- forms -->
<fieldset><legend>Form #1</legend>
<form id="form_1" action="test.php">
<label>Username: <input type="text" name="username" /></label>
<label>Password: <input type="text" name="password" /></label>
</form>
</fieldset>
<br/>
<fieldset><legend>Form #2</legend>
<form id="form_2" action="form.php">
<label>Firstname: <input type="text" name="fname" /></label>
<label>Lastname: <input type="text" name="lname" /></label>
</form>
</fieldset>
<button id="submit" type="button">Submit</button>
<!-- the forms is just an example -->
<!-- it would be weird to separate such fields in to different forms -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#submit').on('click', function(){
$.ajax({
url: $('#form_1').attr('action'),
data: $('#form_1').serialize(),
type: 'POST', // or whatever get
dataType: 'JSON', // or whatever xml script html
success: function(response) {
}
});
$.ajax({
url: $('#form_2').attr('action'),
data: $('#form_2').serialize(),
type: 'POST', // or whatever get
dataType: 'JSON', // or whatever xml script html
success: function(response) {
}
});
});
});
</script>
The form can have only one action, if you want to pass data to a different page then you can do that by calling an ajax function..

How to have two buttons in a same form to do different actions in ajax?

I have a form, which take name from form and it sends to javascript codes and show in php by Ajax. these actions are done with clicking by submit button, I need to have another button, as review in my main page. how can I address to ajax that in process.php page have "if isset(submit)" or "if isset(review)"?
I need to do different sql action when each of buttons are clicked.
how can I add another button and be able to do different action on php part in process.php page?
<script type="text/javascript">
$(document).ready(function(){
$("#myform").validate({
debug: false,
submitHandler: function(form) {
$.post('process.php', $("#myform").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
</script>
<body>
<form name="myform" id="myform" action="" method="POST">
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value=""/>
<br>
<input type="submit" name="submit" value="Submit">
</form>
<div id="results"><div>
</body>
process.php:
<?php
print "<br>Your name is <b>".$_POST['name']."</b> ";
?>
You just need to add a button and an onclick handler for it.
Html:
<input type="button" id="review" value="Review"/>
Js:
$("#review").click(function(){
var myData = $("#myform").serialize() + "&review=review";
$.post('process.php', myData , function(data) {
$('#results').html(data);
});
}
);
Since you have set a variable review here, you can use it to know that is call has come by clicking the review button.
Bind the event handlers to the buttons' click events instead of the form's submit event.
Use the different event handler functions to add different pieces of extra data to the data object you pass to the ajax method.

Problem using jQuery-AJAX to submit form to PHP and display new content in div without refreshing

I am trying to use jQuery-AJAX to submit the data in my form to my controller (index.php) where it is processed by PHP and inserted via PDO into the database if valid. Once the code is inserted into the database, the div where the form previously existed should be replaced by the contents of another page (newpage.php). The original page should not be refreshed upon submitting of the form, only the div where the form previously existed should be refreshed. There is a particular problem with my code, although I can't seem to find where the issue is at:
Here is my jQuery:
<script type="text/javascript">
function processForm() {
var action= $('#action').val();
var data = $('#data').val();
var dataString = 'action=' + action + '&data=' + data;
$.ajax ({
type: "POST",
url: ".",
data: dataString,
success: function(){
$('#content_main').load('newpage.php');
}
});
}
</script>
Here is my HTML: (As a side note, I noticed that when I take the "return false;" out of the HTML, that the form will submit to my database, but the whole page also reloads - and is blank. When I leave the "return false;" in the HTML, the newpage.php loads correctly into the div, but the data does not make it into the database)
<form action="" method="post" onsubmit="processForm();return false;">
<input type="hidden" name="action" value="action1" />
<input type="text" name="data" id="data" />
<input type="submit" value="CONTINUE TO STEP 2" name="submit" />
</form>
Here is my PHP:
<?php
$action = $_POST['action'];
switch ($action) {
case 'action1':
$data = $_POST['data'];
pdo ($data);
exit;
}
?>
I feel like I am making a silly mistake somewhere, but I just can't put my finger on it. Thanks for any assistance you can provide!
SOLUTION (via Jen):
jQuery:
<script type="text/javascript">
function processForm() {
var dataString = $("#yourForm").serialize();
$.ajax ({
type: 'POST',
url: ".",
data: dataString,
success: function(){
$('#content_main').load('newpage.php');
}
});
return false;
});
</script>
HTML:
<form id="yourForm">
<input type="hidden" name="action" value="action1" />
<input type="text" id="data" name="data" />
<input type="submit" value="CONTINUE TO STEP 2" name="submit" />
</form>
PHP:
<?php
$action = $_POST['action'];
switch ($action) {
case 'action1':
$data = $_POST['data'];
pdo ($data);
exit;
}
?>
What I learned: Use the .serialize() jQuery method if it is an option, as it will save a bunch of time writing out the var for each form value and .serialize() does not typically make mistakes sending the info to php.
Give this a try:
$("#yourForm").submit(function(){
// Could use just this line and not vars below
//dataString = $("#yourForm").serialize();
// vars are being set by selecting inputs by id but id not set in form fields
var action= $('#action').val(); // value of id='action'
var data = $('#data').val(); // value of id='data'
var dataString = 'action=' + action + '&data=' + data;
// dataString = 'action=&data=' so nothing is posted to db
// because input fields cannot be found by id
// fix by adding id fields to form fields
$.ajax ({
type: "POST",
url: ".",
data: dataString,
success: function(){
$('#content_main').load('newpage.php');
}
});
return false;
});
And change the form to (I added the id attributes):
<form id="yourForm">
<input type="hidden" id="action" name="action" value="action1" />
<input type="text" id="data" name="data" id="data" />
<input type="submit" value="CONTINUE TO STEP 2" name="submit" />
</form>
Seems like you need an explanation rather than a fix of code. Here is a brief explanation for the 2 cases:
When you take out return false; the code will treat your form as a normal HTML form that will be submitted to the server via action="", which leads to nowhere. The Javascript, however, also does its job in this case but because the page is redirected to nowhere, then it turns blank at the end.
When you put return false; back to the form, the form will catch the event handler and know that this form will be returned FALSE to submit. That's why you can see how your Javascript code does the job. However, one thing you should notice is that your jQuery AJAX function needs to POST (or GET) to a processing file, not '.'
Considering this reply based on no knowledge of your real situation. You need to look back over your code and see how you can edit it. Would be happy to reply if you have any questions.
Hope this small hint helps (:

Categories