isset validation in PHP failing when form submitted through jquery - php

My if(isset) validation is returning false after I have submitted the form through jQuery ,however works fine when done without jquery. Reason I am using jQuery is because I need to submit multiple forms:
Button
<input class="btn btn-primary" type ="submit" id="myButton"
name="create_record" value="Submit 1">
jQuery:
<script>
$(document).ready(function () {
$("#myButton").click(function (event) {
event.preventDefault();
$("#form1").submit();
// $("#form2").submit();
});
});
</script>
PHP
<?php
if(isset($_POST['create_record'])){
$ecode = $_POST['ecode'];
$ename = $_POST['ename'];
$date = $_POST['date'];
$jobRole = $_POST['jobRole'];
}else{
echo "did not receive anything";
}
?>
Always getting "did not receive anything" . Can someone please help.

The submit button value only gets sent if the form is submitted in the traditional way by a button click. Since you are submitting the form via javascript, you'll need to explicitly include the submit button's value or validate your post data in some other way. If you need the value of the specific button that was clicked, something like this should work:
$("#myButton").click(function (event) {
event.preventDefault();
var el = '<input type="hidden" name="' + $(this).prop('name') + '" value="' + $(this).val() + '">';
$("#form1").append(el).submit();
});
As for your objective of submitting multiple forms at once, I believe it's impossible without using ajax as discussed here. If you need guidance on how to do that, better to open a new question.

Your code, isset($_POST['create_record']) maybe false or it didn't receive any values. If your query is only in one PHP file together with your jQuery, you need to check first your algorithm or use var_dump() for testing. Second, If it didn't work, make an alternative solution for it. Do the proper HTML code when using form or make another PHP file for receiving post purpose only.
<form action="directory_to_another_file" method="POST">
<!-- SOME INPUTS HERE -->
<input type="submit" value="Submit 1" name="create_record">
</form>
Try to test all of your codes.

You have to set form method as "POST" type and if you want to receive the form data in same page then empty the "action" key otherwise give the target link.
<?php
if(isset($_POST['create_record'])){
print_r($_POST);
}
?>
<form action="" method="POST" id="form1">
<input type="text" name="create_record" value="Submit 1"/>
</form>
Submit
<script>
$(function(){
$("#myButton").click(function (event) {
event.preventDefault();
$("#form1").submit();
});
})
</script>
Let me know if it's work for you.

Related

Ajax.serialize() request NOT WORKING

I am trying to send my form values to php page in order to perform SQL requests to my server according to my form values. This is original php with form and ajax script:
<script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<form enctype="multipart/form-data" method="post">
<input type="datetime-local" name="start" id="start">
<input type="datetime-local" name="finish" id="finish">
<input type="checkbox" name="consta" id="consta" value="tru"> Remove const
<input type="submit" name="apply" id="apply">
</form>
<script>
$('#apply').click(function(){
var data= $('form').serialize();
$.post('gensetapply.php', data);
});
</script>
And in gensetapply.php I am trying to get variables through $_POST:
<?php
$con=$_POST['consta'];
$str=$_POST['start'];
$fin=$_POST['finish'];
echo $con.", ".$str.", ".$fin;
?>
So, I am sure my ajax request is not working.
I am new to this things and have wrote code above looking to similar examples, so please feel welcome to point out my mistakes. There might be a typo cause I am handtyping it again here, not copy-paste from source.
EDIT:
It was working, I just couldn't see it when i refresh the page, but through devtools in Chrome (Network>Response) I. Hope it'd help some other fools like me ;)
1st : Your using post method to post the data to server so you need to prevent the default submit
<script>
$('#apply').submit(function(e){
e.preventDefault();
var data= $('form').serialize();
$.post('gensetapply.php', data);
});
</script>
2nd : or Simple change the type="submit" to type="button".
Here 'Apply 'button type is submit. Therefore your form submits immediately. As you are handling form submission through ajax so the solution is you need to stop submitting form. You can fix it returning false in click event like following
<script>
$('#apply').click(function(){
var data= $('form').serialize();
$.post('gensetapply.php', data);
return false;
});
</script>

Force data to a form using post

I know that there is no way to use a query string to pass information into a form that uses the post method, but are there any other options? I am trying to use a link (or button) on one website to link to a page on another. In the process, the URL/button needs to send information to the target. The target website uses post, so I can't just use a query string to input my data. Is there some sort of button attribute that will let me send data to the fields in the target website? Thank you in advance.
EDIT: I should have also mentioned that I cannot use the form tag. For some reason, the environment I am using does not allow for some tags to be used.
This should solve your problem (tested it locally and confirmed form data was present) ... got starting point here https://stackoverflow.com/a/13678453/1946558
<button class="btn" id="go">Go </button>
<script type="text/javascript">
$(document).ready(function () {
$('#go').click(function () {
var form = document.createElement("form");
var input = document.createElement("input");
// where you want to post the data
form.action = "test";
form.method = "post";
// add your fields here
input.name = "id";
input.value = 'some data';
// then append
form.appendChild(input);
document.body.appendChild(form);
form.submit();
});
});
</script>
With a button:
<form action="http://example.com/target.php" method="post">
<input type="hidden" name="foo" value="bar" />
<input type="submit" />
</form>
With a link:
<form id="my_form" action="http://example.com/target.php" method="post">
<input type="hidden" name="foo" value="bar" />
</form>
Submit

Doesn't get value with jQuery

