I have this form that i am trying to submit with ajax as well as the regular submit the regular submit is for creating a pdf and the ajax submit is for showing an html example for showing the preview which both work just fine if i use them both individually or use the create pdf before the preview submit but if sumbit for pdf after the preview submit it's not functional, nothing happens like regular submit button is disabled. My code is attached as folows, Do note both work fine just the regular post doesn't work if i use ajax submit first.
<script type="text/javascript">
$('#submitpdf').submit(function() {
return true;
});
$('#submitpreview').click(function() {
$('#form').submit(function(event) { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('GET'), // GET or POST
url: 'test.php', // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
return false;
});
});
</script>
and here is the HTMl of the form tag and the submit buttons:
<form action="dopdf.php" name="formular" id="form" method="GET" enctype="multipart/form-data">
<input type="submit" id="submitpdf" value="Create PDF" name="print" class="btn btn-primary submit-button" onclick="javascript:document.getElementById('act').value='0'" style="margin-left: 0;" />
<input id="submitpreview" type="submit" value="Preview!" name="preview" class="btn btn-primary submit-button" onclick="javascript:document.getElementById('act').value='0'" style="margin-left: 0;" />
</form>
One other thing to note is that with ajax i want to submit to "test.php" and with regular submit i want to submit to "dopdf.php".
The code for submitPreview button click does not look correct to me ( on the click handler, you are basically registering the submit event code!). Try changing to this clean version. Also, make sure to wrap your event handler code inside the document.ready event to avoid other issues.
Also you need to read the method attribute of the form, not GET attribute.
$(function(){
$('#submitpreview').click(function(e) {
e.preventDefault(); // prevent the default form submit behaviour
var _this=$(this).closest("form");
$.ajax({ // create an AJAX call...
data:_this.serialize(), // get the form data
type: _this.attr('method'), // GET or POST
url: 'test.php', // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
});
});
Since your form action value is set to dopdf.php, when user clicks that button, It will be submitted to dopdf.php. You do not need any additional jQuery click handler for that.
you could do the following
your script like this
$('#form').submit(function() {
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('GET'), // GET or POST
url: 'test.php', // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
});
and the form as it is. don't change it
Related
I have this code bellow and I need it to make a post inside a div.
<script type="text/javascript">
$(function() {
$(".loader").click(function(event) {
event.preventDefault(); // stop the link loading the URL in href
$('#content').load($(this).attr('href'));
});
});
</script>
<form method="post">
some random inputs and checkbox's goes here
<input type="submit" href="/consulta/consulta_produto.php" class="loader" value="Consultar">
</form>
When submiting, the javascript is sucessfully loading the consulta_produto.php inside a div called "content", however, I need to adapt the script to make it possible to POST too
Someone at other topic said to Use $(".loader").parent("form").submit instead of $(".loader").click, however i didnt understood what he meant, I tried changing it in a lot of different ways, but none of them worked
I researched a few topics about how to post with javascript, but I could adapt none of them to keep the function to load consulta_produto.php inside the div "content"
So I wonder, how can I adapt my javascript to keep loading consulta_produto.php inside content div while posting the data from some inputs and check boxs?
First of all, you need to either:
Place all of your <script> code after the relevant HTML has been loaded, OR
Wrap it all in a $(document).ready(function() {...}); to achieve the same effect
Then, instead of executing code at your inputs click() event, you can do it upon your forms submit() event. (This is basically what you mentioned someone told you in another topic). I changed your submit input to a submit button, doesn't really matter.
So, instead of loading the href attribute, you load the action attribute of the form itself into the div.
Of course you want to submit actual data along with the form - no problem. You just use an AJAX method. This is in order to stop the page from reloading.
First you do the preventDefault() to stop the usual page reload. Then you initialize the $.ajax() method.
Data: The first parameter 'data' contains all the form data to pass
along.
Type: Represents the type of request (POST)
URL: This is the form action (/consulta/consulta_produto.php).
Success: Finally, the 'success' parameter contains a function
which loads it all into the specified <div>.
AJAX is essential when avoiding page reloads in PHP, play around with it!
<script type="text/javascript">
$(document).ready(function() {
$("#form").submit(function(event) {
event.preventDefault();
$.ajax({ //AJAX Method
data: $(this).serialize(), //Gets data from form
type: $(this).attr('method'), //Gets the method, in your case POST
url: $(this).attr('action'), //Gets the form action
success: function(r) {
$('#content').html(r); //Loads data into div
}
}); //End of AJAX Method
}); //End of form submit event
});
</script>
And here is your HTML:
<div id="content" style="width:100%; height:500px; ">
</div>
<form id="form" action="/consulta/consulta_produto.php" method="post">
some random inputs and checkbox's goes here
<button type="submit">Consultar<button>
</form>
I can't get the value from the form. Due to Firebug the form is submitted tho and when I delete the js it works so it has something to do with it.
$ok= $_POST['ok']; //this doesnt work
if($ok== "ok" ){
echo "works";
}
<script type="text/javascript">
$(document).ready(function() {
var frm = $('#form');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
});
ev.preventDefault();
});
});
function submitForm2() {
$('#form').submit();
}
</script>
<div onclick='submitForm2();'></div>
<form action='' method='post' id='form'>
<input type="hidden" name='ok' value="ok">
</form>
When the form is submitted, your first set of JavaScript kicks in. It:
Stops the normal submission process running
Takes the data from the form and submits it via Ajax
Since the normal form submission doesn't run, the page doesn't reload, so you don't load a new document, so you don't see the document with the ok in it loaded in the main browser window.
Since you don't have a success handler for the Ajax request, you completely ignore the response the server sends back to the JavaScript … so you don't see that document (with the ok in it) either.
If you want to see the results of an Ajax request, then you have to write JS to show you the results (or examine the Net tab of your developer tools).
I have several forms on a page that submit values from radio buttons using jquery/ajax. All works fine when a Submit button is used, but I would like to eliminate the Submit button. I tried using onClick to submit. However, trying it this way causes the forms to get submitted prior to the processing script picking them up. I would very much appreciate advice (and example if possible). Thank you, Brian
Script:
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
var formData = $(this).serialize();
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'process.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json' // what type of data do we expect back from the server
})
// using the done promise callback
.done(function(data) {
if (data.success) {
// success.
// hide form container
$("#"+data.message).hide();
$("#"+data.message+"hr").hide();
}
// log data to the console so we can see
//console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
Form:
<method="post" action="process.php" enctype="multipart/form-data">
<input type="radio" name="answer" value="yes" onClick="onClick="this.form.submit()">
Your syntax for onclick is wrong, but putting onclick attributes on elements is an outdated way of doing things in any case.
You probably want to handle the change event rather than click, since the selection of the radiobutton happens after the click, so if you submit the form right away the radiobutton might not be selected yet (I'm not sure, I'd have to experiment, but change is probably more foolproof).
$(document).ready(function() {
$('input[type=radio]').change(function(event) {
//the rest of your code goes here
//you don't need event.preventDefault() anymore
});
});
Edit: $(this) won't refer to the form anymore of course, just replacing it with $('form') should do the trick.
I am trying to submit form through Jquery in MVC. If I remove form element, submit works. what is wrong with my code?
<form id="Send" method="POST">
<fieldset>
<button type="button" id="test" />
</fieldset>
</form>
<script type="text/javascript">
var data = {........}
$(function () {
$("#test").click(function() {
$.ajax({
type: "POST",
url: "http://localhost:0000/api/test",
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
});
});
});
</script>
Your page, for some reason not shown in your code, is probably behaving like it would when any form is submitting (by GETting or POSTing to its action attribute). You can, however, prevent this behavior. First, I would do your work when the form itself submits, not in a button click event. This will require two changes. (1): Change your button back to type="submit":
<button type="submit" id="test" />
And (2): Handle the "submit" event of the form instead of the "click" event of the button:
$("#Send").submit(function(e) {
// here's where you stop the default submit action of the form
e.preventDefault();
// Now execute your AJAX
$.ajax({
type: "POST",
url: "http://localhost:0000/api/test",
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
}).done(function(response) {
// handle a successful response
}).fail(function(xhr, status, message) {
// handle a failure response
});
});
Advantages of this approach:
You correctly handle the submission process no matter how it was initiated (enter button, button click, programmatically, etc.
You don't have to care what your button is called
The logic would be bound to an event that you would expect it to be
You need to cancel the default form submission, otherwise the browser will do a POST request to the current url with the form data.
$('#Send').submit(function(e) {
e.preventDefault(); // prevents the default submission
$.ajax(/* ... */);
]);
Use serialize() on the form like:
var data = $("#Send").serialize();
Edit:
Or, if you're absolutely sure you have a server side script that would handle RAW POST you could turn your form data into object and stringify that instead, like:
var data = {
'input_1': $("#Send_input_1").value(),
'input_2': $("#Send_input_2").value(),
...
'input_N': $("#Send_input_N").value()
};
data = JSON.stringify(data);
If you dont want to remove the form tags change the button tag for an anchor with the looks of a button (css) and bind the click event:
<a id = "test" href = "#">test</a>
I got control with strongly typed View, with Ajax.BeginForm(). Now I would like to change submit method from
<input type="submit" id="testClick" value="Submit" />
To some javascript method DoSubmit().
What I tried is :
Invoke click on that submit button
Invoke submit on form ('form1').submit(), document.forms['form1'].submit()
jQuery forms with ('form1').AjaxSubmit();
Create jQuery AJAX
$.ajax({
type: "POST",
url: $("#form1").attr("action"),
data: $("#form1").serialize(),
success: function() {
alert("epic win!!!1!1!")
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("epic fail!")
}
});
All those method created normal request (not AJAX), or they didn't work. So anyone know how I can do AJAX submit "Form", from JavaScript and strongly typed mechanism (public AcrionResult MyFormAction(FormModel model); ) will work?
I've had this work fine for me using the forms plugin for jquery. What I found tho, was that I had to handle the click event, do the ajax submit and then return false to ensure that the normal post didn't occur.
<script type="text/javascript">
$('#testClick').click(function(){
$('#form1').ajaxSubmit();
return false;
});
</script>