Submit ajax form on load - javascript

I have a page that generates n ajax forms, one for each camera. On submit each loads a div with pictures from each camera. I'd like to submit the forms as they load.
So far I have this, taken from the action the form already takes when it submits, minus the on-click event binding the submit button to the ajax event.
Here's the HTML (Some CakePHP div soup removed)
<div id="CameraContainer">
<form action="/Cameras/ajaxPicture" id="CameraShowForm" method="post" accept-charset="utf-8">
<input type="hidden" name="_method" value="POST" />
<input type="hidden" name="data[Camera][camera]" label="Images:" value="CS011" id="CameraCamera" />
<label for="datepicker_value">Date: </label><input name="data[Camera][date]" type="text" id="datepicker_value" value="12/13/2011 12:00:00" />
<input type="hidden" name="data[Camera][count]" label="Images:" value="2" id="CameraCount" />
<input id="submit-490507801" type="submit" value="Load Pictures" />
</form>
</div>
<div id="ajaxPicture1" class="ajaxPicture"></div>
And the Javascript:
$(document).ready(function () {
$.ajax({data:$(".CameraContainer").closest("form").serialize(),
dataType:"html",
success:function (data, textStatus) {$("#ajaxPicture1").html(data);},
type:"post",
url:"\/cameras\/ajaxPicture"
});
return false;});
These are both iterated for n camera containers, each has a unique ajax div and CameraContainer div for the form. Currently the <script> is inside the loop but it would be better if I could load it at the end of the page.
This is taken from code generated by my framework so I don't understand it completely; what I want it to (and though it would) do is to grab the nearest from to the element with the id CameraContainer (the form is inside this element), serialize this data and submit it to my ajax function, which is at /cameras/ajaxPicture. However the array it sends to that function is empty, thus the function returns no results.
How can I grab and submit the nearest Ajax form to a given element (and load it in a container div)?

You should use
$("#CameraContainer").find("form").serialize()
CameraContainer is an id so # and not a .
You don't search an element which is close to CameraContainer, you search an element which is in CameraContainer so use find function
Look at my example

Related

Submit form with Javascript then handle with PHP

Not sure how I did this last time or else I wouldnt asking here but here is what I'm trying to do.
I have the usual basic form with a javascript function that will submit the form. Question is that after the form is submitted, I have an if statement in PHP that echos a that the form has been submitted. Any help would be greatly appreciated.
//PHP
if($_POST['submitDelete']){
echo "welcome, You form has been submitted";
}
//HTML
<form id="form_id" action="" method="POST">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
<input type="hidden" name="submitDelete" TYPE="submit">
</form>
<button type="button" onclick="myFunction()">Submit</button>
//JAVASCRIPT
<script>
function myFunction() {
document.getElementById("form_id").submit();
}
</script>
I can't seem to trigger the if statement in PHP. I also tried using the form name in the if statement and that didnt work either.
A form element must be told where to submit its data to when the submit event takes place. This is accomplished by setting the action attribute value for the form. Leaving that attribute empty does not implicitly set the form to post back to the current page. So, if you want to have a single page form/form processor, you need the action to be set to the current page file name:
<form action="currentPageFileName.php" method="post">
Next, there's no reason a single page can't have multiple forms on it. In that case you would need multiple submit buttons, each tied to a specific form. For this reason, you can't just drop a submit button anywhere on the page that you like unless you add the form attribute to the button to tie it back to the form it is supposed to trigger the submit for. Also, if you simply place the submit button within the form element it "belongs" to, you don't have to worry about this.
Also, you have some invalid HTML with:
<input type="hidden" name="submitDelete" TYPE="submit">
An element may not have the same attribute repeated within it (the case that you type the attribute in makes no difference since HTML is not case-sensitive). So, that code would wind up simply creating a submit button.
Lastly, if all you want to do with your submit button is cause its related form to be submitted, there is no need for JavaScript at all. That is what submit buttons do by default.
So, in the end, you can get rid of the JavaScript in your code completely and change your HTML to this:
<form id="form_id" action="currentFileName.php" method="POST">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
<input type="hidden" name="submitDelete" value="true">
</form>
<button type="submit" form="form_id">Submit</button>

Jquery / Ajax - How to determine which form to .serialize if all forms have same class?

On my mainPage.html, I dynamically created multiple forms each with different values in their input tag.. this is my mainPage.html:
<form class='voteForm' method="post" action="/post/likePost/">
<button class="voteButton" type="submit">
</button>
<input type="hidden" name="postID" value="1" />
</form>
<form class='voteForm' method="post" action="/post/likePost/">
<button class="voteButton" type="submit">
</button>
<input type="hidden" name="postID" value="2" />
</form>
<form class='voteForm' method="post" action="/post/likePost/">
<button class="voteButton" type="submit">
</button>
<input type="hidden" name="postID" value="3" />
</form>
As you can see, all three forms are similar, just their value is different. Now, this is my JS function
<script type='text/javascript'>
$('.voteForm').click( function() {
event.preventDefault();
alert($('.voteForm').serialize());
});
</script>
The problem is, whenever I click on any of the forms, it keeps automatically assuming that the form clicked is the last form which has a value of '3' in input, so it keeps altering the number 3 regardless of which form I click. I'm assuming this is because I did
$('.voteForm').click
and all three forms have the same class so it automatically takes the last form and runs the function. How do I make it so that it takes the form who's button I clicked and alerts the input-value of the clicked form WITHOUT changing the class or adding an ID to the form? Is there a way? I need all the forms to be the same (except for their input-value's).
Your click event handler is given a reference to the button that was clicked as the this context for the callback function. Use that to select the correct form:
$('.voteForm').click( function() {
event.preventDefault();
alert($(this).closest('form').serialize());
});
Better yet, rearchitect your markup so you have a single form, or no form at all, and just use the value of the thing which is being clicked. Using three forms for this which all submit to the same URL is a little odd.

