Process form data using jQuery - javascript

I'm currently using Prototype, but I'd like to rewrite this function to jQuery:
function post(div,url,formId) {
new Ajax.Updater(div, url, {
asynchronous:true,
parameters:Form.serialize(formId)
});
}
HTML example that goes with it:
<form method="post" action="" id="foo"
onsubmit="post('result','getdata.php','foo');return false;">
<input type="text" name="data" />
</form>
<div id="result">&lt/div>
I've been looking at jQuery.load() and jQuery.post(), but I'm not sure which one to use and how exactly.
Thanks in advance for your help.

With this HTML:
<form method="post" action="getdata.php" id="foo">
<input type="text" name="data" />
</form>
<div id="result"></div>
You can do this with jQuery:
$(function() { // wait for the DOM to be ready
$('#foo').submit(function() { // bind function to submit event of form
$.ajax({
type: $(this).attr('method'), // get type of request from 'method'
url: $(this).attr('action'), // get url of request from 'action'
data: $(this).serialize(), // serialize the form's data
success: function(responseText) {
// if everything goes well, update the div with the response
$('#result').html(responseText);
}
});
return false; // important: prevent the form from submitting
});
});
The reason I got rid of the onsubmit code is because it is considered bad practice to have inline JavaScript like that. You should strive to make your forms free of JavaScript and then bind all the JavaScript away from it. This is known as unobtrusive JavaScript and it is a Good Thing.
EDIT:
Since you have that code in many pages, this is a function that will do what you want using the same signature you currently have on the post function. I recommend you take a few hours to update all your forms over keeping this, but here it is anyways:
function post(div,url,formId) {
$.post(url, $('#' + formId).serialize(), function(d) {
$('#' + div).html(d);
});
}
As far as your problem, the livequery plugin could help you there. Alternatively, it is as simple as encapsulating the binding code in a function and calling it whenever a form is added.

Use this and get rid of the onsubmit attribute in your HTML:
$(document).ready(function() {
$("#foo").submit(function() {
$.post($(this).attr("action"), $(this).serialize());
return false; // prevent actual browser submit
});
});
jQuery serialize method docs

You can't send "multipart/form-data" forms with jquery because of security problems. You must do it with flash or iframe...

Related

How to convert a GET request to POST

I don't know if it is possible or not. I referred some site, but I didn't get exact answer.
I am using
click
When I send this request to server in the response page easily I can see "id=4" in address bar, obviously which is not secure, But in post request we cant see this.
So can we convert a get request to post or ant other way is there to hide this from address bar.
Thanks in advance.
Firstly, to convert GET to POST, simply change the link to a form:
<form id="myForm" action="xyz" method="post">
<input type"hidden" name="id" value="4"/>
</form>
This form will not be visible and you can easily auto-submit it using JavaScript in your link:
click
Secondly and more importantly, both GET and POST are equally not secure over HTTP. To secure them, use HTTPS and they will be both equally secure, so no need to change if GET is working for you.
click
Dynamically create a from and post it.
function postForm() {
var form = $('<form method="POST" action="xyz"></form>');
$(document.body).append(form);
form.append('<input type="hidden" name="id" value="4"/>');
form.submit();
}
As Racil suggested in comments, you can also do the following
click
and then
$('#postLink').click(function(e){
e.preventDefault();
//create form and post
});
Call a java script function on onclick which will make the form submission using post method or you can use ajax call to post the data and get your desired results.Use id as a parameter in function.
<a href="#" onclick="postData(4)">
/// Javascript function for ajax call
function postData(id){
var param = { "Id": id};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "xyz.aspx",
data: JSON.stringify(param),
success: function (data) {
/// Recive data here or do your stuff here
}
}
Make a form having single input type hidden and onclick set value of that input type hidden element and submit form using jquery.
<form id="target" action="destination.html">
<input type="hidden" id="hiddenValue">
</form>
/// Javascript function for setting value of hidden element and form submission using jquery
function postData(id){
$("#hiddenValue").val(id);
$("#target").submit();
}
Hopefully this will solve your problem.

