Cannot get .js to be called upon form POST - javascript

I have a bit of code that's "working," but is not doing what I want it to do.
On my page, I have a bit of code in the header:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="update.js"></script>
and inside my main page, I have:
<form id="updateChanges" method="POST" action="update.php">
...code...
</form>
When I click the button inside of this form, I want the code inside of update.js to execute, but the page redirects to update.php and executes my code successfully instead. I am trying to bypass this redirect, and execute the code without doing a page refresh. I do not understand why it's not working.
I got the .js from a tutorial on how to use AJAX.
$(function() {
// Get the form.
var form = $('#updateChanges');
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
});
});
my javascript file is not being called. Why?

You've already defined jQuery form object in the form variable, you do not need to wrap it for jQuery again.
All instances of $(form) become: form
$(function() {
// Get the form.
var form = $('#updateChanges');
// Set up an event listener for the contact form.
form.submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData = form.serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: form.attr('action'),
data: formData
});
});
});

Related

Two submits one ajax one regular form

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

Can't get values from 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).

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.

submit JSON through form submit via jquery

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>

any way to stay in the same location when refreshed

i am working on jquery and javascript. and is there any way to make the page refresh and to restore the same link which is clicked. for example. in gmail.com when we open sent items which is in the lefthand side of the window and refresh the page. it get reloaded with the same sent items tab's contents, same things work for inbox and drafts when refreshed. is there anyother method or example to acheive this. if yes. please help. it would be appreciated.
here is my code to make the page refresh on refresh:
<script>
$(window).load(function(){
$(function()
{
$('#submit').click(function()
{
$('.container').show();
$('#login').hide();
$.cookie('shown', true);
});
if ($.cookie('shown')) {
$('#submit').click()
}
});
});
</script>
Here is a sample ajax form submit script.
// this is the id of the submit button
$("#submit").click(function() {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
Presuming that you're using Ajax to change your page states, why not look at something like History.js?

Categories