onClick and action html - javascript

I am using purecss as a base for a simple project. What I am currently having trouble with is I have a submit button where I will pull some info from the fields, and when clicked I want to run some javascript, as well as take the user to another page. This is what I am trying with no luck:
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" onClick="saveInfo(this.form)" action="confirm.html">Submit</button>
<button type="submit" class="pure-button pure-button-primary">Search</button>
</div>

Give your buttons IDs for simplicity, and take out that nasty inline JS.
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" id="button1">Submit</button>
<button type="submit" class="pure-button pure-button-primary" id="button2">Search</button>
</div>
And then with your script:
var el = document.getElementById("button1"); //cache the save button
el.addEventListener("click", function() {
document.forms[0].submit(); //submit the form or save it etc
window.location.href = "confirm.html";
}, false); //event handler
Send your form data into the function, and then use a simple redirect since only form elements have action properties. Then just add the click event, save your form however you want (submission, ajax call, doesn't matter), then either in a callback or how it is, redirect the client with window.location.href

You could have a Javascript event handler for a button press which might look something like:
document.getElementById('buttonID').onclick=function(){
//Do whatever processing you need
document.getElementById('formID').submit();
};
Alternatively, you could have an event handler in jQuery which would look something like:
$('#buttonID').on('click',function(){
// Do whatever processing you need
$('#formID').submit();
});

You can make the code inside saveInfo() redirect the user to confirm.html after you're done saving the info.
window.location = "confirm.html"

<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" id="button1">Submit</button>
<button type="submit" class="pure-button pure-button-primary" id="button2">Search</button>
</div>
<script>
$(document).ready(function() {
$('#button1').click(function(){
var form = $(this).parents('form');
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: form.serialize(),
dataType: 'json',
success: function(response) {
window.location.href = "http://www.page-2.com";
}
});
return false;
});
});
</script>

Your form could as well do without a type submit..
Type can be a mere button.. On click, you could now do all your javascript stuff with onclick="javascript:somefunction()",
somefunction = function (){
Process javascript here
document.formname.submit();
location.href = "new.html"
}

Related

jQuery to handle two submits one with validation and another without validation

I have a form as:
<form method='post' action="submit.cfm" id='formid' class="formclass" name="formname">
<input type='submit' name='submit' value="save">
<input type='submit' name='submitDraft' value="save draft">
</form>
Now without jQuery, I can submit the form and it will validate with html required fields for whichever fields it needs to be, and I will fill it and save it, now for the save draft, I want to save it without validation and trying to use jQuery to accomplish this but it's not working as expected.
I tried like this:
$("#formid").submit(function(event) {
event.preventDefault(); // prevent default action
var post_url = $(this).attr("action"); // get form action url
var form_data = $(this).serialize(); // Encode form elements for submission
$.post( post_url, form_data, function( response ) {
$("#server-results").html( response );
});
});
Now can I kill 2 birds with one stone, any feasible solution? There is no upload field, so I am safe from that perspective.
More tried came up with
<script type="text/javascript">
$(document).on('submit','#formid',function(event) {
event.preventDefault(); //prevent default action
var _id = $(this).find("#saved").attr('id');
if(_id == 'saved') {
alert('hi');
var isDrafted = 0;
$.validate({
modules : 'date, file'
});
} else {
alert('hello');
var isDrafted = 1;
var post_url = $(this).attr("action"); //get form action url
var form_data = $(this).serialize() & '&isDrafted=' + isDrafted; //Encode form elements for submission
$.post( post_url, form_data, function( response ) {
$("#server-results").html(response);
});
}
});
</script>
Now I am using a formvalidation.net validator, its old but its working, and honestly it is going to be mess to replace it, so how can I make this work?
Something else noticed, I had to click the button twice before it shows validation messages when clicked on save.
And the whose context is save means submit to the action page to save in database
You would need to name the buttons the same with different values, like mentioned here:
<input type='submit' name='submit' value="save">
<input type='submit' name='submit' value="save draft">
Or, since you are open to jQuery, setting a hidden field to which submit button was pressed:
<input type='hidden' name='whichSubmit' id='whichSubmit'>
<input type='submit' name='submit' value="save">
<input type='submit' name='submitDraft' value="save draft">
$("#formid").submit(function(event){
$('#whichSubmit').val(event.target.name);
});
(both of those are untested pseudo code)

aJax update a specific row in sqlite and php using a button

