I want to pass a selected checkbox value, when a user submits (POSTs) a form, to Google Analytics to track as a custom metric within Google Analytics dashboard.
The user will submit their choice to the server which will first call the JS sendDataToGA(selectedOption) { function to pass that data to GA, then the POST will run.
How do I accomplish this? It seems that the POST is firing and not calling the JS function.
PHP/HTML:
<?php if (!empty($_POST)): ?>
Selection: <?php echo htmlspecialchars($_POST["option"]); ?><br>
<?php else: ?>
<!-- On form submit, fire a custom GA function to capture the selected option -->
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post" >
<input type="checkbox" name="option" value="option 1">Option 1<br>
<input type="checkbox" name="option" value="option 2">Option 2<br>
<input type="submit" value="Submit" id="submitBtn" onclick="sendDataToGA(selectedOption);">
</form>
<?php endif; ?>
JS:
function sendDataToGA(selectedCheckboxValue) {
ga('send', 'event', 'category', 'action', {
'metric1': selectedCheckboxValue,
'hitCallback': function () {
console.log("data has been sent to Google Analytics");
}
});
}
If you give your form an id attribute you can do the following using jQuery
$("#myForm").submit(function () {
ga(...);
});
or without jQuery:
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> onsubmit="sendDataToGA(selectedOption)" method="post">
...
</form>
You can intercept the submit event before it posts to the server. In jQuery, this is a handler you attach in the domReady event. This assumes your form has id="formid", and you can halt the postback by setting everythingIsOkay = false.
$(document).ready(function () {
$("#formid").submit(function(event) { //Catch form submit event
event.preventDefault(); //Stop it from posting back unless you tell it to
var everythingIsOkay = true;
//Do your processing here
if(everythingIsOkay){
document.forms["formid"].submit(); //Go ahead and postback
}
});
});
Related
I have tried many of the scripts and jquery examples here on this website, but none of them worked for my specific situation.
Basically I'm trying to autosubmit a form (without user needing to press submit).
As soon as the page loads, the autosubmit will be triggered.
My Form:
<form method="post" id="adduser" action="<?php the_permalink(); ?>" >
<input type="text" name="confirmed" id="confirmed" value="yes" class="regular-text" />
<p class="form-submit">
<?php echo $referer; ?>
<input name="updateuser" type="submit" id="updateuser" class="submit button" value="<?php _e('Update', 'profile'); ?>" />
<?php wp_nonce_field( 'update-user' ) ?>
<input name="action" type="hidden" id="action" value="update-user" />
</p>
</form>
As you can see I have php in the form's action, so javascript/jquery that needs to set an action URL inside the script won't work, as they don't allow a php.
Any help would be greatly appreciated.
You could set an event to trigger after the document has loaded, like this:
<script>
document.addEventListener('DOMContentLoaded', (e) => {
const form = document.querySelector('#adduser')
form.submit()
})
</script>
This will submit the form right after all the contents in the DOM will be loaded.
$(function () {
$('#adduser').submit();
}
This should work.
try the following code:
<script>
$(document).ready(function () {
var formData = $('#adduser').serializeArray();
if(formData.length != 0) {
$("#adduser").submit();
}
})
</script>
I just started learning ajax and its really great and time saving i agree.
But i got stuck at this point sending form data without page reload.
Below is my html code.
<form id="form4" method="post">
<input type="checkbox" name="test" id="agreed" value="check">
<br>
<br>
<input type="submit" id="form-submit" name="submit" value="Send">
<p class="form-message"></p>
</form>
Below is my Ajax script
<script>
$(document).ready(function() {
$("#form4").submit(function(event) {
event.preventDefault();
var action = 'another_test';
var agreed = $("#agreed").val();
var submit = $("#form-submit").val();
$(".form-message").load("test3.php", {
test: agreed,
submit: submit,
action: action
});
});
});
</script>
Below is my php code
<?php
if (isset($_POST['action'])) {
if ($_POST['action'] == 'another_test') {
$test = $_POST["test"];
$errorEmpty = false;
if (!empty($test)) {
echo "<p>Click the checkbox pls</p>";
$errorEmpty = true;
}
else {
echo "<p>Checkbox clicked</p>";
}
} else {
echo "Error.. cant submit";
}
}
?>
<script>
var errorEmpty = "<?php echo $errorEmpty ?>";
</script>
The php file is on another page called test3.php
This particular code works if it was an input text but doesn't work for a checkbox.
Please help me so i can learn well.
Thanks in advance.
.load() (as per the documentation) performs a GET request, not a POST, but your PHP is (as shown by the $_POST references) expecting a POST request - and it usually makes sense to submit form data using POST.
So you'd be better to use $.post() - this will send a POST request. Then you can handle the response and load it into your "form-message" element in the "done" callback triggered by that request.
N.B. You could also make the code shorter by putting the "action" variable as a hidden field in the form, and then simply serialize the form in one command instead of pulling each value out separately.
Example:
HTML:
<form id="form4" method="post">
<input type="checkbox" name="test" id="agreed" value="check">
<br>
<br>
<input type="submit" id="form-submit" name="submit" value="Send">
<input type="hidden" action="another_test"/>
<p class="form-message"></p>
</form>
JavaScript
$(document).ready(function() {
$("#form4").submit(function(event) {
event.preventDefault();
$.post(
"test3.php",
$(this).serialize()
).done(function(data) {
$(".form-message").html(data);
});
});
});
Documentation:
jQuery Load
jQuery Post
jQuery Serialize
I have a simple HTML document with a form I would like to post to the server without leaving the page. I've Googled around the internet all day trying to figure out how to get this to work and I've come up with the following code:
<body>
<script>
$(document).ready(function() {
$('#newResource').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'scripts/script.php?new-resource=1',
data: $('#newResource').serialize(),
success: function () {
alert('form was submitted');
}
});
return false;
});
});
</script>
<form id="newResource" class="form-basic" enctype="multipart/form-data" method="post" action="scripts/script.php?new-resource=1">
<label><b>Resource Name:</b></label>
<input class="input-text" type="text" placeholder="Enter the resource name..." name="name" id="name" autocomplete="off" required="">
<br>
<label><b>Resource URL:</b></label>
<input class="input-text" type="text" placeholder="Enter the resource URL..." name="url" id="url" autocomplete="off" required="">
<br>
<label><b>Resource Department:</b></label>
<p>Select the department this resource should belong to.</p>
<select class="input-select" name="department" id="department">
<option value="5">Human Resources</option>
<option value="1">Information Technology</option>
<option value="3">Marketing</option>
<option value="0">No Department</option>
<option value="6">Purchasing</option>
<option value="4">Sales</option>
</select>
<br>
<label><b>Resource Icon:</b></label>
<p>Select the icon image to be displayed with this resource.</p>
<select class="input-select" name="icon" id="icon">
<option value="bell.png">Alarm Bell</option>
<option value="chat-bubbles.png">Chat Bubbles</option>
<option value="chronometer.png">Chronometer</option>
<option value="database.png">Database Icon</option>
<option value="envelope.png">Envelope</option>
<option value="folder.png">File Folder</option>
<option value="analytics.png">Monitor with Line Graph</option>
<option value="pie-chart.png">Monitor with Pie Chart</option>
<option value="networking.png">Networking Heirarchy</option>
<option value="orientation.png">Orientation Arrow</option>
<option value="server.png">Server Rack</option>
<option value="settings.png">Settings Gears</option>
<option value="speedometer.png">Speedomoeter</option>
<option value="worldwide.png">World Wide Web Globe</option>
</select>
<br>
<div style="float: right;">
<button type="button" onclick="loadPrefs('resources');" class="form-button cancel">Cancel</button>
<button class="form-button submit" type="submit">Submit</button>
</div>
</form>
</body>
The code is all within the body tag.
The problem is that when I click the submit button I am redirected to the PHP action script. Does the script I have need to be in the head tag instead?
If I remove the action from the form then the script redirects to the same page but no data is submitted.
Here is the PHP script if necessary:
if(isset($_GET['new-resource'])){
// escape the SQL input for security
$name = mysqli_real_escape_string($conn, $_POST['name']);
$url = mysqli_real_escape_string($conn, $_POST['url']);
$department = mysqli_real_escape_string($conn, $_POST['department']);
$icon = mysqli_real_escape_string($conn, $_POST['icon']);
// Run the SQL query to add the new resource item
$sql = "INSERT INTO Resources (ID, ResourceName, ResourceURL, IconImg, Department) VALUES (NULL, '$name', '$url', '$icon', '$department');";
$conn->query($sql);
// Close the SQL connection
$conn->close();
}
I can't seem to figure out why this is not working. Any thoughts and feedback are appreciated.
The important info in your case was "The HTML form elements are added with AJAX". At $(document).ready(), the #newResource form element did not yet exist, so the event was never bound. In your working example you used event delegation: $(document).on('click', '.submit', function(e) {...}, this is the correct way setup event listeners for non-existing elements.
Your event handler is bound to the submit event of the form. By the time the form has been submitted, it's too late to stop the default synchronous HTML form submission.
Bind your handler to the to click event on the submit button, use event.preventDefault() and submit the form via Ajax:
$(document).ready(function() {
$('.submit').click(function (e) {
e.preventDefault();
var form = $('#newResource');
var action = form.attr('action');
var data = form.serialize();
$.ajax({
type: 'POST',
url: action,
data: data,
success: function () {
alert('form was submitted');
}
});
});
});
Please note, the way this is written, it will fire for any click of an element with a class of submit. Since you may have more than one form on your web page and more than one button with a class of submit, it's not good to have the form variable use a hard-coded ID selector.
If the HTML of all your website forms are always coded this same way, with the submit button inside of a div which is nested in the form, you could replace:
var form = $('#newResource');
with:
var form = $(this).parent().closest('form');
Now you can wrap that code in a function called "bindForms()" or whatever, and you have a generic recipe for handling all forms, provided that the HTML structure is always the same (or at least, to the extent that the submit button always has a class of submit and is always wrapped in a parent container which is a child of the form.
Ok, I've managed to get this following code to work:
<script type="text/javascript">
$(document).on('click', '.submit', function(e) {
debugger;
e.preventDefault();
var form = $(this).parent().closest('form');
var action = form.attr('action');
var data = form.serialize();
$.ajax({
type: 'POST',
url: action,
data: data,
success: function () {
loadPrefs('resources');
}
});
});
</script>
The HTML form elements are added with AJAX but so was the script element. I moved the script element to the top of the page so that it is static and no longer loaded with the form.
I have a page which has lot of post data in the url.
For example,
www.test.com/test.php?userid='tester'&name=test&so on
The above page has a form that has something like this:
<?
$set=get_value_set;
if($set ==1) {
$set_value="SET";
} else {
$set_value="UNSET";
}
?>
<form name="test">
<input type="text" readonly="READONLY" value="<? echo $user_id; ?>">
<input type="submit" value="Email" name="submit_user">
<input type="submit" value="<? echo $set_value; ?>" name="submit_user">
<?
function setuser()
{
//sets the value
}
function email_user()
{
//sets the value
}
?>
there are two buttons above, when I click on email, i want the value of email button to be passed to the email_user function and do some proceesing there. Similar thing when I click on the set button.
NOTE:But in both cases above, I want the form to remain in the same page with the same post data in the url, but I also want the page to be refreshed so that the set button can have a value of Set or Unset depending on the database update.
Is this possible?
I would start to remove the submit action of each button and change them to
<input type="button" class="btn-Email" value="Email" name="submit_user" />
<input type="button" class="btn-Other" value="<? echo $set_value; ?>" name="submit_user" />
and then, using jQuery, you can easily process each click and submit the form
$(function() {
$(".btn-Email").click(function() {
// append anything you want
var but_email_value = $(this).val(), // or $(".btn-Email").val()
btn_other_value = $(".btn-Other").val();
$("form").submit();
});
$(".btn-Other").click(function() {
// append anything you want
var but_other_value = $(this).val(), // or $(".btn-Other").val();
btn_email_value = $(".btn-Email").val();
$("form").submit();
});
});
change your HTML
<form id="test" name="test">
...
<button onclick="email_user();">Email</button>
<button onclick="setuser();"><? echo $set_value; ?></button>
</form>
your functions should submit the form for you:
document.getElementById("test").submit();
I have a list, (a simple list) from which i am able to select and set elements (using js), and then a form that allows me to choose how many elements i want, and a submit form.if one doesn't select an element, there is a script that throws an exception. The problem is that i want that the form doesn't submit, if an element is not selected, but not throw an exception, but to show me a message down the submit button (using jquery). my script below:
<? foreach ($types as $type):?>
<ul class = "product_types">
<? if ($type->stock_2 > 0):?>
<li id = 'product_types'><a href="#" onclick='selecteazaElement(<?= $type->id; ?>,<?= $type->stock_2; ?>);'><?= $type->label; ?></a></li>
<? else: ?>
<li id = 'product_unavailable_types'><label><?= $type->label; ?></label></li>
<? endif; ?>
</ul>
<? endforeach; ?>
<form name="addtobasket" method="POST" action="<?= Route::url('Add to Basket', array('sale_id' => $sale->id)); ?>">
<input type="hidden" name="idOfSelectedItem" id="idOfSelectedItem" value="-1">
<select name="number" id="number">
<option value=0>Alege numarul de produse</option> </select>
<button type="submit" name = "submit" onclick="addtobasket";>Adauga in cos</button><br />
</form>
and the js that sets the list elements:
<script type="text/javascript">
function selecteazaElement(id,stock)
{
document.addtobasket.idOfSelectedItem.value=id;
window["canSubmit"] = true;
var number23=document.addtobasket.number;
number23.options.length=0;
if (stock>=6)
stock=6;
for (i=1;i<=stock;i++)
{
//alert ('id: '+id+'; stock: '+stock);
number23.options[number23.options.length]=new Option(i, i);
}
//window.status="my status";
}
Add a submit listener to the form. When it's submitted, check to see if an element is selected, and if not you can prevent the submission by using return false. Here's an example:
$('#myForm').submit(function()
{
if (/* test case not true */) {
$('#myError').show();
return false;
}
// ... continue work
});
And here's the HTML:
<form id="myForm">
<input type="text"/>
<input type="submit"/>
</form>
If you don't want to use jQuery, you can also handle the submit event with plain JavaScript like so:
var myform = document.getElementById('myForm');
myform.addEventListener('submit', function() { console.log('Submitted!'); return false; });