Auto submitting form on page load - javascript

I am trying to submit a form on page load.
<?php if($abc == $xyz){ ?>
<form action="register.php" id="testform">
...form content...
</form>
<?php } else{ ?>
Error
<?php } ?>
<script type="text/javascript">
window.onload = function(){
document.getElementById('testform').submit();
};
</script>
Auto submitting the form works fine, but it is rechecking the condition <?php if($abc = $xyz){ ?> while submitting. How to stop it from performing the same action again?

If you can use Jquery, here is an answer with jquery.
The this one is using the jquery post request, but ignoring the response.
window.onload = function(){
$.post('server.php', $('#testform').serialize())
};
This one is using the jquery post request, but working with response.
window.onload = function(){
var url = "register.php";
$.ajax({
type: "POST",
url: url,
data: $("#testform").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});
return false; // avoid to execute the actual submit of the form.
});
Complete reference of jquery form submit

When you use document.getElementById('testform').submit();
The page will be reload again that why it rechecking condition
To avoid page reload you can use ajax submit data to register.php action.
Example Ajax with Jquery
$.ajax({
method: "POST",
url: "register.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
Hope it help!

Related

PHP how to run php inside php without redirect?

I have two php files. abc.php and def.php
I want to execute only abc.php in browser and only abc.php should be visible in the browser URL bar.
When submit button is clicked on my html page then abc.php should execute and pass the data of form to def.php in background using POST and def.php should not be visible in URL. is that possible?
abc.php
<script>
$.post( "def.php",{parameter: 'value'}, function( data ) {
if (data == 'success'){
alert( 'succeeded' );
}else{
alert( 'failed' );
}
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
def.php
<?php
// Do your functions here
function this(){
// do stuff
} or die('fail');
?>
success
Let me see if I understoond your issue. You have a form in abc.php.
When user submits the form PHP should send data to def.php and back to abc.php without use notices that?
If that's the case, you can do it using AJAX.
In your abc.php put an Id into your form and do the code below with jQuery:
<form method="post" action="" id="ajax_form"> ...
jQuery('#ajax_form').submit(function(){
var formData= jQuery(this).serialize();
jQuery.ajax({
type: "POST",
url: "def.php",
data: formData,
success: function(data) {
alert(data);
}
});
return false;
});

run full php-script in ajax/jquery

Sorry for my bad english. I'm trying to run a PHP function through an ajax script. The PHP script should run as a FULL NORMAL php script. My idea is to run a recaptcha by a Submit button WITHOUT refreshing the page. That is working, but I found no way to run a normal php script after that. Here is the part of my script.
php:
if( isset( $_REQUEST['startattack'] )){
$secret="********************";
$response=$_POST["g-recaptcha-response"];
$verify=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
$captcha_success=json_decode($verify);
if ($captcha_success->success==false) {
echo "<script type='text/javascript'>alert('failed!')</script>";
} else if ($captcha_success->success==true) {
echo "<script type='text/javascript'>alert('success!')</script>";
}
}
html:
<form method='post' id="myform">
<center>
<div class="g-recaptcha" data-sitekey="6LfETygTAAAAAMC7bQu5A3ZhlPv2KBrh8zIo_Nwa"></div>
</center>
<button type="submit" id="startattack" name="startattack" onclick="mycall()" class="btn btn-attack">Start Attack</button>
</form>
ajax:
<script>
$(function () {
$('button').bind('click', function (event) {
$.ajax({
type: 'POST',
url: 'post.php',
data: $('button').serialize(),
success: function () {
alert('button was submitted');
type: 'post';
url: 'post.php';
}
});
event.preventDefault();// using this page stop being refreshing
});
});
</script>
I want to check the recaptcha here. If correct, it should echo correct in PHP and I want to add feature later. The same with the false captcha.
I think you can simplify things a bit. You don't return the response in the Ajax is your main problem.
PHP:
Just echo the returned json from the recaptcha (although I have no idea where you get the g-recaptcha-response key/value, you are not sending it anywhere).
if(isset( $_POST['startattack'] )){
$secret = "********************";
// I have added a key/value in the ajax called "sitekey",
// this might be what you are trying to retrieve?
$response = $_POST["g-recaptcha-response"];
echo file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
exit;
}
AJAX:
I think since the return from the recaptcha is json anyway, just echo it and pick it up on this side:
$(function () {
$('button').bind('click', function (event) {
var statusBlock = $('#status');
statusBlock.text('button was submitted');
$.ajax({
type: 'POST',
url: 'post.php',
data: {
// Not sure if you are trying to pass this key or not...
"sitekey":$('.g-recaptcha').data('sitekey'),
"startattack":true
},
success: function (response) {
var decode = JSON.parse(response);
var alertMsg = (decode.success)? 'Success' : 'Failed';
statusBlock.text('');
alert(alertMsg);
}
});
// using this page stop being refreshing
event.preventDefault();
});
});
Form:
Leave a spot to post the submit status so it doesn't interfere with the return alert dialog window.
<form method='post' id="myform">
<div id="status"></div>
<center>
<div class="g-recaptcha" data-sitekey="6LfETygTAAAAAMC7bQu5A3ZhlPv2KBrh8zIo_Nwa"></div>
</center>
<button type="submit" id="startattack" name="startattack" onclick="mycall()" class="btn btn-attack">Start Attack</button>
</form>

How do i submit a hidden form using ajax when the page loads?

How can i submit a hidden form to php using ajax when the page loads?
I have a form with one hidden value which i want to submit without refreshing the page or any response message from the server. How can implement this in ajax? This is my form. I also have another form in the same page.
<form id = "ID_form" action = "validate.php" method = "post">
<input type = "hidden" name = "task_id" id = "task_id" value = <?php echo $_GET['task_id'];?>>
</form>
similar to Zafar's answer using jQuery
actually one of the examples on the jquery site https://api.jquery.com/jquery.post/
$(document).ready(function() {
$.post("validate.php", $("#ID_form").serialize());
});
you can .done(), .fail(), and .always() if you want to do anything with the response which you said you did not want.
in pure javascript
body.onload = function() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","validate.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("task_id=" + document.getElementById("task_id").value);
};
I think you have doubts invoking ajax submit at page load. Try doing this -
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
"url": "validate.php",
"type": "post"
"data": {"task_id": $("#task_id").val();},
"success": function(){
// do some action here
}
})
})
</script>
If you're using jQuery you should be able to get the form and then call submit() on it.
E.g.:
var $idForm = $('#ID_form');
$idForm.submit();
Simple solution - jQuery AJAX post the value as others have suggested, but embed the PHP value directly. If you have multiple forms, you can add more key:value pairs as needed. Add a success/error handler if needed.
<script type="text/javascript">
$(document).ready(function(){
$.post( "validate.php", { task_id: "<?=$_GET['task_id']?>" } );
})
</script>
As others have said, no need for a form if you want to send the data in the background.
validate.php
<?php
$task_id = $_POST['task_id'];
//perform tasks//
$send = ['received:' => $task_id]; //json format//
echo json_encode($send);
JQuery/AJAX:
$(function() { //execute code when DOM is ready (page load)//
var $task = $("#task_id").val(); //store hidden value//
$.ajax({
url: "validate.php", //location to send data//
type: "post",
data: {task_id: $task},
dataType: "json", //specify json format//
success: function(data){
console.log(data.received); //use data received from PHP//
}
});
});
HTML:
<input type="hidden" name="task_id" id="task_id" value=<?= $_GET['task_id'] ?>>

