Sending form with PHP through AJAX with no page refresh - javascript

So I have this code to POST data with PHP and AJAX without redirecting page, I'm using the same script on the login page. The login page works like a charm but the other pages don't. The only diffeence between these is that login php script page uses if (empty($_POST) === false) {} and the other pages use if (isset($_POST['save-settings'])) {}. I don't know what do to.. Here below is the script I'm using.
HTML BUTTON
<input id="save-settings" class="submit" type="submit" name="save-settings" value="Save" onclick="return false;" />
JS SCRIPT
$(document).ready(function() {
$("#save-settings").click(function() {
var name = $("#webname").val();
var charset = $("#webchar").val();
var meta = $("#webmeta").val();
var description = $("#webdesc").val();
var startsite = $("#webstartsite").val();
var starturl = $("#webstartsiteurl").val();
var footer = $("#webfooter").val();
$.post("../lib/action.php", {
name: name,
charset: charset,
meta: meta,
description: description,
startsite: startsite,
starturl: starturl,
footer: footer
}, function(data) {
$("#gy-main-notification-bar").hide().html("<h1>!</h1><h2>" + data + "</h2>").slideDown(500);
setTimeout(function() { $("#gy-main-notification-bar").slideUp(500) }, 2500);
});
});
});
PHP SCRIPT
if(isset($_POST['save-settings'])) {
$updatesettings = "UPDATE `settings` SET
`name`='".escape($_POST['webname'])."',
`charset`='".escape($_POST['webchar'])."',
`meta`='".escape($_POST['webmeta'])."',
`description`='".escape($_POST['webdesc'])."',
`startsite`='".escape($_POST['webstartsite'])."',
`starturl`='".escape($_POST['webstartsiteurl'])."',
`footer`='".escape($_POST['webfooter'])."'
WHERE `id`= 1";
if ($update_settings = $db_connect->query($updatesettings)) {}
echo 'Success!';
}
I don't really want to change the isset to empty in the script due the fact that I have all my "onclick" script in one action.php file. When I remove onclick="return:false;" from input it works.. I'm so confused I appriciate any help!