Submit a form with Ajax

I'm making a user script for a site, and my goal is to submit a form on a page that I haven't opened. If I remove all unneeded bits from the page with the form that I want to submit, this is what is left (censoring the links):
<form action="http://foo.com/supply/" method="POST" name="supplyContractForm">
<input type="hidden" name="supplyContractData[selected][]" value="2244068">
<input type="type" name="supplyContractData[party_quantity][2244068]" value="123">
<input type="text" value="0" name="supplyContractData[quality_constraint_min][2244068]">
<input type="submit" name="applyChanges">
</form>
It's all about the third line: with the 'value="123"'.
I want to change that value to "222".
What do I do: I change the input value from "123" to "222", I press the submit button, and the form submits: the page reloads, and the value shown is "222".
Exactly as I want.
Now, this was all manual, and I want it scripted.
This works:
$("input:submit").click();
However, this doesn't work:
$("form").submit();
And this doesn't work either:
$.post($("form").attr("action"), $("form").serialize())
How can I post this form using Ajax, in a way I can change the value from http://foo.com/main/?
Note: I can only do things client-side, I'm just making a user script, and I can't see the server-side code.
This would do the trick
Html, notice the addedd class for cleaner js:
<form action="http://foo.com/supply/" method="POST" name="supplyContractForm">
<input type="hidden" name="supplyContractData[selected][]" value="2244068">
<input class="changer" type="type" name="supplyContractData[party_quantity][2244068]" value="123">
<input type="text" value="0" name="supplyContractData[quality_constraint_min][2244068]">
<input type="submit" name="applyChanges">
</form>
Js:
$('form input.changer').val('222');
$('input:submit').click();
The reason why $('form').submit() might not work would be because $('form') matches multiple element, ie do you have multiple forms in your html? if so make the selector more unique, via either adding ids or classes so your selected becomes:
$('#formid').submit();
Ajax
This doesn't use ajax though, for that you would need:
var form = $('form');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(){
alert('Form posted via ajax!');
}
});

Input field with onchange fails to trigger when user click button in another form

I have a page with multiple small forms on it. Each form has one input field that has an onchange function which will submit it's form to a url that returns a no data status.
Things work fine, submitting form after form, until the user clicks on a small form that has ONLY a submit button in it. This click works, but abandons the change in the previous field resulting in its onchange not firing the click at the bottom of the changed function fails (still trying to understand the firebug trace).
What's going on? is there a fix for my structure?
UPDATE:
First I tried simply delaying the action of the submit, but no luck.
I have hidden the and added an <input button> to the chain of "events" so that the focus has a place to come to rest before the real submit tries to happen -- the code below has been updated. So the question now becomes:
Is this as simple as it can be?
Script:
$(function() {
$('input,select').change(changed);
});
function changed(){
...
$(this).parents('form').find(':submit').click();
}
function doSubmit(elt, id)
{
$(elt).focus();
setTimeout(function(){
$(id).click();
}, 400);
}
One of may small forms:
<form class="clean" method="POST" action="QuoteProApp.php">
<input type="submit" value="field" name="btn_update" style="display: none;">
<input type="hidden" value="000242" name="quote_id">
<input type="text" maxlength="15" size="3" value="" name="q[cost][4][1][unit]">
</form>
The offending click goes into this form:
<form class="clean" method="POST" action="QuoteProApp.php">
<input type="hidden" value="000242" name="quote_id">
<input type='button' name='btn_close' value='Close' onclick='doSubmit(this,"#CLOSE");'>
<input id='CLOSE' type='submit' name='btn_close' value='Close' style='display:none;'>
</form>
Might be totally irrelevant, but your selector for the change event includes your submit input too. Can you change it to:
$('input[type="text"],select').change(changed);
to see if anything changes?
The solution turned out to be to create a button tag, set the focus explicitly to a it, and then set a timeout to click the real, but hidden, submit input tag. This allows the change in focus to run the submit associated with it and then continue with the explicit submit of the page.
The question has been updated to show this solution.

Posting an array of checkboxes from an onclick button event prototype or jQuery

I have a table of rows containing data and a checkbox to the very left. Here is the HTML for one of my rows
(the checkbox):
<input type="checkbox" id="records[]" name="records[]" value="1" />
As you can see, the row has a checkbox with a name of "records[]", indicating it is an array of values within the records array. Just above my HTML table, I have a button that when pushed, will take the checked records and post it to a new URL. I cannot figure out how to accomplish this. Just an FYI, the table and the buttons are not within a form.
I'm assuming that your HTML looks something like what is posted below, where your inputs are within the form, but the table and your buttons are not.
One trick to handling this situation is to bind an onclick event handler to your button element that then invokes the click method of a hidden submit button in the form itself. This effectively "chains" your buttons together.
<form action="/yourURL" name="yourForm" method="post">
<input type="checkbox" id="records[]" name="records[]" value="1" />
<input type="submit" style="display:none" id="submitBtn" />
</form>
<table>
<button id="yourButton" value="click me" />
</table>
$('#yourButton').click(function() {
$('#submitBtn').click();
}
Another method is to just call the submit method of the form object itself:
$('#yourButton').click(function() {
$('[name="yourForm"]').submit();
}
jQuery('#tableId input[type="checkbox"]')
a little bit of jquery. This will select all chekbox items from table. You can check with .val() method is it cheked.

Categories

Resources