I've got a table that lists values inputted by a user, with 2 buttons on the side to remove or to mark completed. On the page the table is visable, there are 3 tabs, we will call these Tab1, Tab2, and Tab3
Each tab has a table (As described above) with information about a specific type of entry.
These buttons are simple <a href> links, so when clicked they reload the page. This is a problem because the users view is refreshed and it takes the tabs back to the default tab, and is also an inconvenience when trying to mark several entries.
I would like to make these buttons send Ajax requests to another page to process the data. The only problem is, I am not really sure how to make the ajax call.
This is what I have right now
My buttons
echo "<td class='td-actions'>";
echo " <a href='?complete=".$row['uniqueID']."' class='btn btn-success btn-small'>
<i class='btn-fa fa-only fa fa-check'> </i>
</a>
<a href='?remove=".$row['uniqueID']."' class='btn btn-danger btn-small'>
<i class='btn-fa fa-only fa fa-remove'> </i>
</a>";
echo "</td>";
There is one called Complete, and one called Remove.
When either of these are pressed, it currently reloads the page which triggers a few php if statements.
if(isSet($_GET['remove'])) {
$sql = "DELETE from rl_logged where uniqueID='".$_GET['remove']."';";
$ret = $db->exec($sql);
echo "<meta http-equiv='refresh' content='0;index.php' />";
}
if(isSet($_GET['complete'])) {
$sql = "UPDATE rl_logged set complete=1 where uniqueID='".$_GET['complete']."';";
$ret = $db->exec($sql);
echo "<meta http-equiv='refresh' content='0;index.php' />";
}
These are relatively simple functions. My problem is that I do not know javascript very well.
Any help would be much appreciated.
the javascript that I have come up with is this
$(document).ready(function() {
$('#markComplete').click(function() {
var input = input = $(this).text()
$.ajax({ // create an AJAX call...
data: {
onionID: input,
},
type: 'POST', // GET or POST from the form
url: 'pages/ajax/markCompleteRL.php', // the file to call from the form
success: function(response) { // on success..
refreshAllTabsWithFade();
}
});
});
});
using this button
<div name='markComplete' id='markComplete' class='btn btn-success btn-small'>
<i class='btn-fa fa-only fa fa-check'></i>".$row['uniqueID']."
</div>
But, while inspecting with firebug, this seemed to work ONCE, but now the button doesn't do anything.
I tried again this morning, the button presses and the first time it sends this post, then the button doesn't do it again - even on page reload.
I was able to get it to work with the following:
javascript:
$('.markComplete').submit( function( event ) {
event.preventDefault();
event.stopImmediatePropagation();
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // serialize the form
type: "POST", // GET or POST from the form
url: "pages/ajax/repairlogMarks.php", // the file to call from the form
success: function(response) { // on success..
refreshAllTabs();
}
});
return false;
});
button:
<form class="markComplete">
<input type="text" style="display:none;" class="form-control" name="uniqueid" value='<?=$row['uniqueID'];?>'>
<input type="text" style="display:none;" class="form-control" name="markcomp" value='1'>
<button type="submit" class="btn btn-success">
<i class="btn-fa fa-only fa fa-check"></i>
</button>
</form>
Basically, I made the button into a form which I knew how to create an ajax request for.
--
Update to make it work for multiple buttons that do the same function for different unique ID's.
Well for since you're sending the ajax call using "POST", it seems to me that if(isSet($_GET['complete'])) would evaluate to false. Also if your button is generated dynamically using php then change your click handler to the following:
$('document').on('click', '#markComplete', function (){
// Your code here
})
If you have more than one "Mark Complete" button; you need to use classes rather than ID to bind the event.
<button id="test">
Test 1
</button>
<button id="test">
Test 2
</button>
<script>
$('#test').click(function (e) {
console.log('test', e.target);
});
</script>
In this example, only the first button works. jQuery will only return the first element when you specify an ID.
If you use classes to bind the event; both buttons will work:
<button class="test">
Test 1
</button>
<button class="test">
Test 2
</button>
<script>
$('.test').click(function (e) {
console.log('test', e.target);
});
</script>
i think you have an error in your javascript at this line...
var input = input = $(this).text()
try to replace by this..
var input = $(this).text();

PHP-AJAX passing input text to action url directly with ajax

