How do I refresh a value in php from javascript? - javascript

I have a form that I'm submitting using javascript. However, one of the checks it does uses a php script that queries an API and gets a user's password. This is for the purposes of form validation (i.e. if password doesn't match what we have on file..)
I'm using a php script to decode the password like this
function submitForm() {
var options = {
decoded_password: '<?php echo abc_decode($contactInfo['Password'])?>',
}
if (jQuery('#current_password').val() != options.decoded_password && $psc('#current_password').val()) {
render_alert('Your current password does not match what we have on file.');
return false;
} else {
$psc('#account-information').submit();
document.getElementById("account-information").reset();
}
Page loads, great, submit form, great. However, the variable is remembered from the first page load, so if I try to change the password again, it says my password doesn't match what is on file. If I reload the page, no problem.
Is there any way to change the value of $contactInfo['Password'] in javascript without a page reload?

You could try making an AJAX call instead. This won't require a page reload, but will still give you the opportunity to send the data back to the server. If you store the data in the $_SESSION variable it will persist across multiple calls.

Related

Asp.Net MVC app - caching data between page loads

I have a simple Asp.Net MVC app. I have a form, which I'm trying to gather data for, and then submit. However, within that form is a list of selections - each time a selection is made, I go to the server to add that data:
function addSelection(item) {
fetch("/test/selection/" + item,
{
method: "POST"
})
.then(response => {
const name = document.getElementById('Name').value;
localStorage.setItem("name", name);
if (response.ok) {
location.reload();
} else {
console.error("Unable to add");
}
});
}
The server then stores the list in a HttpContext.Session variable.
The target is to keep the name property in place across calls. The code above works great - I set the control on load:
window.onload = function() {
var getName = localStorage.getItem('name');
document.getElementById('Name').setAttribute('value', getName);
}
However, the form itself is eventually submitted, and the entire form, with the selected items, is submitted to the server:
<div>
<input type="submit" value="Submit"
asp-controller="My" asp-action="Create"/>
</div>
The problem that I have is that the local storage still retains the value of name, and so the next time the form is loaded, it's still there. Does anyone have any techniques for achieving the same result without using local storage?
The only solution that I can think of so far is to replace the submit button with a manually coded JS script that resets the value, but that doesn't account for situations where the user just moves away from the form. I feel like I'm heading down a rabbit hole of my own making, and there must be a simpler way to do the same thing.
One solution is to use hidden form fields to persist the data between requests instead of local storage. On each item selection, add the data to a hidden form field on the client-side instead of saving it to local storage. Then, when the form is submitted, the hidden form field value will be included in the form data and can be retrieved on the server-side.
On the server-side, you can retrieve the NameValue from the form data in your action method.
[HttpPost]
public IActionResult Create(string NameValue, ...)
{
...
}

Conceal URL in javascript code ( URL generated by PHP )

I am looking for a solution to the following:
I have a piece of JS code, that performs a redirection to a URL that is constructed with PHP, and that redirection is only done when the user presses a button on a confirmation dialog.
The code is, as follows:
function one() {
window.location.replace("<?php
if($new_redir == "1") {
echo "$new_second_redirect_URL/?token=$hash";
}
else {
echo "$second_redirect_URL/?token=$hash";
}
?>");
}
It works perfectly fine. What I wanna do is conceal the URL that is displayed in the source code when a user opens the page.
What would be the best way to do that?
You're thinking too much into this to be honest.
If they want to avoid the confirmation screen and get the URL from the source, there's not really much you could do.
The best really is possibly performing an AJAX request on confirmation and getting a CSRF token based URL from the response and using that, but that could end up being overkill as well.
You could also make it into an actual <form></form> form with a few hidden fields (again, such as a CSRF token), and perform the post validation onclick. If it a success - redirect them.
UPDATE:
Use robots.txt to stop bots
Build the QS with JS to stop most bots, something like:
var csrftoken='XJIWHEOU324uipHFOFUHR';
var url="http://url.com/page.php?token=";
url=url+csrftoken;
What you could also do, is something like us actually, although for your use case it could be too much.
Log every single page load into the DB, and check if if they're a first time visitor to the page after confirmation.
AJAX call (jQuery example):
$.post( "url_to_backend_page_to_get_url", {hasSubmittedForm:"true"}, function( data ) {
window.location.href = data;
});

Contact Form 7 not redirecting upon email sent

I have a form that I am trying to have redirect to http://www.example.com upon successfully sending an email. I have tried different approaches including on_sent_ok in the additional settings as well as
if(jQuery('.wpcf7-mail-sent-ok').length > 0)
window.location.replace("http://stackoverflow.com");
in my JavaScript, but that does not seem to work as well.
Edit: I forgot to mention that upon the user clicking submit, I do a prevent default in order to do some calculations and generate a PDF. Once it is all done I do
$("form.wpcf7-form").unbind('submit').submit();
to allow the submission to happen. Could this be causing any issues with the redirection?
Contact Form 7 made a ajax call. After success the element is inserted. Then you can check if element exist:
jQuery(document).ajaxComplete(function() {
if (jQuery('.wpcf7-mail-sent-ok').length) {
alert(1);
//window.location.replace("http://stackoverflow.com");
}
});
Well, maybe I'm writing late, but this code will definitelly will do the job. (If you're working in wordpress). I'm using it so far and it's working normally.
Remember to place this code at your functions's file and as final note remember that you must use one or the other, not both...!
add_action('wp_head', 'RedirectsCF7');
// Start of function.
function RedirectsCF7() {
if(is_page("contact-page-or-whatever-page-name-is")) {
echo "<script>document.addEventListener('wpcf7mailsent', function(event) {location = 'https://www.google.com/';}, false);</script>";
}
}
// Or simply add this code to all pages, like this.
if(!is_admin()) {
echo "<script>document.addEventListener('wpcf7mailsent', function(event) {location = 'https://www.google.com/';}, false);</script>";
}
}
Reference here

jQuery already submitted vs. being submitted

I'm working on a jQuery function that forwards form data to page without interfering with the normal submission. I can do it without any issues as long as I capture the submit using .submit(), but I would have to run my own validation on the data because it operates independently of the regular submission. Is there a way for jQuery (or any Javascript) to detect that form data has been posted and validated?
cheers,
Mike
Edit:
Workflow looks like this:
1. User enters data
2. Clicks submit
3. Site runs validation and accepts input
4. Submits data to new page
5. jQuery function detects new data was submitted and accepted so it runs.
More Edits for Clarity
I think you guys are missing the issue. I know how to detect a form is being submited (which is fine and dandy)
This is NOT what I want:
$(this).each(function(){
$(this).submit(function(){
*** Code ***
}
}
Suppose I have a validation script running independent of the code I am currently writing. How can I detect that this ran, and then go to the submit code above?
Use onsubmit="" on your <form> element, but return false. i.e.:
<form action="?" method="post" onsubmit="validate_and_submit(this);return false;">
The return false prevents the form from actually submitting so you can do stuff with AJAX.
Hope this helps!
What you need is AJAX here . So make a XHR request that goes to your server and posts data . The server's response would now go to a callback function ( your jquery function ) . If the data was validated and fine , you proceed further , else you stop .
What you are trying to do is not possible via the normal HTTP POST request .
EDIT: for the original clarification
If you want the server to only received validated data, then just make sure its not submitted to prior to the client-side validation occuring. You can do this with selectively calling event.preventDefault() based on the result of the validation.
$("#form").submit(function(event) {
//some stuff
if (validate(formdata) == false) {
event.preventDefault();
}
});
If you want a server to do the validation and submit to itself or another service, you should make that part of the server-side workflow. So it'd be like
1.) client submits to Service1
2.) Service1 validates
3.) Services1 submits to Service2 (such that service2 never receives code from elsewhere)