Click event handler function can have event argument. When you catch this argument you can use preventDefault() method. With this method default action of click will be prevented and page won't be refreshed.
Change
$("#save-settings").click(function() {
var name = $("#webname").val();
to
$("#save-settings").click(function(ev) {
ev.preventDefault();
var name = $("#webname").val();

You Forgot to include the post save-settings. You probably should've included it with the ajax post like this:
$.post("../lib/action.php", {
'name': name,
'charset': charset,
'meta': meta,
'save-settings': true,
'description': description,
'startsite': startsite,
'starturl': starturl,
'footer': footer
},
change this in your sql statement for the correct posts
`name`='".escape($_POST['name'])."',
`charset`='".escape($_POST['charset'])."',
`meta`='".escape($_POST['meta'])."',
`description`='".escape($_POST['description'])."',
`startsite`='".escape($_POST['startsite'])."',
`starturl`='".escape($_POST['starturl'])."',
`footer`='".escape($_POST['footer'])."'
WHERE `id`= 1";

writing onclick="return false" in HTML cancels the execution of the javascript code. just delete this onclick="..." and add preventDefault() like this to prevent form submittion
$("#save-settings").click(function(e) {
e.preventDefault();
.....

Related

Pass data between two HTML pages (Google Apps Script)

I'm trying to pass var 'id' from the page 'a.html' to 'b.html'. The var content comes from 'code.gs' as below:
code.gs
function data(){
var id = 1;
return id;
}
Next, I get this var and I show it in 'a.html':
a.html
<?
var id = data();
?>
<h1><?= id ?></h1>
Go to B.html
By clicking 'Go to B.html', the system directs the user to there. I need to bring the same value of var 'id' from the page 'a.html' to 'b.html'.
Ps: searching for a little, I saw that there's a kind to send this var by the command 'localStorage', but it's not working for me. :(
Can anybody help me?
Use localstorage
a.html
localStorage.setItem('id',1)
b.html
var id = localStorage.getItem('id')
the other way is to put it in a js file and import it in both html
Storing & Retrieving html data on the server
Client Side JavaScript:
<script>
function saveId(v) {
google.script.run.saveKeyValue({key:'id',value:v});
}
function getId() {
google.script.run
.withSuccessHandler(function(v){
alert('The value is ' + v );
})
.getKeyValue('id');
}
</script>
Server Side Google Apps Script:
function saveKeyValue(obj) {
PropertiesService.getScriptProperties().setProperty(obj.key,obj.value);
}
function getKeyValue(key) {
return PropertiesService.getScriptProperties().getProperty(key);
}
You could also replace PropertiesService with CacheService.
Client To Server Communications
Properties Service

reCaptcha V3 fails validation on first form submission only

I am trying to set up reCaptcha v3 and it sort of works. For some reason the first time I submit the form it fails but from the second submit onwards it is fine. I can't figure out why this is happening?
<script src="https://www.google.com/recaptcha/api.js?render=MY_SITE_KEY"></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute('MY_SITE_KEY', { action: 'contact' }).then(function (token) {
var recaptchaResponse = document.getElementById('captcha-response');
recaptchaResponse.value = token;
});
});
</script>
<input type="hidden" name="captcha-response" id="captcha-response">
PHP
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretKey.'&response='.$_POST['captcha-response']);
$responseData = json_decode($verifyResponse);
if(!$responseData->score < 0.5) {
$message .= "Verification failed " . $responseData->score;
}
When I submit the form the first time, I get the validation error but my score is 0.9.
Why you have added "!" with "$responseData->score"? you may need to replace your condition with the following:
Replace this:
if(!$responseData->score < 0.5) {
$message .= "Verification failed " . $responseData->score;
}
With this one:
if($responseData->score < 0.5) {
$message .= "Verification failed " . $responseData->score;
}
P.S: Following code takes few seconds to properly load and get a "captcha-reponse" code, so you may need to disable all submit button and wait till you got a "captcha-reponse" to enable the submit button in form or you needs to implementent another way to delay the submit to execute only once you got a "captcha-response" code otherwise you will keep getting "missing-input-response" error message
<script src="https://www.google.com/recaptcha/api.js?render=MY_SITE_KEY"></script>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('MY_SITE_KEY', {
action: 'contact'
}).then(function(token) {
var recaptchaResponse = document.getElementById('captcha-response');
recaptchaResponse.value = token;
});
});
</script>
You should re-generate the reCaptcha token after error form validation occured.
The token reCaptcha only valid for ONE TIME.
So, you have two options to fixes this issue.
1. Reload the page when error occured
This is the easiest way. You only need to reload the page whenever form validation error occured.
Of course, this will trigger the reCaptcha to generate new token.
2. Handle with AJAX (Non-reload page)
This is the best approach, since this will helps the user not losing the form data and continue to fill the form.
So, here's what you should do.
<!-- Put this hidden input inside of your form tag -->
<input name="_recaptcha" type="hidden">
<script src="https://www.google.com/recaptcha/api.js?render=YOUR_SITEKEY_HERE"></script>
<script>
// This will generate reCaptcha token and set to input hidden
const generateRecaptcha = function() {
grecaptcha.execute(
"YOUR_SITEKEY_HERE", {
action: "YOUR_ACTION_NAME"
}).then(function(token) {
if (token) {
document.querySelector("input[name='_recaptcha']").value = token;
}
});
}
// Call it when page successfully loaded
grecaptcha.ready(function() {
generateRecaptcha();
});
// Do your AJAX code here
$.ajax({
url: "https://example.com",
success: function(response) {
console.log(response);
},
error: function(error) {
// Call again the generator token reCaptcha whenever error occured
generateRecaptcha();
}
</script>
Don't forget to put your Site key and your action name. Make sure the action name matches with your Backend action name.
Medium Article

passing data using post array in java-script

i am try to load B.php from A.php after execution in the function and pass some data using a post array from A.php to B.php within same time.
code list as follows
A.php
<script type="text/javascript">
alert_for_the_fucntion();
window.location.href = "B.php";
function alert_for_the_fucntion() {
$.post("B.php", {action: 'test'});
}
</script>
B.php
<?php
if (array_key_exists("action", $_POST)) {
if ($_POST['action'] == 'test') {
echo 'ok';
}
}
?>
for testing purpose i tried to echo something in the B.php. but currently this is not working. have i done any mistakes? or is there any possible method to do this.
Your code does this:
Tells the browser to navigate to B.php (using a GET request)
Triggers a POST request using XMLHttpRequest
The POST request probably gets canceled because the browser immediately leaves the page (and the XHR request is asynchronous). If it doesn't, then the response is ignored. Either way, it has no effect.
You then see the result of the GET request (which, obviously, doesn't include $_POST['action']) displayed in the browser window.
If you want to programmatically generate a POST request and display the result as a new page then you need to submit a form.
Don't use location. Don't use XMLHttpRequest (or anything that wraps around it, like $.ajax).
var f = document.createElement("form");
f.method = "POST";
f.action = "B.php";
var i = document.createElement("input");
i.type = "hidden";
i.name = "action";
i.value = "test";
f.appendChild(i);
document.body.appendChild(f);
f.submit();
If you want to process the results in JavaScript then:
Don't navigate to a different page (remove the line using `location)
Add a done handler to the Ajax code
e.g.
$.post("B.php", {action: 'test'}).done(process_response);
function process_response(data) {
document.body.appendChild(
document.createTextNode(data)
);
}
Try this:
Javascript:
<script type="text/javascript">
window.onload = alert_for_the_fucntion;
function alert_for_the_fucntion() {
$.post("B.php",
{
action: 'test'
},
function(data, status){
if(status=="success"){
alert(data);
}
}
);
}
</script>
PHP
<?php
if(isset($_POST['action'])){
echo $_POST['action'];
}
?>

Executing php script on button click and returning value by ob_start

I have button which in enclosed by <a> tag. When clicked, it executes redirect.php script.
login.php - contains
<input type = "button" id = "loginButton2" class = "btn btn-primary" value = "Login | Twitter " style = "left:650px; margin-top: -32px; position:relative"/>
redirect.php contains twitter authentication code. If authenticated successfully then gives id and name. I want to fetch these both value in index.php
Using ob_start(); I can receive values from php script to JS function via json.
But I am confused about how to manage the code in index.php to execute script on button click and receiving these two value also.
redirect.php
<?php
session_start();
require_once('twitteroauth/twitteroauth.php');
require_once('config.php');
if (empty($_SESSION['access_token']) || empty($_SESSION['access_token']['oauth_token']) || empty($_SESSION['access_token']['oauth_token_secret'])) {
header('Location: ./clearsessions.php');
}
$access_token = $_SESSION['access_token'];
$connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']);
$content = $connection->get('account/verify_credentials');
$twitteruser = $content->{'screen_name'};
$notweets = 5;
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=".$twitteruser."&count=".$notweets);
$id = $content->{'id'};
$name = $content->{'name'};
?>
Please let me know if you need further explaination.
Bottomline:
Rather executing redirect.php script on link click, I want it to execute via function on button click event.
Getting id and name from redirect.php to index.php after redirect script executed
I already have session_start() to manage the twitter session. So dont want to mess up using mutiple session if not necessary ..
UPDATE after david's answer
<body>
<input type="button" value="Run somePHPfile.php" id = "b1" />
<script>
$('#b1').click(function () {
window.location.href = 'redirect.php';
$.get('index.php', function(data) { //If I put this out side click then it gives undefined value for name and id before redirect.php gets executed
// data.id is the id
var id= data.id;
var name = data.name;
alert(name);
});
});
</script>
</body>
Apologize to say:
On button click redirect.php script executed. redirect.php includes other files, which finally reach to index.php. And index.php returns name and id.
So is this enough to manage it : $.get('index.php', function(data) { ... }
To bind to a click event of an HTML button, you would use JavaScript. Since you tagged the question with jQuery, I'll assume its use. The event handler would look something like this:
$('#loginButton2').click(function () {
window.location.href = 'redirect.php';
});
Note: This simulates an anchor click effectively. If you instead want to more closely resemble an HTTP redirect, you might want to use this instead:
window.location.replace('redirect.php');
As for the id and name values, how exactly does this flow return the user to index.php in the first place? Your redirect.php has, well, a redirect (though not all code paths result in that) so it kind of assumes non-AJAX interaction. (I think XHR follows redirects sometimes, but the behavior is different from one browser to another.)
If the redirect isn't terribly important and you just want to make an AJAX call to redirect.php, then you can do that with a simple AJAX request:
$.get('redirect.php');
In order to get those values back to the page, they'll need to be emitted from redirect.php. Something like this:
echo json_encode((object) array('id' => $id, 'name' => $name));
Then in the client-side code you would have those values available in the AJAX callback:
$.get('redirect.php', function(data) {
// data.id is the id
// data.name is the name
// use these values client-side however you need
});
<script>
$("#loginButton2").on('click',function(){
window.location.href="redirect.php";
});
</script>
and in redirect.php file
$_SESSION['id']=$id ;
$_SESSION['name']=$name;
and also
<input type = "button" id = "loginButton2" class = "btn btn-primary" value = "Login | Twitter " style = "left:650px; margin-top: -32px; position:relative"/>
to
<input type = "button" id = "loginButton2" class = "btn btn-primary" value = "Login | Twitter " style = "left:650px; margin-top: -32px; position:relative"/>

Submitting one form and Ajaxing too

I use below code to submit the form AND get registered in aweber email list (addlead.pl is just a registration script).
Here is what i want to accomplish:
User submits a form - it registers him in aweber email list (using two of many form fields) as it woud be signup form, then user gets redirected to normal form action url with posted information from the form (all fields)
$('#redeemform').submit(function() {
var nameVal = $(this).find('input[name="custname"]').val();
var emailVal = $(this).find('input[name="custemail"]').val();
$.post('http://www.aweber.com/scripts/addlead.pl', {
meta_web_form_id: '1234',
meta_split_id: '',
listname: 'listname',
redirect: '',
meta_adtracking: 'newsletter',
meta_message: '1',
meta_required: 'name,email',
meta_tooltip: '',
email: emailVal,
name: nameVal
});
alert("thank you"); //<<magic line
return true;
});
Code works but only with magic line - alert "thank you" - without this line it woud only submit to default form action not registering to aweber.
I've figured out that if i try submitting form (return true) and in the same time send those POST requests like this - site will refresh too fast and ingnore one of the requests.
Question is how do i do it without alert / some fixed delay in this line. Is there some kind of fancy command for it ?
Absolutely BEST solution is to let your form request call weber using CURL or similar on the server
since you cannot Ajax to another domain, you need to be more inventive if you are to run this on the client
So in the submission event we
Change the target to hiddenframe2
submit the aweber form to hiddenframe1
let the main form submit to hiddenframe2
Now you need in the RESULT of your main form return something like
<script>top.location.replace("thankyou.html");</script>
assuming your form sends the request to the same server the html comes from
and have
$('#redeemform').on("submit",function() {
$(this).prop("target","hiddenframe2");
if (!$("#hiddenframe1")) {
$("<iframe/>",{"id":"hiddenframe","name":"hiddenframe1"})
.css("display","none")
.appendTo("body");
}
if (!$("#hiddenframe2")) {
$("<iframe/>",{"id":"hiddenframe","name":"hiddenframe2"})
.css("display","none")
.appendTo("body");
}
var nameVal = $(this).find('input[name="custname"]').val();
var emailVal = $(this).find('input[name="custemail"]').val();
$("<form>",{"action":"http://www.aweber.com/scripts/addlead.pl",
"target":"hiddenFrame1"})
.append("<input/>",{meta_web_form_id: '1234'})
.append("<input/>",{meta_split_id: ''})
.append("<input/>",{listname: 'listname'})
.append("<input/>",{redirect: ''})
.append("<input/>",{meta_adtracking: 'newsletter'})
.append("<input/>",{meta_message: '1'})
.append("<input/>",{meta_required: 'name,email'})
.append("<input/>",{meta_tooltip: ''})
.append("<input/>",{email: emailVal})
.append("<input/>",{name: nameVal})
.submit();
});
Here is what COULD have done had you been able to Ajax to aweber, which you cannot because of cross domain scripting. If they support JSONP/CORS you may be able to do it anyway
$('#redeemformButton').on("click",function() {
var $form = $('#redeemform');
var nameVal = $form.find('input[name="custname"]').val();
var emailVal = $form.find('input[name="custemail"]').val();
$.post('http://www.aweber.com/scripts/addlead.pl', {
meta_web_form_id: '1234',
meta_split_id: '',
listname: 'listname',
redirect: '',
meta_adtracking: 'newsletter',
meta_message: '1',
meta_required: 'name,email',
meta_tooltip: '',
email: emailVal,
name: nameVal
},function() {
$form.submit();
});
});
and have a
<input type="button" id="redeemformButton" value="Sign up and submit" />

Categories

Resources