Ajax Jquery Comments Page

I've looked at many posts here on SO and I thought that what I have would work in terms of sending form data using AJAX without refreshing the page. Unfortunately it's not working and I'm at a loss to see what it going wrong so here is my code:
profile.php
<script>
$(function () {
$('form#commentform').on('commentsubmit', function(e) {
$.ajax({
type: 'post',
url: 'insertcomment.php',
data: $(this).serialize(),
success: function () {
alert('MUST ALERT TO DETERMINE SUCCESS PAGE');
$("#comment").val('');
}
});
e.preventDefault();
});
});
</script>
<form id='commentform' method='post'>
<textarea class='comment' id='comment'></textarea>
<input type='hidden' name='activityid' value='$activityid'>
//$activityid is the ID of the status so the database knows what status ID to connect the comment with
<input type='submit' name='commentsubmit' value='Comment'>
</form>
insertcomment.php
<?php
include 'header.php';
$activityid=htmlspecialchars($_POST['activityid'], ENT_QUOTES);
$comment=htmlspecialchars($_POST['comment'], ENT_QUOTES);
$commentsql=$conn->prepare('INSERT INTO wp_comments (user_id, activity_id, comment, datetime) VALUES (:userid, :friendid, :comment, CURRENT_TIMESTAMP)');
$commentsql->bindParam(':userid', $_SESSION['uid']);
$commentsql->bindParam(':activityid', $activityid);
$commentsql->bindParam(':comment', $comment);
$commentsql->execute();
include 'bottom.php';
?>
The end result hopefully is that the comment gets inserted into the database without refreshing the page and then the text area is reset.
As of right now when I click the comment submit button it refreshes the page.
try this:
$(document).ready(function(){
$('form#commentform').submit(function( e ) {
var postData = $(this).serializeArray();
$.ajax({
type: 'post',
url: 'insertcomment.php',
data: postData,
success: function () {
alert('MUST ALERT TO DETERMINE SUCCESS PAGE');
$("#comment").val('');
}
});
e.preventDefault();
});
});

Getting data from form.serializaArray()

i need help..why does my code not working?what is the proper way to get the data from a form.serialize? mines not working.. also am doing it right when passing it to php? also my php code looks awful and does not look like a good oop
html
<form action="" name="frm" id="frm" method="post">
<input type="text" name="title_val" value="" id="title_val"/>
post topic
</form>
<div id="test">
</div>
Javascript
$( document ).ready(function() {
$('#save').click(function() {
var form = $('#frm');
$.ajax({
url: 'topic.php',
type:'get',
data: form.serializeArray(),
success: function(response) {
$('#test').html(response);
}
});
});
});
Php
<?php
class test{
public function test2($val){
return $val;
}
}
$test = new test();
echo $test->test2($_POST['title_val']);
?>
OUTPUT
You're telling your ajax call to send the variables as GET variables, then trying to access them with the $_POST hyperglobal. Change GET to POST:
type:'post',
Also, it should be noted that you are binding your ajax call to the click on your submit button, so your form will still be posting. You should bind on the form's submit function instead and use preventDefault to prevent the form posting.
$('#frm').submit(function(e) {
e.preventDefault(); // stop form processing normally
$.ajax({
url: 'topic.php',
type: 'post',
data: $(this).serializeArray(),
success: function(response) {
$('#test').html(response);
}
});
});

Categories