Submit form if action == something - php

I would like to submit a <form> automatically if:
if(isset($_POST['action']) && ($_POST['action'] =='confirmado')){
submit form.
I donĀ“t know if I should use a javascript script.
I try doing this but it is not working.
<script>
if(isset($_POST['action']) && ($_POST['action'] =='confirmado')){
$("#form").submit(function(){
document.form.submit();
return false;
}
</script>

You are trying to mix up PHP, which is a server-side language, with Javascript, which is a client-side language. So, that won't work.
Moreover, the submission of a <form> is NOT captured in its $_POST array as $POST['action']. The method of submission is POST and the $_POST array contains data submitted via the form's html elements.

Try this:
$( '#form' ).submit(function () {
if ( this.action !== 'confirmado' ) return false;
});

First of all, I agree with coder1984: you are mixing PHP with Javascript, and you are trying to access POST data in the client side, which is not possible. If I can guess what you are trying to do, maybe this code will help you:
<script type="text/javascript">
if (<?php echo (isset($_POST['action']) && ($_POST['action'] =='confirmado')) ? '1' : '0'; ?>) {
document.form.submit();
}
</script>

If i understand your code right, you would like to only submit the form if the field "action" equals "confirmando". Since you are allready using jQuery let's keep at it.
JavaScript:
<script>
$('document').ready(function() {
$('input[name=action]').change(function() {
if($(this).val() == 'confirmando') {
$('form').submit(); // If you would like to do a normal sumbit
$.post('my_php_file.php', $('form').serialize(), function(data)) { // or use AJAX
/* var data now contains the output of the PHP file */
}
}
});
});
</script>
It still makes sense to check the submited form in PHP when you receive the data from the form.

Related

How to POST data from a field with Javascript

Hi I am trying to make a page which will use the $.post method in Javascript to post the data from a live text field through to another script when the space bar is pressed. I want the data from a the page known as index.php to be posted through another file called save.php. I want to the value of txt_a textfield to to be the value of the post varible text. How would I do this? Below is my code so far...
<html>
<head>
<script type="text/javascript">
function event_a() {
if (event.keyCode == 13) {
$(document).ready(function(){
txt=$document.getElementsByName('txt_a')[0].value;
$.post("save.php",{text:txt});
};
};
}
</script>
</head>
<body>
<form method="POST" name="" action="">
<input name="txt_a" type="text" id="txt_a" onkeypress="event_a()"/>
</form>
</body>
</html>
Thanks
This should get you started:
$(function(){
$('#txt_a').keyup(function(e){
if(e.which === 13) {
$.post('save.php',{text: $(this).val()}, function(data){
//do something with the response
});
}
});
});
And in save.php:
$text = isset($_POST['text']) ? $_POST['text'] : null;
Your javascript function should look more like this:
function event_a(event) { // event needs to be defined as arg to use.
if (event.keyCode == 13) { // ready is used to trigger code when the page is ready, not needed here
var txt=$('txt_a').val(); // assuming you are using jQuery, you can access the value like this
$.post("save.php",{text:txt});
}
}
Why are you passing variable from one file to the another? Use $_SESSION to save and retrieve the set data/variable in multiple pages .

Post form data to a new page and show that page with the posted data

I have:
form.php
preview.php
form.php has a form in it with many dynamically created form objects. I use jquery.validation plugin to validate the form before submitting.
submit handler:
submitHandler: function() {
var formData = $("#myForm").serialize();
$.post("preview.php", {data: formData },function() {
window.location.href = 'preview.php';
});
Question:
- How to change the current page to preview.php and show the data? my submitHandler doesnt work? Any tips?
preview.php:
$results = $_POST['data'];
$perfs = explode("&", $results);
foreach($perfs as $perf) {
$perf_key_values = explode("=", $perf);
$key = urldecode($perf_key_values[0]);
$values = urldecode($perf_key_values[1]);
}
echo $key, $values;
enter code here
You can simply add the onsubmit even of the form and use your validation check along a function. At the end if anything is going good, return it with a true state otherwise, false to stop it from getting submitted.
For example:
<form name="Iran" method="POST" action="preview.php" onsubmit="return alex90()">
</form>
And use this script:
<script language="javascript">
function alex90()
{
// use whatever validation you want
if(form == valid){
return true;
}else{
alert("Something's wrong folk!");
return false;
}
}
</script>
Just submit the form without ajax and make sure action of form is "preview.php"
EDIT: to do this in validation plugin simply remove the submitHandler option you show above. This is used if you want to over ride normal browser form submit, which you now don't want to do.
WIth your ajax submit, then trying to go to the page.... it is 2 page requests and without the form redirecting automatically there is no data available on page load using the javascript redirect
I managed to solve my problem. without sessions.
add to form:
<form action="preview.php" onsubmit="return submitForPreview()">
<input type="hidden" name="serial" id="serial" value="test">
js:
function submitForPreview()
{
if($("#form").valid()){
$('#serial').val($("#newAdForm").serialize());
return true;
}else{
return false;
}
}
preview.php
echo $_POST['serial'];
//Which shows the serialized string. YEEEEYYY :D
Thanks for help folk :D

How would I check the value in form before sending it to server using ajax

I want to check the value enter in the form by user. i have applied validation and its working. The problem is that if user enter any form value incorrectly and then clicks submit, the whole page is refreshed and all input data is lost.
I want that validations is checked before passing it to server. One of my friends told me its possible with AJAX. Can anyone guide a beginner on how to do this?
You can use javascript instead and save the server from transferring some extra KBs and calculations by using Ajax (which technically is javascript but you send the request back to the server)
Jquery has a plugin called validation that will make your life easier though:
http://docs.jquery.com/Plugins/validation
There is a live demo in the link above
For example if you wanted to validate the username you could do this
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
</script>
<form id="commentForm">
<input id="uname" name="name" class="required" />
</form>
yes you can use ajax or otherwise with your current approach you can use sessions to store user data and prevent it from being lost. with ajax you can show response from the server to show to the user.
$.ajax({
url: 'ajax_login.php',
type:'post'.
data:(/*data from form, like,*/ id: $('#username').val())
success: function( data ) {
if(data == 1) {
$('.feedback').html('data has been saved successfully');
//redirect to another page
}
else {
$('.feedback').html('data could not be saved');
$('.errors').html(data);
}
}
});
ajax_login.php would be something like
<?php
if(isset($_POST)) {
//do form validation if it is valid
if(form is valid) {
saveData();
echo 1;
}
else {
echo $errors;
}
}
?>
Do not need ajax.
Just set the onsubmit attribute of your form to "return checkfun();" and define checkfun some way like this:
function checkfun()
{
if ( all things were checked and no problem to submit)
return true;
else
{
alert('ERROR!');
return false;
}
}

Easiest Way To Make A Form Submit Without Refresh

I have been trying to create a simple calculator. Using PHP I managed to get the values from input fields and jump menus from the POST, but of course the form refreshes upon submit.
Using Javascript i tried using
function changeText(){
document.getElementById('result').innerHTML = '<?php echo "$result";?>'
but this would keep giving an answer of "0" after clicking the button because it could not get values from POST as the form had not been submitted.
So I am trying to work out either the Easiest Way to do it via ajax or something similar
or to get the selected values on the jump menu's with JavaScript.
I have read some of the ajax examples online but they are quite confusing (not familiar with the language)
Use jQuery + JSON combination to submit a form something like this:
test.php:
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="jsFile.js"></script>
<form action='_test.php' method='post' class='ajaxform'>
<input type='text' name='txt' value='Test Text'>
<input type='submit' value='submit'>
</form>
<div id='testDiv'>Result comes here..</div>
_test.php:
<?php
$arr = array( 'testDiv' => $_POST['txt'] );
echo json_encode( $arr );
?>
jsFile.js
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
The best way to do this is with Ajax and jQuery
after you have include your jQuery library in your head, use something like the following
$('#someForm').submit(function(){
var form = $(this);
var serialized = form.serialize();
$.post('ajax/register.php',{payload:serialized},function(response){
//response is the result from the server.
if(response)
{
//Place the response after the form and remove the form.
form.after(response).remove();
}
});
//Return false to prevent the page from changing.
return false;
});
Your php would be like so.
<?php
if($_POST)
{
/*
Process data...
*/
if($registration_ok)
{
echo '<div class="success">Thankyou</a>';
die();
}
}
?>
I use a new window. On saving I open a new window which handles the saving and closes onload.
window.open('save.php?value=' + document.editor.edit1.value, 'Saving...','status,width=200,height=200');
The php file would contain a bodytag with onload="window.close();" and before that, the PHP script to save the contents of my editor.
Its probably not very secure, but its simple as you requested. The editor gets to keep its undo-information etc.

JQuery and PHP validation problem?

I want to do the validation on my PHP side and then have my JQuery code display your changes have been saved when the submit button is clicked but the JQuery code states that the changes have been saved even when the validation fails.
How can i fix this so that PHP can do the validation and then JQuery can do its thing when PHP has finished its validation?
Here is my Jquery code.
$(function() {
$('#changes-saved').hide();
$('.save-button').click(function() {
$.post($('#contact-form').attr('action'), $('#contact-form').serialize(), function(html) {
$('div.contact-info-form').html(html);
$('#changes-saved').hide();
$('#changes-saved').html('Your changes have been saved!').fadeIn(4000).show();
});
$('a').click(function () {
$('#changes-saved').empty();
$('#changes-saved').hide();
});
return false; // prevent normal submit
});
});
Here is part of my PHP code.
// Check for an email address:
if (preg_match ('/^[\w.-]+#[\w.-]+\.[A-Za-z]{2,6}$/', $_POST['email'])) {
$email = mysqli_real_escape_string($mysqli, strip_tags($_POST['email']));
} else {
echo '<p class="error">Please enter a valid email address!</p>';
}
in the jquery you can add a if statment that check if the php validation pass,
in the php you need to return a value like 1\0 or true \ false.
and check this parameter in jquery
i add example its using json but is the same issue
jquery :
$.post($('#contact-form').attr('action'), $('#contact-form').serialize(), function(data_pack){
if(data_pack.msg ==1){
# success do something ....
.........
}
alert(data_pack.html);
}, 'json');
the php code like :
if($validation_ok){
$arr = array('msg'=>1,'html'=>$html);
}
else {
$arr = array('msg'=>0,'html'=>$error_msg);
}
echo json_encode($arr);
exit;
You should validate it with both client-side and server-side (ie. with both JavaScript and PHP). If this is not possible, I'd consider posting the form asynchronously and parsing the reply from the server with javascript to determine whether the changes were saved.

Categories