Updating a DIV on Submit without page refresh

I need refresh <myDiv> on my webpage when the Submit button is clicked.
I created an example of what I need. I want to display the user input text inside <myDiv> when the Submit button is clicked. Currently it's not showing anything. How can I fix this?
http://jsfiddle.net/NathaliaZeed/8dn5j/2/
Thanks everybody.
You need to use complete: not done:, then, assign your val1 variable to myDiv.
Working fiddle: http://jsfiddle.net/8dn5j/14/
See below:
$('#btn').click(function(e) {
var val1 = $('#val1').val();
e.preventDefault();
$.ajax({
type: 'post',
data: {'val1':val1},
complete: function(jqXHR, textStatus){
$("#myDiv").html(val1);
}
});
});
The code in your example is good, except you forget to load the jQuery library.
If you make sure you include jQuery, the javascript code should work.
Also, your example should run on a PHP server. JSfiddle does not interpret PHP code, so that is also why the example does not work.
If you don't have a PHP server, Google for WAMP for Windows or MAMP for Mac.
Not Sure why you need php and ajax if there is only need to update the div on button click and not doing any server side processing for the need you described in question this code will work
<div class="myDiv" id="myDiv"></div>
<div class="sear">
<form action="" method="post">
Search Word: <br />
<input type="text" name="val1" id="val1" /><br />
<input type="button" value="Submit" id="btn" />
</form>
</div>
Js
$('#btn').click(function(e) {
var val1 = $('#val1').val();
$("#myDiv").html(val1);
$("#myDiv").toggle("slow");
});
By the way, you don't need to use the form-tag..
I would do it this way:
$('#btn').click(function(e) {
var val1 = $('#val1').val();
$.ajax({
type: 'post',
data: {val1:val1},
success: function(data) {
$("#myDiv").text(data);
}
});
});
For me it doesn't do anything with Ajax request.
$('#btn').click(function(e) { e.preventDefault();
$("#myDiv").html($('#val1').val());
//..ajax stuff..
});

Form submition using AJAX is not working

Im tring to submit form to other page using ajax, but it doesn't send the post.
Javascript on top of page.
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function(){
$(".button").click(function(){
event.preventDefault();
var name = $("#name").val();
var dataVar = "name=" + name;
$.ajax({
type: "POST",
url: "https://www.example.ee/index.php?e=area_sa&date=2010",
data: dataVar,
success: function() {
alert("works");
}
});
});
});
<script>
And HTML code:
<form>
<input type="text" name="name" id="name">
<input type="submit" name="submit" class="button" value="Add">
</form>
It's not working because you're trying to make a cross-domain AJAX request.
If you have a domain mywebsite.com, then all AJAX requests should be limited to this domain, e.g. mywebsite.com/example/ajax/request.
What you're trying to do (cross-domain request) is possible but involves a workaround that's a bit more complicated, and makes use of different library calls.
It seem that your click event is not bind to the .button,
That happen when the event is bind before the html element is loaded
few solutions :
1) encapsulate your JavaScript code inside an on-load event
2) place your JavaScript at the bottom of the page
3) use $(body).on('click', '.button' , function(){ /* your code here */})
also look like you posting to an external domain,
if you are the owner make sure you add the CORS policies.

Accepting an image in script