Html:
<form id="yourFormId" method="POST" action="/">
{{csrf_field()}}
<div id="check" class="input-group margin-bottom-sm">
<input class="form-control" type="text" name="find" placeholder="Search">
<button type="submit"><div id="search" class="input-group-addon"><i class="fa fa-search"></i></div></button>
</div>
</form>
JS:
<script>
$(function(){
$(".form-control").on('change',function(e){
$("#yourFormId").attr("action","/" + this.val() );
});
});
</script>
That script doesn't work. I need an ajax solution to pass dynamically my input text to action url. How to do that?
Try this:
<script>
$(function(){
$(".form-control").on('change',function(e){
$("#yourFormId").attr("action","/" + $(this).val() );
});
});
</script>
i think u want to submit your form with ajax request with dynamic text field value.
you can use simple java script function on change or click event whatever you want or with ajax request
you simple use like this
window.location.href="/"+$(this).val();
return false;
This code will submit your form on keyup (as soon as you stop typing)
var timerid;
jQuery("#yourFormId").keyup(function() {
var form = this;
clearTimeout(timerid);
timerid = setTimeout(function() { form.submit(); }, 500);
});
In this code you intercept the form submit and change it with an ajax submit
$('.form-control').bind('keyup', function() {
$("#yourFormId").submit(function (event) {
event.preventDefault();
$.ajax({
type: "post",
dataType: "html",
url: '/url/toSubmit/to',
data: $("#yourFormId").serialize(),,
success: function (response) {
//write here any code needed for handling success }
});
});
});
To use the delay function you should use jQuery 1.4. The parameter passed to delay is in milliseconds.

Submit URL via AJAX / PHP set variable without refreshing page, load variable

I'm having an issue with some script to perform a function via AJAX without refreshing my page. I have a field for a user to enter an external URL, and when they click submit it pops up a modal window, with some information generated through a separate PHP page (images.php currently). I have the script working when the form is actually submitted, the page reloads, and images.php is able to see index.php?url=whatever, but I'm trying to update the page without having to refresh. Do I need to re-render the DIV after defining the variable? I think this may be where I'm having problems.
JS
<script type="text/javascript">
$(function() {
$("#newNote").submit(function() {
var url = "images.php"; // the script where you handle the form input.
var noteUrl = $('#noteUrl).val();
$.ajax({
type: "POST",
url: url,
data: {noteUrl: noteUrl},
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
HTML
<form id="newNote">
<input type="text" class="form-control" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
PHP (aside from form being submitted to this, this is also included in the modal, which opens, but returns NULL on var_dump($postUrl))
$postUrl = $_REQUEST['noteUrl'];
echo $postUrl;
I could definitely be missing something glaring here, but honestly I've tried every combination of AJAX example I could find on here. Am I missing a huge step about having PHP get the variable? Do I need to refresh a DIV somewhere?
Please help.
Here is a bit neater version of the same code, with the missing quote corrected.
$(function() {
$("#newNote").submit(function() {
$('#notePreview').empty();
var url = "images.php"; // the script where you handle the form input.
var noteUrl = $(this).find('#noteUrl').val();
var request = $.ajax({
type: "POST",
url: url,
data: {noteUrl: noteUrl}
});
request.done(function(data) {
$('#notePreview').append(data);
});
return false; // avoid to execute the actual submit of the form.
});
});
Add the attribute name="noteUrl" to your input
<form id="newNote">
<input type="text" class="form-control" name="noteUrl" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
You can also do var_dump($_REQUEST); to see what request variables are being sent.
You might have missed the noteUrl as name. Try giving the name as below and get it using the same name. In your case it is noteUrl
<form id="newNote">
<input type="text" class="form-control" name="noteUrl" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
Shouldn't this
var noteUrl = $('#noteUrl).val();
be
var noteUrl = $('#noteUrl').val();
^^^

JQuery get formaction and formmethod

I have the a like this one
<form id="popisgolubova_form">
<input name="pregledaj" type="button" formaction="uredigoluba.php" formmethod="post" formtarget="_self" value="pregledaj" class="button" onclick="popisgolubova_radiobutton(this)">
<input name="rodovnik" type="button" formaction="rodovnik.php" formmethod="post" formtarget="_blank" value="rodovnik" class="button" onclick="popisgolubova_radiobutton()">
<input name="podaci" type="button" value="poodaci" formaction="podaciogolubu.php" formmethod="post" formtarget="_blank" class="button" onclick="popisgolubova_radiobutton()">
</form>
and javascript
function popisgolubova_radiobutton(element)
{
alert($(element).find("[formaction]").val());
var popisgolubova_radiobutton=$("input[name=RadioGroup1]").is(":checked");
if(popisgolubova_radiobutton==false)
{
alert("nop");
}
else
{
$("form#popisgolubova_form").submit();
}
}
First I'm checking if any checkbox is checked or not and if it is the I can submit the form. But the problem is formaction, formmethod and formtarget. how to get them and submit them
To get the action or method attributes of a form you can try something like below:
$(function() {
var action = $("#formid").attr('action'),
method = $("#formid").attr('method');
});
Hope this helps to get an idea to solve ur problem
<form id="popisgolubova_form">
<input name="pregledaj" type="button" formaction="uredigoluba.php" formmethod="post" formtarget="_self" value="pregledaj" class="button postForm"/>
</form>
$(document).on('click', '.postForm', function () {
$('#popisgolubova_form').attr('action', $(this).attr('formaction'));
$('#popisgolubova_form').attr('method', $(this).attr('formmethod'));
$('#popisgolubova_form').attr('formtarget', $(this).attr('formtarget'));
});
So the question is talking about the unfortunately named
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-formaction
...which is a way to override
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#attr-action
per clicking a properly set up submit button. The place you want to check this is upon submit - when you're sure things are actually being submitted.
The button you used to submit is stored as :focus - this does not seem to be otherwise stored in the event object at the moment.
$('form').on("submit", function(event) {
if( $(':focus').is('[formaction]') ) {
console.warn($(':focus').attr('formaction'));
}
if( $(':focus').is('[formtarget]') ) {
console.warn($(':focus').attr('formtarget'));
}
});
if( $(':focus').is('[formaction]') ) {
console.log($(':focus').attr('formaction'));
}
I had this problem and after searching the web I couldn't find a proper answer. Finally, I realized it's so simple.
When you add an event on form.submit you have an event argument that contains e.originalEvent.submitter, just use it as follows:
$('form').submit(function(e){
var url = form.attr('action');
if (e.originalEvent.submitter) {
var frmAction = $(e.originalEvent.submitter).attr('formaction');
if (frmAction)
url = frmAction;
}
,.....
});
You can use the samething for the formmethod as well.

Categories

Resources