Javascript to Post Inside a Div - javascript

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>

Related

Trouble with ajax script using onClick to submit form

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.

Sending dynamic POST data with Javascript

So basically, I'm trying to send some data to a remote PHP page, via POST, with 4 static parameters and one random parameter, a number.
So far what I have done is created an HTML page with a form with 4 hidden fields and 1 empty field, in which a random number is inserted as the value via Javascript (using Math.random). Now whenever I submit this form, it takes me to the remote PHP page, and so I have to click back again (in the browser) and then submit.
So, I decided to load this form in an iFrame in another HTML Page, so after clicking submit, I can just hit refresh, and then submit again.
I want to know, is there a way I can use Javascript in the parent HTML to automatically submit the form in the iFrame, then create a new random value and submit it again?
Here is my code so far
a.html
<html>
<body>
<form method="post" action="http://awebsite.com/remotefile.php">
*some hidden fields with the static values*
<input type="text" id="mytext" name="mobile_no">
<input type="submit">
</form>
<script>//don't remember the exact code, use javascript to generate a random number which is put in the value for mytext via getElementById</script>
</body>
</html>
now this was the form which was to manually send data to the server
this is to load an iframe:
b.html
<html>
<body>
<iframe src="a.html">
</body>
</html>
Can I use javascript in b.html to resend the form multiple times, but with the value of mobile_no different each time?
Or can I simply send POST data with the parameters to the server via simple Javascript (or PHP)
You question isn't 100% clear, but it sounds like you want to asynchronously post form data. You could easily do this with a JavaScript library like jQuery without the need for an iframe. First you should add an ID attribute to your form to make it easier to reference in your jQuery code. Then you can attach an event listener to the form's submit event where you can customize the form before submission and handle the response
$('#myForm').submit(function(e) {
// prevent default form submit action from occuring
e.preventDefault();
// load values need to make AJAX request
var method = $(this).attr('method');
var action = $(this).attr('action');
// Process Ajax request
$.ajax({
type: method,
url: action,
dataType: 'html',
data: $(this).serialize(),
beforeSend: function() {
// generate and assign per form submit random number
// show loading gif
},
success: function(response) {
// AJAX POST success, insert the HTML response into the DOM
},
error: function(jqXHR, textStatus, errorThrown) {
// console.log any errors for debugging here
},
complete: function() {
// Post completion tasks, such as hide loading gif
}
});
});

form within AJAX jQuery toggle, submits at parent onClick not from submit button