How would I edit this so it accepts the image when put in form all other options work just the image not uploading to server or database.
Please could someone help I have looked around and can't find anything that I understand,could someone possibly add a bit of code to this?
Thanks in advance.
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#Submit").click(function() {
var url = "../AdsCreate/CreateCar.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#myForm").serialize(), // serializes the form's elements.
success: function(html){ $("#right").html(html); }
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
That's because <input type="file" gets skipped when performing the .serialize() on the form.
It's possible to upload files with JavaScript, but far easier to just do it within the form:
<form action="../AdsCrease/CreateCar.php" method="post" enctype="multipart/form-data">
...
<input type="file" name="myfile" ... />
...
<button type="submit">Submit</button>
</form>
jQuery documentation on .serialize clearly states that file upload is not supported (and indeed you need a multipart/form-data POST submission for uploads, it's not just a query string).
Right before the "example" sections you can find:
Data from file select elements is not serialized.

Jquery .load and POST data

This is really frustrating I would appreciate some help with this. I have a div, called comments and a form inside of that div. What I want to do is post a form to the current page and have it load inside of the div without reloading the entire thing. Here is my current code:
<div id="comments">
<form action="#" method="post" onsubmit="return false;" >
<input type="hidden" name="txtname" value="test">
<textarea id="wysiwyg" name="wysiwyg" rows="5" cols="50"></textarea>
<input type="submit" name="post" id="post" value="Submit">
</form>
<script type="text/javascript">
EDIT: Read edit below for current code
</script>
</div>
When I submit, the alert fires, but the page does not load. It works fine if I make the event as follows:
$("#comments").load("comments.asp");
It's not liking the posting of data. I have used .load before but never to post data. I got the above code from these very same forums.
I'm honestly not sure of the purpose of 'name' and 'tel' - do I refer to those variables or the form variable names when processing the code? This is in ASP classic.
What's wrong with the above code, how can I get it to send data from the forum via POST? Thanks!
EDIT:
I am now using the following code:
$("#post").submit(function(event){
var $form = $(this),
$inputs = $form.find("input, select, button, textarea"),
serializedData = $form.serialize();
$inputs.attr("disabled", "disabled");
$.ajax({
url: "/comments.asp",
type: "post",
data: serializedData,
success: function(response, textStatus, jqXHR){
console.log("comment posted");
},
error: function(jqXHR, textStatus, errorThrown){
console.log(
textStatus, errorThrown
);
},
complete: function(){
// enable the inputs
$inputs.removeAttr("disabled");
}
});
event.preventDefault();
});
And now it's using properly getting the form handled...however it goes to comments.asp. How can I make all the action happen in a certain div (comments div?)
It seems to me you are blending a bunch of different techniques in a way that is not entirely coherent.
$.post is a shortened version of $.ajax (see here).
$.load takes a url and sticks it into a <div> or other DOM Element (see here).
If I understand it correctly (and I may not!), you're not really wanting to load the form, but put values into the form fields. $.load is an odd way to do this. (It may work, but I do it another way.)
If you're using $(#...).submit, you can also leave out a whole bunch of stuff in your form. The following should work fine.
<form id="form_id">
...
<input type="submit" value="Submit">
</form>
My method is: (1) have a hardcoded HTML form (or build it by AJAX), (2) get the values from the DB (or wherever) using $.post (or $.ajax), (3) stick the values into the form using .val() (or equivalent - whatever is right for the input type) and the DOM id of that input, and then (4) use .submit (in a manner similar to yours). You will need to add preventDefault as the others have suggested.
You're also muddying the waters using #post as the DOM id. You really want to give the form itself the ID, and then use $(#form_id).submit(... I can't test it now, but having the submit on the input field may cause some grief. The official example attaches the .submit to the form id.
I'm also not sure the <div> with id 'comments' really does much. I have a container id like your 'comments', but that's because I build forms by AJAX and stick them into the container. If you don't need to do that, the id 'comments' is unnecessary to the whole procedure.
Your text box element dont have an id with value txtname. But in your script you are trying to access using # (which is supposed be with an id context). So add an id element to your input box.
<input type="hidden" name="txtname" id="txtname" value="test">
And as expascarello said, You need to stop the default behaviour of the submit button . Other wise it will do the normal form posting so you wont be able to feel the ajax effect.
Use preventDefault
$(function(){
$("#post").click(function(e) {
e.preventDefault()
alert("clicked");
$("#comments").load("comments.asp", {
'name': $("#wysiwyg").val(),
'tel': $("#txtname").val()
});
});
});
You are not cancelling the clicking of the button so the form is submitting and resetting the page.
$("#post").click(function(evt) {
evt.preventDefault();
...
jQuery event.preventDefault()
The load() method does a get and not a post.

Categories

Resources