Submit a form with Ajax - javascript

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!');
}
});

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>

Different Values in Form Inputs

I have a simple HTML form that works with a PHP script (to process the values).
For some reason it's not working correctly. After many tests, I inspect the mark-up for the form and I find:
<form id="delete_item_3_form" action="upload/delete_item.php" method="post">
<input type="hidden" value="4" name="item_id">
<input type="hidden" value="test" name="item_info">
</form>
As it should be. Please note that the values for the inputs are hard-coded.
However, if I go to the browser console (I am using Chrome) and write:
$('#delete_item_3_form');
I get:
<form id="delete_item_3_form" action="upload/delete_item.php" method="post">
<input type="hidden" value="4" name="item_id">
<input type="hidden" value name="item_info">
</form>
As you can see the value from the second input, item_info, is empty. Both inputs have a name.
I am not new to Form Handling but I have never seen this. The page mark-up shows one thing in a form, and a simple jQuery call to the same form shows another thing.
I have nothing, on my scripts, changing the value of the inputs.
The form is submitted by the press of a button. Here is the jQuery code:
$('#delete_item').click(function()
{
$("#delete_item_3_form").submit();
});
How is this happening?
I had another form in the page with the same ID.

How to remove/enhance/change the form submit data using standard submit event and jquery, before the actual submit happens?

Is it possible to extract data from a form, say:
<form action="/search/search" data-remote="true" data-type="json" id="search_form" method="get">
<div class="input-group">
<span class="input-group-addon">
<input name="search[req][text][e]" type="hidden" value="false">
<input id="search_req_text_e" name="search[req][text][e]" type="checkbox" value="true">
</span>
<input id="search_req_text_v" name="search[req][text][v]" type="text" value="">
</div>
<button id="fire_search" type="submit">Search</button>
</form>
I thought about jQuery's .submit() method. But how to extract and change the url from the event?
$('#search_flickr_panel_body form').submit(function(e) {
console.log(e)
}
I don't see in Chrome DevTools any url in the printed event object
I would like to remove the text fields which are unchecked.
Maybe .attr('disabled', 'true') would be a variant for remove, but how to change the data, without change it in the text field, only in submit url?
Update:
I have over 100 such input fields in the form, so to just send all of them even if only one is checked is not so nice (too much useless data making the communication overhead)
Update2:
I want not only be able to remove the unchecked data from the submit data, but also be able to change this data before submit(e.g. add a prefix to the values, add new parameters), so that I can effect the resulted url (with data).
This will disable all the text fields that have associated checkboxes unticked...
$(function() {
$('#search_form').submit(function(e) {
e.preventDefault();
$(".input-group").each(function() {
$(this).find("input:text").prop("disabled", !$(this).find("input:checkbox")[0].checked);
});
this.submit();
$(".input-group input:text").prop("disabled", false);
}
});
The disabled ones should not be submitted with the rest of the form.

Submit a form with an additional POST var (NO AJAX)

Is possible to submit a from (synchronous normal classic way, no AJAX) with an additional POST var?
Using AJAX is easy:
$("#cpa").submit(function(e) {
e.preventDefault();
newvalues = { name: "John", time: "2pm" };
$.post(theurl, newvalues);
});
But i like to know if can SUBMIT (so the page reloads or goes to theurl) the form with additional data.
EDIT: Since there is a confusion on the comments, ill like to share more code:
http://jsfiddle.net/4zc4d/
Each time you click save the content of the alert is what i want to add to the form vars.
Use
<input type="hidden" name="country" value="Norway">
as seen in w3schools to submit fields that the user shall not see.
Beware: If the user cares to check sourcecode or traffic, he can find out the values.
EDIT:
About the additional fields in the jsfiddle: Did you realise you can send arrays directly?
<input type="hidden" name="id[]" value="1">
<input type="hidden" name="id[]" value="2">
<input type="hidden" name="id[]" value="3">
will result in
$_POST['id'] = array(1,2,3)
No need to concat values.
You can also add the hidden input via jQuery if you want to:
$("#cpa").submit(function(e) {
$(this).append('<input type="hidden" name="theName" value="some value" />');
});
As someone mentioned, add a hidden field to your form HTML
<input type="hidden" id="hidValue" />
Set the value required.
$("#hidValue").val("Anyvalue");

Submit ajax form on load

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

Categories

Resources