Basically mysimplewebform.php form submits when the toggle is clicked, as opposed to after the form is loaded, used by user and SUBMITTED via submit button at form. Obviously I need to have form operate functionally; user fills it out, and clicks submit. I simply used AJAX to bring in the form on the template page. Now everytime toggle button is clicked 'Form is submitted with empty values' and then appears in the toggle. Making it pretty useless at this point, I have been struggling with this forever. I think this is a matter of toggling the data: below --
$(document).ready(function() {
$('#toggle3').click(function(){
var tog = $('.toggle');
$.ajax({
type: 'POST',
url: '/mysimplewebform.php',
data: $(this).closest('form').serialize(), // This was a recent suggestion
success: function (fields){
tog.html(fields);
tog.slideToggle(1000);
}
});
});
});
Branched out from: How to send external form POST data through AJAX
Ok, so you want to display an html form when a user clicks a button? In that case you can use the simplified jquery load method:
$('#yourbutton').click(function(){
$('#somediv').load('/mysimplewebform.php');
});
I know this doesnt handle your toggle requirement, but i dont think that is where you are having issues.
Now onto the php. I dont know exactly what should be in mysimplewebform so heres an example
if(isset($_POST['fname'])){
//we have a post request, lets process it
echo 'hello'.$_POST['fname'];
}?>
<form action="absolute/path/to/mysimplewebform.php" method="post" id="mysimplewebform">
<input type="text" name="fname" placeholder="Enter Name">
<input type="submit" value="submit">
</form>
Notice the action is an absolute path to the file, because a relative path will be wrong if the form is loaded into another page via ajax.
Now when this form is submitted, the browser will be redirected to mysimplewebform.php.
I expect you want to stay on the same page, in which case you could submit the form via ajax:
$('#mysimplewebform').submit(function(ev){
ev.preventDefault();//stop normal redirecting submit
$.post( $(this).attr('action'), $(this).serialize(), function(data){
$('#somediv').html(data)
});
This replaces the whole form in the dom with the output, so the hello message would be displayed.
All of the above is an attempt to help you understand where you have been going wrong in your attempts. It is not the best solution to your overall problem - i would separate the html form and processing into seperate files for a start, but it should be familiar to you.

Getting some problem with apply event to dynamic added form in Jquery

I am loading the form in dialog box via jQuery
The code is like
<form class ="form1" action="" method="post" enctype="multipart/form-data" >
...
</form>
I am using jQuery form plugin to submit form like this
$(".form1").live('submit', function(e) {
var options = {
target: '.ajaxMessage',
beforeSubmit: showRequest,
success: showResponse,
type: 'POST'
};
alert('test');
$(this).ajaxSubmit(options);
return false;
});
Now
If i load the form directly without AJAX and then i submit the form then form gets submiited successfuly without any problem. It works 10 out of 10 times
In second case I load the form dynamically. When i click on form link then i load the form dynamically in a jquery dialog box then if i click on submit form then i can see the alert but form is not submitted. But it works sometimes but sometimes not. I would say it work 2 times out of 10.
Firebug console is also not showing any error
Is there any way i can find whats problem
Firebug will usually (I actually think not at all) won't show any errors for a ajax call, instead the error will be in the ajax request(still in firebug). Click the request and then response.
My guess is that there is a problem with the params you are sending or there is something wrong with what you a returning(i.e. you return html when ajax is expecting json, this will cause success never to be fired)
Also, try to pass an error:function(jqXHR, textStatus, errorThrown){} to the ` ajaxSubmit params and see what happens.

How to post form using jQuery?

I have a form with a submit button and it works fine, but I now have a user request to make the form get saved (posted to save action) if a link on the page is clicked and the form is "dirty".
I've got the logic in place by having an isDirty JavaScript variable, now I would like to post the form from the JavaScript function when it is dirty.
My form declaration is as follows:
<form id="formSmart" action="<%= ResolveUrl("~/SmartForm/Proceed") %>"
method="post" enctype="multipart/form-data">
and my JavaScript is:
function checkLink() {
if (isDirty) {
$("#formSmart").submit();
}
}
The proceed action doesn't get called, yet when I click the submit button on the form it works fine. What am I doing wrong in the JavaScript?
Note: The call to checkLink() works fine, the ultimate problem is that $("#formSmart").submit(); is not posting to the Proceed action.
You have the correct way of submitting the form based on what you have posted and the names match up.
Are you sure you are calling checkLink and is isDirty equal to true?
Put and alert('Test'); right before you submit and in the if scope.
EDIT: To hookup your event you need to do the following:
$('#yourLinkID').click(checkLink(); return false;);
Note the return false which will cause your link to not execute a navigate. If you want the link to navigate, you can just remove that part.
Sounds like the requirement is that 'a link on the page is clicked'.
Perhaps attach this event to all the <a> tags on the page.
$(document).ready(function() {
// all <a> tags get the checkLink attached to them
$("a").click(checkLink());
});
your problem is that the browser navigate before the page performs your submit.
the solution is suspending the navigation till you save the form.
The UGLY solution:
you could do it buy saving the clicked url at a hidden field,
returning false to stop the navigation,
and after submit check for a value there and if it exists do navigation
A better solution:
post the form via ajax and after the ajax call completes(no need to check for success or error) perform the navigation(to make it really easy just use ajaxForm ajaxForm plugin)
the only problem with this solution is if the link has target="_blank" because then you have to use window.open which might be blocked by popup blockers
you can play with a simple jsbin sample i prepared showing this
this example post some values to an older version of this page + navigate to google, open fiddler and see that it first post and then navigate.
If you went to the jsbin page stop reading here
here is the Html:
<form id="formSmart" action="http://jsbin.com/oletu4/edit" method="post">
<input type="text" name="someLie" />
<input type="text" name="someLie2" />
<input type="submit" value="submit" />
<a id="lnkNavOut" href="http://www.google.com">www.google.com</a>
here is the JS:
$(document).ready(function(){
$("#lnkNavOut").click(function(){
var jqFormSmart = $("#formSmart");
//check here if the form is dirty and needs to be saved
var jqClickedLink = $(this);
$.ajax({
url: jqFormSmart.attr("action"),
type: "POST",
data:jqFormSmart.serialize(),
complete:function(){
location = jqClickedLink.attr("href");
}
});
return false;//stop navigation
});
});​

Categories