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>
Related
I am trying to send js variables from my js file to another php file when the user hits "FINISH" on the main php page. Here is my code so far:
map.php
<form action="./finalmap.php">
<input class="finish-button" type="submit" value="FINISH" onclick="sendData();" />
</form>
map.js
function sendData() {
$.ajax({
method: "POST",
url: "../finalmap.php",
data: {
selectedLoc: selectionArray,
startLoc: start,
endLoc: end,
dist: distance,
locTypes: allLocations
},
beforeSend : function(http) { },
success : function(response,status,http) {
alert(response);
},
error : function(http,status,error) {
$('.response').html("<span class='error'>Something went wrong</span>");
$(".response").slideDown();
}
});
}
finalmap.php
<?php
$data = $_POST['data'];
echo $data;
?>
Post is successful and I'm able to see the contents(my code) in my finalmap.php from the alert command. When I try to console.log $data in finalmap.php, it is empty/null.
My goal is to send the data to finalmap.php and redirect to it.
To solve this problem, you must reduce what you're testing to one thing at a time. Your code has errors and is incomplete. So let's start with the errors first: If you're using AJAX, you don't want HTML to submit the form in the regular way. If you get a page refresh, your AJAX didn't work.
<button type="button" id="submit-button">FINISH</button>
Note, no <form> is needed; you're submitting through AJAX.
Next, you need to be sure that your ajax function is being executed (since you're using $.ajax, I presume you have JQuery loaded):
<button type="button" id="submit-button">FINISH</button>
<script>
// all listener functions need to wait until DOM is loaded
$(document).ready(function() {
// this is the same idea as your onclick="sendData();
// but this separates the javascript from the html
$('#submit-button').on('click', function() {
console.log('hello world');
});
});
</script>
You use your web console to see the console.log message.
Now, try out the ajax command with a simple post:
<button type="button" id="submit-button">FINISH</button>
<script>
// all listener functions need to wait until DOM is loaded
$(document).ready(function() {
$('#submit-button').on('click', function() {
$.ajax({
method: "POST",
// "./finalmap.php" or "../finalmap.php"?
url: "../finalmap.php",
data: {foo: 'bar'},
success: function(response){
console.log('response is: ');
console.log(response);
}
});
});
});
</script>
finalmap.php
<?php echo 'This is finalmap.php';
If you see This is finalmap.php in the web console after pressing the button, then you can try sending data.
finalmap.php
<?php
echo 'You sent the following data: ';
print_r($_POST);
See where we're going with this? The way to eat an elephant is one bite at a time.
./finalmap.php is not a thing.
Instead the code must look like this:
<form action="/finalmap.php">
<input class="finish-button" type="submit" value="FINISH" onclick="sendData();" />
</form>
Try using this instead.
EDIT: OOPS SORRY, I JUST CPED AND PASTED.
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!
I have a form with an input field for a userID. Based on the entered UID I want to load data on the same page related to that userID when the user clicks btnLoad. The data is stored in a MySQL database. I tried several approaches, but I can't manage to make it work. The problem is not fetching the data from the database, but getting the value from the input field into my php script to use in my statement/query.
What I did so far:
I have a form with input field txtTest and a button btnLoad to trigger an ajax call that launches the php script and pass the value of txtTest.
I have a div on the same page in which the result of the php script will be echoed.
When I click the button, nothing happens...
Test.html
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script>
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
</script>
</head>
<body>
<form name="testForm" id="testForm" action="" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" name="txtTest" id="txtTest"/>
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
<input type="submit" name="SubmitButton" id="SubmitButton" value="TEST"/>
</form>
<div id="testDiv" name="testDiv">
</div>
</body>
The submit button is to insert updated data into the DB. I know I have to add the "action". But I leave it out at this point to focus on my current problem.
testpassvariable.php
<?php
$player = $_POST['userID'];
echo $player;
?>
For the purpose of this script (testing if I can pass a value to php and return it in the current page), I left all script related to fetching data from the DB out.
As the documentation says 'A page can't be manipulated safely until the document is ready.' Try this:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
You need to correct two things:
1) Need to add $(document).ready().
When you include jQuery in your page, it automatically traverses through all HTML elements (forms, form elements, images, etc...) and binds them.
So that we can fire any event of them further.
If you do not include $(document).ready(), this traversing will not be done, thus no events will be fired.
Corrected Code:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
$(document).ready() can also be written as:
$(function(){
// Your code
});
2) The button's HTML is improper:
Change:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
To:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
$.ajax({
url: "testpassvariable.php",
type: "POST",
data: {
userID: $("#txtTest").val(),
},
dataType: text, //<-add
success: function (response) {
$('#testDiv').html(response);
}
});
add dataType:text, you should be ok.
You need to specify the response from the php page since you are returning a string you should expect a string. Adding dataType: text tells ajax that you are expecting text response from php
This is very basic but should see you through.
Change
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
Change AJAX to pass JSON Array.
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "action.php",
data: data,
....
// action.php
header('Content-type: application/json; charset=utf-8');
echo json_encode(array(
'a' => $b[5]
));
//Connect to DB
$db = mysql_connect("localhst","user","pass") or die("Database Error");
mysql_select_db("db_name",$db);
//Get ID from request
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
//Check id is valid
if($id > 0)
{
//Query the DB
$resource = mysql_query("SELECT * FROM table WHERE id = " . $id);
if($resource === false)
{
die("Database Error");
}
if(mysql_num_rows($resource) == 0)
{
die("No User Exists");
}
$user = mysql_fetch_assoc($resource);
echo "Hello User, your number is" . $user['number'];
}
try this:- for more info go here
$(document).ready(function(){
$("#btnLoad").click(function(){
$.post({"testpassvariable.php",{{'userID':$("#txtTest").val()},function(response){
$('#testDiv').html(response);
}
});
});
});
and i think that the error is here:-(you wrote it like this)
data:{userID:$("#txtTest").val(),}
but it should be like this:-
data:{userID:$("#txtTest").val()}
happy coding :-)
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();
});
});
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);
}
});
});