<form method="POST">
<div id="showme">Show me <?php echo $_POST['name']?></div>
Send the value<input type="radio" name="name" value="ja"/>
<input type="submit" id="submit" name="submit" value="BEREKENEN! ">
</form>
<script>
$(document).ready(function () {
$('#showme').hide();
$('#submit').click(function(e) {
e.preventDefault();
$('#showme').fadeIn(5000);
});
});
</script>
This code won't send the value of the radiobutton to the showme div.
I can't receive the $_POST['name'] when I use hide() and fadeIn() between the <script> tags.
Whenever I don't use jQuery it sends the data - when using it , it won't let me send the value.
How do I fix this problem, this is just an example of 1 radio button. I have a list of 6 radiobuttons that need to be sent to PHP section in the same file, I don't want to make another file for this.
This code will FadeIn the requested div, it shows me Show me but it won't show the value where I ask for with the line <?php echo $_POST['name']?>
PHP is parsed on the server. <?php echo $_POST['name']?> has already been evaluated and echod to the page long before any of the submission stuff happens. What you need is to use AJAX.
You can replace the submit button with just a regular button, remove the <form> element entirely even.
jQuery:
$('#submit').on('click', function(evt) {
var e = evt || window.event;
e.preventDefault();
$.post('page.php', { name: $('input[name="name"]').val() }, function ( data ) {
$('#showme').append(data).fadeIn(5000);
});
return false;
});
(if you do what I did below turning submit into button, you dont need the e.preventDefault())
PHP:
if(isset($_POST['name'])) {
echo $_POST['name'];
return;
}
HTML:
<div id="showme">Show me </div>
<label for="name">Send the value</label><input type="radio" name="name" value="ja"/>
<input type="button" id="submit" name="submit" value="BEREKENEN!">
I'm not so sure you can get a non-BOOLEAN value from a radio button with PHP though. You're probably better off using <input type="hidden" value="ja" /> or maybe type="text".

Run PHP code after button click but without refreshing page

I have a form in HTML to apply a Discount Coupon to a current shopping cart.
I would like the user to just click on APPLY (after entering the coupon code) and then without refreshing the page, to have some PHP code run so it computes the corresponding discount.
Here is my form:
<form action="">
<input type="text" name="couponCode">
<input type="submit" value="Apply">
</form>
PHP to be run:
if (isset($_REQUEST['couponCode']) && $_REQUEST['couponCode']!='')
{
$couponCode = $_REQUEST['couponCode'];
if ($couponCode == "TEST1")
{
$discount=0.2;
}
}
How would this be done using javascript?
You need to use either the onsubmit event of the form or the onclick event of the button.
In the event handler, you assemble a URL and "get" it. For example:
<script type="text/JavaScript">
function submitCouponCode()
{
var textbox = document.getElementById("couponCode");
var url =
"https://www.example.com/script.php?couponCode=" + encodeURIComponent(textbox.value);
// get the URL
http = new XMLHttpRequest();
http.open("GET", url, true);
http.send(null);
// prevent form from submitting
return false;
}
</script>
<form action="" onsubmit="return submitCouponCode();">
<input type="text" id="couponCode">
<input type="submit" value="Apply">
</form>
Use jQuery AJAX. When it's complete, refresh your page as needed.
You can use Jquery to do an AJAX post you your PHP script, and then use JS to change the contents of the calling page.
http://api.jquery.com/jQuery.post/
It's simple with jQuery. You just have to use the right tag. If you use an "a" tag the page will refresh.
<button id="MyButton">Click Me!</button>
<script>
$("#MyButton").click( function(){
$.post("somefile.php");
});
</script>

submitting form with two buttons

I have 2 buttons in HTML form. And both of them should submit the form. I would need to capture which button has been clicked so i can use it to perform different actions based on which button was clicked.
I am able to submit the form with both the buttons but how would i capture which button was clicked in the php file .
<INPUT type="button" name="submit" class="button" class="element_2" value="firstbutton">
<INPUT type="button" name="submit1" class="button" class="element_2" value="second button.. ">
i am using post method in Jquery to submit the form. How can i check which HTML button was clicked in server side php script
You could use a hidden element here, something like this:
<input type="hidden" id="submittedBy" name="submittedBy">
Your current .submit() handler using .serialize() and $.post() should work, just update the hidden field when clicking either button, for example:
$("form :submit").click(function() {
$("#submittedBy").val(this.name);
});
Then in PHP just check that $_POST["submittedBy"] == "submit" or "submit1" to see which caused it.
The alternative is to have the click handler POST and add in the value between .serializeArray() and when $.param() is called, like this:
$("form :submit").click(function() {
var data = $(this.form).serializeArray();
data.push({ name: 'submittedBy', value: this.name });
$.post("myPage.php", data, function(result) {
//do something
});
return false; //prevent normal form submission, even with the .submit() handler
});
Just do this,
HTML
<button type="submit" name="action[update]" value="1">Update</button>
<button type="submit" name="action[delete]" value="1">Delete</button>
PHP
$action = isset($_POST['action']['update']) ? 'update' : 'delete';
You CAN'T depend on JavaScript to tell you wich button was clicked, if user has JavaScript disabled, your form is broken.
You could try using the isset function
if(isset($_POST['submit'])){
echo "first button was clicked";
}
Or to detect the second one was clicked:
if(isset($_POST['submit1'])){
echo "second button.. was clicked";
}
I would capture all the events on the page using:
$(document).click(function (obj) {
if ('equipmentSetup' === obj.target.id) {
$('#form').submit();
}
....
Then add an if statement looking for the "id" of the button you want. Don't use the name or id "submit". I forgot why but I remember it caused problem for me.
You could try changing the buttons to type="button" and give them ids. With that, you can use the jquery line (not able to check my syntax below, but think i've got it right)
$('form button').click(function(){
if($(this).attr('id') = "button1"){ ...button 1 clicked}
..process form here..
});
would that do it?

Categories