How can I confirm something in JavaScript and then use - javascript

I have a form and when you submit it, a JavaScript message appears.
$message = "Want to insert?";
echo "<script type='text/javascript'>window.confirm('$message');</script>";
And what I want to do is, if the person clicks 'OK' it inserts values in the database, if not it cancels it.
$titulo = $_POST['titulo'];
$mensagem = $_POST['mensagem'];
$ano = $_POST['ano'];
$mes = $_POST['mes'];
$dia = $_POST['dia'];
$link = " ";

Use <form> tag, and handle the onsubmit event. once he clicked 'OK' on message box submit the form.
Once the form gets submitted, In server side (PHP) write a code to get the data ( either by GET/POST which ever way you are sending) and insert into the table.

In simple words, PHP executes first, and then client side JavaScript executes. If you want it to be interactive, you must use AJAX, which will allow you to send PHP command controlled by JavaScript.
If I were you, I would do this way:
if (confirm("Are you sure?"))
$.post("path/to/php.php", {data: you_need_to_send}, function (response) {
if (response == "OK")
alert("All Done!");
});
else
alert("You cancelled the insertion.");
Note: Here, $.post() is a jQuery implementation of AJAX POST method. Just for ease of explanation I gave this. Please don't shout at me for answering a jQuery way for a JavaScript question.
Update
You can use onsubmit of the form to make this possible. Make sure you give a return inside the event:
<form method="post" action="http://example.com/" onsubmit="return confirm('Are you sure?');">
<input />
<input type="submit" value="Send" />
</form>
Run the above snippet and check it out.

You need to pass data using a request to your server. You cannot use JavaScript to write in you database directly since you already use PHP
But to confirm the user before you send your request or you can use this in your JavaScript code before you send your request.
if (confirm('Your Message')) {
// User click OK
// Send your data to server using a Request
} else {
// User click cancel
}

Related

Is it possible the invoke a js in html after php from validation and redirection? Now trying to solve with Ajax