onunload - Check if Form was submitted

I have a form on a webpage.when the user moves from that page, I want to check that the form was submitted. If it was, then the user simply continues to the next page, if not, the user receives an alert msg and is brought back to the original page where the form resides.
I am not too familiar with javascript so I would appreciate some code snippets if that's possible?
GF
Your question is a bit vague. Your question implies that you're submitting the form asynchronously, but you said that you aren't familiar with JavaScript. Submitting a form asynchronously requires JS knowledge. Also, if you're actually submitting the form synchronously, the solution would have been too obvious (just render some JS conditionally on the server side).
If you're actually submitting the form asynchronously, then just set some token/toggle in as form's data-xxx attribute after the succesful form submit. E.g.
function submit(form) {
// Do your thing to submit it.
// And then on succes:
form['data-submitted'] = true;
return false;
}
Then, during beforeunload event you just check if the token/toggle is there and in case it's missing, return the message accordingly.
window.onbeforeunload = function() {
for (var i = 0; i < document.forms.length; i++) {
var form = document.forms[i];
if (form['data-submitted'] != 'undefined' && !form['data-submitted']) {
return "There is unsaved data!";
}
}
}
Note that you can't use unload event for this since it too late then to keep the page open.
Update: so the form is submitted synchronously. Okay, whatever server side language you're using, just let it conditionally render a JS window.onbeforeunload call when the form is not submitted (you obviously already know when the form is been submitted, how else would you be able to process it? ;) ). You also need to disable the window.onbeforeunload call when the form is about to be submitted.
Based on your question history I bet that you know PHP, so here's a PHP targeted kickoff example:
<?php
if (!$form_is_submitted) {
echo '<script>window.onbeforeunload = function() { return "There is unsaved data!"; }</script>';
echo '<form onsubmit="window.onbeforeunload=null">';
}
?>

Categories