JavaScript ActiveElement is form not button with Safari - javascript

I have a list of forms on my site with JS/AJAX that submits the forms on click. The JavaScript determines the submit type based on the active element. This has been working find across multiple browser.
Problem: Basically Safari (Version 10.0.2) on MAC considers the activeElement the form instead of the button so the getAttribute returns null. Is there a way to get the clicked element? I need to know which button the user clicked.
HTML Stuff:
<div id="#Records">
<form action="update.php" method="post">
...
<input name="submit" type="submit" data-action="send" value="send stuff" />
<input name="submit" type="submit" data-action="update" value="update" />
<input name="submit" type="submit" data-action="delete" value="delete" />
</form>
</div>
JavaScript stuff
$("#Records form").submit(function (e) {
e.preventDefault();
var url = this.action;
var data = $(this).serializeArray();
var action = document.activeElement.getAttribute('data-action');
data.push({ name: 'submit', value: action });
$.ajax({
type: "POST",
data: data,
cache: false,
url: url
}).done(function (data) {
$("#Records").html(data);
}).fail(function (result) {
ShowMessage("Error updating record!");
});
return false;
});

Can't you get the element using e.currentTarget instead of the active element? Something like
var action = $(e.currentTarget).attr('data-action');
(I'm assuming button click leads to the submit)

Ok, based on Tiny Giant and other comments I have changed the code to this. Not sure it is the best method but seems to work everywhere I have tested.
note simplified, comments welcome
HTML
<div id="#Records">
<form action="update.php" method="post">
...
<input type="button" onclick="return $(this).processRequest(this, 'send');" data-action="send" value="send stuff" />
<input type="button" onclick="return $(this).processRequest(this, 'update');" data-action="update" value="update" />
<input type="button" onclick="return $(this).processRequest(this, 'delete');" data-action="delete" value="delete" />
</form>
</div>
JavaScript
jQuery.fn.processRequest =
function(button, action)
{
var form = $(button).parents('form');
var url = form[0].action;
var data = $(form).serializeArray()
data.push({ name: 'submit', value: action });
$.ajax({
type: "POST",
data: data,
cache: false,
url: url
}).done(function (data) {
$("#Records").html(data);
}).fail(function (result) {
ShowMessage("Error updating record!");
});
return false;
}

Related

AJAX request in a looping form

I was wondering how to make an ajax request separately inside the looping form, which able to send the async delete request when I click the specified row deleted button.
not sure how to allocate the identity when I click the button using jquery.
foreach(var item in Model){
<form>
<input type="text" id="id" name="id" value="item.id"/>
<input type="button" id="btn" name="submit" value="Delete"/>
</form>
}
<script>
$("#btn").click(function(){
// alert the id value
});
</script>
You can try with
foreach(var item in Model){
<form>
<input type="text" id="id" name="id" value="item.id"/>
<input type="button" class="btn" data-id="item.id" name="submit" value="Delete"/>
</form>
}
<script>
$(".btn").click(function(){
// alert the id value
alert($(this).attr("data-id"))
});
</script>
I have found the solution based on Agus Friasana method:
$(".btn").click(function () {
// to skip the alert from parent modal button
if ($(this).attr("data-id") != undefined) {
alert($(this).attr("data-id").toString());
$.ajax(
{
url: "your url" + $(this).attr("data-id").toString(),
type: "DELETE",
dataType: "text",
success: function () {
alert('success');
},
error: function () {
alert('fail')
}
}
);
}
});

Form not submitting on ajax request

So I'm comparing the value of the input field entered by the user to the value of the mysql DB (using an Ajax request to the checkAnswer.php file). The request itself works fine, it displays the correct "OK" or "WRONG" message, but then it does not submit the form if "OK". Should I put the .submit() somewhere else?
HTML code:
<form id="answerInput" action="index" method="post">
<div id="answer-warning"></div>
<div><input id="answer-input" name="answer" type="text"></div>
<input type="hidden" id="id" name="id" value="<?=$id?>">
<div><button type="submit" id="validate">Valider</button></div>
</form>
</div>
JS code
$("#validate").click(function(e){
e.preventDefault();
$.post(
'includes/checkAnswer.php',
{
answer : $('#answer-input').val(),
id : $('#id').val()
},
function(data){
if(data === '1'){
$("#answer-warning").html("OK");
$("#answerInput").submit();
}
else{
$("#answer-warning").html("WRONG");
}
},
'text'
);
});
I think it is because you set your button type as submit. Why?
When you do $("#validate").click(function(e){, you implicitly replace the default submit behavior of the form.
As you want to interfere in the middle of the process for extra stuff, I suggest you change the button type to button or simply remove the type attribute.
Then the $("#validate").click(function(e){ will alter behavior of click, not the submit of form.
<form id="answerInput" action="index" method="post">
<div id="answer-warning"></div>
<input id="answer-input" name="answer" type="text">
<input type="hidden" id="id" name="id" value="<?=$id?>">
<button onlcick="validate()">Valider</button>
</form>
/******** JS ************/
function validate(){
var post = {};
post['answer'] = $('#answer-input').val();
post['id'] = $('#id').val();
$.ajax({
url: 'includes/checkAnswer.php',
type: 'POST',
data: {data: post},
success:function (data) {
console.log('succsess');
},
error:function (jQXHR, textStatus, errorThrown) {
console.log('failure');
}
});
}

Submit jQuery ajax Form with multi buttons and PHP

here is my problem:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<form id="roomform" action="room.php" method="POST">
<button name="room" value="Room01">IMG01</button>
<button name="room" value="Room02">IMG02</button>
<button name="room" value="Room03">IMG03</button>
<button name="room" value="Room04">IMG04</button>
<button name="room" value="Room05">IMG05</button>
<button name="room" value="Room06">IMG06</button>
<button name="room" value="Room07">IMG07</button>
<button name="room" value="Room08">IMG08</button>
<button name="room" value="Room09">IMG09</button>
<button name="room" value="Room10">IMG10</button>
</form>
<script type="text/javascript">
var frm = $('#roomform');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
</script>
</body>
</html>
PHP using $_POST['room'] to get the room name Room01-Room10(Room100 maybe?) and doing something special.
It works good.
Now I need to do this using Ajax. Above code seems ok, but I cannot get any data(Room01-Room10) from it.
then I found this:
<form action="/vote/" method="post" class="vote_form">
<input type="hidden" name="question_id" value="10" />
<input type="image" src="vote_down.png" class="vote_down" name="submit" value="down" />
<input type="image" src="vote_up.png" class="vote_up" name="submit" value="up" />
</form>
$(".vote_form").submit(function() { return false; });
$(".vote_up, .vote_down").click(function(event) {
$form = $(this).parent("form");
$.post($form.attr("action"), $form.serialize() + "&submit="+ $(this).attr("value"), function(data) {
// do something with response (data)
});
});
but it seems not suitable to my case, my all buttons with same name="room" for $_POST['room'] and no class.
and this not works:
$(function() {
$('input[name=room]').click(function(){
var _data= $('#roomform').serialize() + '&room=' + $(this).val();
$.ajax({
type: 'POST',
url: "room.php?",
data:_data,
success: function(html){
$('div#1').html(html);
}
});
return false;
});
});
anyone know how to solve this problem?
Your (last) code is not sending AJAX requests because you attached the handler to the wrong input selector. Your buttons are button elements, not input elements. This should work:
$('button[name=room]').click(function() { ...
Edit:
Your first code isn't working because your buttons are just buttons. You have to add the type attribute to let your form know you're pressing a submit button: <button type="submit"...>
The serialize() method does not collect the data from a button element. Take a look to the documentation on this link: https://api.jquery.com/serialize/. In your code I would assume that your data object is empty.
Also if you post several form controls (serialized) , they should have different name attributes.

Form submitting on return false

I have the following form:
<form id="sizeForm" style="float:right;">
<input value="test" name="comments" type="text">
<input class="btn-sm btn-main" value="Save" type="submit">
</form>
Which I'm trying to submit using ajax but the form is posting, here's the JQuery:
$("#sizeForm").submit(function () {
$.ajax({
type: "POST",
url: "/ajax/actions/editSize.php",
data: $(this).serialize(),
success: function (dataBack) {
$('#size2'+dataBack).fadeOut().promise().done(
function(){
$('#size1'+dataBack).fadeIn();
}
);
}
});
return false;
});
Any ideas where I'm going wrong?
The issue may be with your PHP script (which you haven't provided), but here are some ideas.
HTML:
<form id="sizeForm" style="float:right;">
<input value="test" name="comments" type="text">
<input class="btn-sm btn-main" value="Save" type="submit">
</form>
javascript:
$("#sizeForm").on('submit', function () {
$.ajax({
type: "POST",
url: "/ajax/actions/editSize.php",
data: $(this).serialize(),
success: function (dataBack) {
$('#size2'+dataBack).fadeOut().promise().done(
function(){
$('#size1'+dataBack).fadeIn();
}
);
}
});
return false;
});
In your PHP script add something like this so you know the value is received. This will show in the network tab in the browser developer tools.
if (!empty($_POST['comments'])) {
echo "form submitted!";
exit;
}
In the network tab, you should see an entry like POST editSize.php. If you don't see it, the form was not sent. If you do see it, open it up and look at the "post" tab. This will show you what was sent. Then, your "response" tab will show you the output from your PHP script.

multiple submit buttons different actions with passing variables

I have a form like the code below (called index.php) with multiple submit buttons. I'd like to have different php actions on submit buttons. The 1st button without refreshing the browser's page and of course with passing the variables. The other with normal action which can redirect to a new page (here form_submit.php). I managed to make the 1st button working with the help of this topic but I can't distinguish the 2nd button from the 1st one. Is there any way to switch between functionality of these buttons ?
<? php>
if($_POST['formSubmit'] == "Next") {
$var1 = $_POST['name1'];
$var2 = $_POST['name2'];.
session_start();
$_SESSION['variable1'] = $var1;
$_SESSION['variable2']= $var2;
header("Location: form_submit.php");
exit;
}
?>
<html>
<body>
<form action="index.php" method="post">
<input type="text" name="name1" id="name1" maxlength="50" value="<?=$var1;?>" />
<input type="text" name="name2" id="name2" maxlength="50" value="<?=$var2;?>" />
<input type="submit" name="dataSubmit" value="Insert Data" />
<input type="submit" name="formSubmit" value="Next" />
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'data_submit.php',
data: $('form').serialize(),
});
});
});
</script>
</form>
</body>
</html>
As soon as 1st button doesn't actually need to make submit you can set 'onClick' event handler on it and make it just 'button'. In this case only JS will be triggered when you press the button and browser will not submit the form. Here is what I mean:
<input type="button" id="justButton" name="dataSubmit" value="Insert Data" />
<input type="submit" name="formSubmit" value="Next" />
<script>
$(function () {
$('#justButton').on('click', function (e) {
$.ajax({
type: 'post',
url: 'data_submit.php',
data: $('form').serialize(),
});
});
});
</script>
First, add clicked class to button:
$('.submitButton').click(function(){
$('.submitButton').removeClass('clicked');
$(this).addClass('clicked');
});
Than in submit event check button:
$('form').submit(function(){
var button = $('.submitButton.clicked');
if (button.attr('id') == 'name1') {
...
} else {
...
}
return false;
});

Categories

Resources