I have a html form on my page. Im using a php file to send an email from the form, and after a successful email send its redirects back to the html form.
After that i want to fade in a bootstrap success-alert.
Is there any event that can handle this or anyway to solve this problem?
This is my JS now, but its dont run because if I hit the send button, its call the php file.:
<script type="text/javascript">
$(document).ready(function() {
$('#btnSubmit').click()(function(){
$('#myAlert').show('fade');
});
});
</script>
I'm assuming you need show alert after the form request is processed and page is redirected to original form page, In that case You need to pass some parameter as a flag in query string while redirecting from server side. On form page you need to check for that flag and show alert.
On server side while redirecting
header("Location:form_page.php?status=success");
On form page
$status = $_GET['status'];
Assign value of $status to js variable and show alert.
Use ajax to achieve that.
Catch the submit event with
$("#btnSubmit").submit(function(){//your ajax});
In the success do your $('#myAlert').show('fade');
You have a good example here : How to submit html form without redirection?

How to setup event tracking on Google Analytics on form submission?

Im trying to track when a user hits the submit button on a contact form.
The page's URL doesn't change, its static.
I can't track a differnt URL after submission, the only option would be to track when a user hits the submit button.
Do I need to edit my analytics account?
Where do I add the additional javascript?
UA is installed correctly (analytics.js)
I'm new to GA and javascript so please break it down for me.
Thanks
I can't track a differnt URL after submission, the only option would be to track when a user hits the submit button.
That is a bit of a non sequitur. Even when the Url does not change there is probably some stuff happening - before you send it there is probably some form validation, and there is some action behind the scene to send there form, like e.g an ajax call.
You could attach event tracking to a submit handler:
<form onSubmit="ga('send','event','category','action','label')">
<input type="text" id="text" name="text">
<input type="submit">
</form>
However this would just tell you that somebody hit the submit button, not if they filled in the form correctly or if the form actually has been sent.
Now I enter speculation land, because I do not know how your form actually works - maybe you can show us an url or give more information.
But maybe you have a validation function that is called on the submit action of the form to see if the form is filled in correctly. In that case it would be advisable to do the tracking in the validation function (horribly simplified example, not production code):
<form onSubmit="validate()"><input type="text" id="text" name="text"><input type="submit"></form>
<script>
function validate() {
var test = document.querySelector('#text').value
if(test = "") {
ga('send','event','Form','Submit','Submitted, but not filled in');
return false;
}
ga('send','event','Form','Submit','Submitted with correct values');
return true;
}
</script>
That's a tad better, at least it tracks the difference between correct submissions and invalid submissions.
Even more speculation: If your form is sent without page reloads it uses probably an ajax call, and there is a huge probability that is uses jQuery (I say that because a) it really is probable and b) it's easier to construct an example in jQuery. The same can be achivied with other libraries or in native JS, but the example will produce an error if you do not use jQuery).
jQuery has a thing called "global ajax handlers". "Global" means they are not callbacks for a specific action, they hook into jQuerys ajax "mechanism" whenever a call to an ajax function is made. The following might work if you have only one aja event per page (else you need logic to distinguish the different ajax event e.g, by checking the url they are being send to), and allows you to track if the ajax call has returned successfully, like when your form data has been send to the server and the request return a 2xx status code:
$(document).ajaxSuccess(function() {
ga('send','event','Form','Submit','Yeah, form data sent to the server');
});
However this does not tell you if the data has been processed correctly. For that you need to make the server emit a success message and check the response:
$( document ).ajaxSuccess(function( event, xhr, settings ) {
if ( settings.url == "formprocessor.php" ) {
if(xhr.responseText.indexOf("success") > -1) {
ga('send','event','Form','Response Received','Form data processed ');
} else {
ga('send','event','Form','Response Received','Form data NOT processed ');
}
}
});
The global ajax event handler is attached to the document - you can put that anywhere on your page, it will do nothing unless an ajax event was called.
Again, this is not production code. Do not try to copy and paste.
This was certainly a bit much if you are new to this, but it should at least help you to improve the question and to see what kind of things are possible. If you can share an Url to your form I can possibly improve the answer.

Trouble passing a variable from javascript page to php page

I want to send a string from one php page to another via a JavaScript page.
The string is sent through upon the push of a button. The name of the
button is changed each time it is displayed and the name of the button is
the one that is sent through. The problem is, it is not getting displayed in
next php page but the alert() function outputs the string as required. What
is wrong with the code?
Here is the php code in the first page
echo "<form method = 'post' action = 'passer.php'>
<input type = 'submit' value = 'play' name = '$ball'></input>
</form>";
Here's the javascript code
$(':input').click(function(){
var cat = $(this).attr("name");
alert(cat);
console.log(cat);
$.post("studSport.php",{input: cat}, function(data){
});
});
And the php code in the next page
{
$receiver = "";
if(isset($_POST['input'])){
$receiver = $_POST['input'];
echo $receiver;
} else{
echo " it is empty";
}
}
The output is always "it is empty" even though the alert() displays the right variable. What is wrong with the code, why wont $receiver be displayed?
Your Ajax request never runs. When you click the input you trigger it… but the input is a submit button so the Ajax request is canceled, the form submits, and a new page is loaded.
Since your form doesn't have an input named input, you'll always failed the test if(isset($_POST['input'])). (The Ajax request, which gets canceled, does input input, but you never make that request).
To stop the form submitting you need to capture the event object and prevent the default behaviour that the event would normally trigger.
$(':input').click(function(evt){
evt.preventDefault();
Note, however, that your success handler function:
function(data){
}
… does nothing, so you won't be able to see the result without inspecting the HTTP response using your browser's developer tools.
It is possible that your goal isn't to use Ajax, but is to load a new page - just with additional data in the form.
To do that, you need to modify the controls in the form instead.
$(':input').click(function(){
var cat = $(this).attr("name");
alert(cat);
$(this).append(
$("<input type='hidden' name='input'/>").val(cat)
});
});
But if you just want to tell which submit button was pressed then don't involve JavaScript at all. Just use a submit button with the name and value you want.
<form method='post' action='passer.php'>
<button name="input" value="<? echo htmlspecialchars($ball); ?>'>
play
</button>
</form>

Prevent form submission after submit button has been clicked using cancel button [duplicate]

This question already has answers here:
Onsubmit still submits when returning false
(2 answers)
Closed 7 years ago.
I have a form that submits values to back-end, but I wish to have a cancel button that stops the submission of the form.
<form action="upload.php" method="post" enctype="multipart/form-data" id="UploadForm">
/*
*
parameters
*
*/
<button type="submit" value="submit" id="SubmitButton">Submit</button>
<button type="button" value="cancel" id="CancelButton">Cancel</button>
</form>
Can anyone please tell how it can be done?
Solution that could work:
var cancelObject = '';
$('#UploadForm').on('submit', function(e){
//prevent default submit
e.preventDefault();
//submit via ajax
cancelObject = $.post('upload.php', $( "#UploadForm" ).serialize());
});
$('#cancel_button').click(function(){
//Cancel the request
cancelObject.abort();
});
UNTESTET! - Only an idea that could work....
Try something like this. Here's your HTML:
<form action="upload.php" method="post" enctype="multipart/form-data" id="UploadForm">
<button type="submit" value="submit" id="SubmitButton">Submit</button>
<button type="button" id="CancelButton" disabled>Cancel</button>
</form>
Here's your jQuery and JavaScript:
$(function() {
var $form = $('#UploadForm');
var form = $form.get(0);
var $submit = $('#SubmitButton');
var $cancel = $('#CancelButton');
var xhr = null;
function cleanup() {
xhr = null;
$submit.removeAttr('disabled');
$cancel.attr('disabled', true);
}
function doneCallback() {
// your code for completed form submission goes here
// redirect the page or whatever you need to do
cleanup();
}
$cancel.on('click', function() {
if($cancel.attr('disabled')) {
return;
}
if(xhr instanceof XMLHttpRequest) {
xhr.abort();
}
cleanup();
})
$form.on('submit', function(event) {
event.preventDefault();
xhr = new XMLHttpRequest();
xhr.open($form.attr('method'), $form.attr('action'), true);
xhr.addEventListener('load', doneCallback);
$submit.attr('disabled', true);
$cancel.removeAttr('disabled');
xhr.send(new FormData(form));
return false;
});
});
This uses the FormData API so check your browser support for that.
This is not as simple as just abort the submit. As soon as that button is clicked there is no practical way to know how much, if any, of its data has been sent yet.
A web browser and a web server doesn't keep its connection between the requests and therefore stopping a script client side doesn't mean it stops it server side.
To abort that submit, you need to send a second request to the server telling so, then at the server, it might already been saved so a delete will be required, and if so, you will then need some unique id to both identify the submit and its abort request, as they will arrive server side as 2 unique requests.
At the server, setting some rules of what and how much data is required to actually save it to the db could be done, still, what if one user has only 1 image and a second has 3, how to know when it is supposed to be an "aborted submit" or not, based on such rules?
A time delay before saving it might be something else, when an abort can be accepted, but again, very difficult to make fail safe and will need the unique id's anyway to identify the requests.
I guess your best bet is to save it, as I would like to believe most user want that, and if a second request comes within a certain time frame, it allows to be deleted.
Accept and use Patrick Roberts answer as a start would be a good idea.
At these 2 similar post you might find additional help.
onSubmit returning false is not working
Onsubmit still submits when returning false
Add onsubmit attribute to the button tag:
<button type="submit" value="submit" id="SubmitButton" onsubmit="return cancel()"> SubmitIt </button>
Javascript:
function cancel()
{
var decision=null;
alert("Press Y to submit or N to cancel");
decision=prompt("Do you want to submit?","Y or N");
if( decision.equals("Y"))
{
return true;
alert("Form has been submitted");
}
else if (decision.equals("N"))
{
return false;
alert("Form submission has been cancelled");
}
else
{
alert("wrong input.Re-submit the form.");
return false;
}
}
Form will be submitted if the value returned is true.The js function asks the user if he wants to proceed and submit or cancel the action.
Hmm, won't this work for you?
form (...) onsubmit="return false;"
In place of 'return false' you can use any JS function you wish. Typical use for this is form validation, for example.

How does "Add Comment" javascript/AJAX work on stackoverflow?

I was just looking at the code in firebug and I can't follow it. I can't figure out how clicking "add comment" calls the jquery function that shows the comment form. On my site I am trying to mimic this behavior. I have a registration form and I want a link such as "Fill in my data" which then displays a text input below the link where they enter a code, and then a submit button that through AJAX populates the fields. I am new to js and AJAX, but am a quick learner so I was hoping to get some clarity here on the details of implementation. Seems to me the displaying of the input field should not be AJAX, but just js. And then submit would trigger the AJAX function. I know AJAX is fairly involved, in terms of having to create an xml that describes the server side data that needs to be collected and then somehow submit button will trigger call to server side php script or something. Conceptually I understand, but mechanically I don't... Thanks! Brian
I just tried implementing as described, but the url is not triggering the js. Here is what I have:
<script type="text/javascript">
$(function(){
$(".previousreg-link").on("click", function( event ){
event.preventDefault(); // Prevents browser following #hash
$(this).hide(); // hide the button
$(".previousreg-form-container").show(); // Show the form parent
});
$(".previousreg-form-container form").on("submit", function( event ){
event.preventDefault(); // Don't send headers
alert( $(this).serialize() +"\nWILL BE SENT TO PHP" );
// $.ajax stuff
});
});
</script>
<a href=# class=previousreg-link>Use previous registration data</a>
<div class="previousreg-form-container dno">
<form>
<textarea name=previousreg></textarea>
<input type=submit>
</form>
</div>
Because my site already loads jquery I didn't add the script declaration for jquery. Is anything above obviously wrong? Thanks.
Here in StackOverflow, the form is already present, but hidden initially (to save valuable space).
(StackOverflow uses a .dno class to hide elements.)
The click on the add a comment button does simply:
hide the clicked add a comment button
show the DIV holding the form
A simple way to do it:
$(function(){
$(".comments-link").on("click", function( event ){
event.preventDefault(); // Prevents browser following #hash
$(this).hide(); // hide the button
$(".comment-form-container").show(); // Show the form parent
});
$(".comment-form-container form").on("submit", function( event ){
event.preventDefault(); // Don't send headers
alert( $(this).serialize() +"\nWILL BE SENT TO PHP" );
// $.ajax stuff
});
});
.dno{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href=# class=comments-link>add a comment</a>
<div class="comment-form-container dno">
<form>
<textarea name=comment></textarea>
<input type=submit>
</form>
</div>
Regarding the $.ajax
since by submitting the form we don't want the page to refresh, AJAX is used to POST data to a PHP (let'ssay: saveComment.php page) which than stores to database. AJAX returns than a message response from the PHP code:
$.ajax({
type : "POST",
url : "saveComment.php",
data : $(this).serialize(), // `this` is our form
success : function( response ) { // Response is the PHP echo
alert("PHP says: "+ response);
// Using jQuery append the message to
}
});
The PHP stuff
in the code above AJAX will POST a serialized data to PHP like:
comment=Please, show what you tried!
The saveComment.php than might look like:
<?php
if ($_SERVER['REQUEST_METHOD'] != 'POST') exit; // Don't allow anything but POST
$response = "";
if ( isset($_POST["comment"]) ) {
$commment = htmlspecialchars( $_POST["comment"] );
// TODO: $userId = retrieve here the user ID from the session;
// Sanitize(!!!!!) and save to database $comment and $userId
$response = $commment;
} else {
$response = "Please, enter a comment";
}
echo $response; // This will be sent/returned to AJAX
exit;
above, whatever you put in the echo, it will be returned by AJAX into the response argument.

Categories