Display response to a GET & POST request in a textbox - javascript

I'm trying to get the response of a GET request inside a textfield on my webpage using jquery. Currently, I have the following code with which I can get the response on the console.
$(document).on('click', '#get-button', function(e) {
e.preventDefault();
$.ajax({
type: "GET",
url: $("#url").val(),
data: '',
success: function(response, textStatus, XMLHttpRequest) {
console.log(response);
}
});
return false;
});
$(document).on('click', '#post-button', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $("#url").val(),
data: $("#json-data").serialize(),
success: function(response, textStatus, XMLHttpRequest) {
console.log(response);
}
});
return false;
});
Below is a part of the HTML code where I want to fit the response(in JSON) format.
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="panel panel-danger">
<div class="panel-heading">JSON Response</div>
<div class="panel-body text-danger">
<textarea class="form-control" rows="8" placeholder="server response"></textarea>
</div>
</div>
</div>
</div>

Place your code in ready function, or add deffer to your script definition. In that way your script will execute after DOM is loaded.
Don't add events on docuemnt like this, it is too big. You are using id's, thats nice, so use it:) It depends on your DOM size, butin most cases find a element by id and then add event to it.
Add an id to your textbox, that will be more usable and faster.
.
$(document).ready(function(){
$('#get-button').on('click', function(e) {
e.preventDefault();
$.ajax({
type: "GET",
url: $("#url").val(),
success: function(response) {
console.log(response);
$('.form-control').val(response); // personally I would give your textbox an ID
}
});
return false;
});
$('#post-button').on('click', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $("#url").val(),
data: $("#json-data").serialize(),
success: function(response) {
console.log(response);
$('.form-control').val(response);
}
});
return false;
});
})
If your URL are correct, this will work.
Just remember that after you get the response, and you will get a JSON object, you will have to convert it to String using JSON.stringify().
I will try to explain. In Javascript we have Objects and simple types (boolean, String, float, etc). When we want to print a simple type, we just see it's value. But when we want to display a Object, JS engine has a problem, because each object can be very big, complex. Thats why when printing an object or JSON (witch is an Object) we get [Object]. Luckilly JSON is so popular that JS has an default methods for serializing String to JSON (JSON.parse(someString)) and other way around (JSON.stringify(JSONObject)).

Related

Submit form array fields using Ajax [duplicate]

I have a form with name orderproductForm and an undefined number of inputs.
I want to do some kind of jQuery.get or ajax or anything like that that would call a page through Ajax, and send along all the inputs of the form orderproductForm.
I suppose one way would be to do something like
jQuery.get("myurl",
{action : document.orderproductForm.action.value,
cartproductid : document.orderproductForm.cartproductid.value,
productid : document.orderproductForm.productid.value,
...
However I do not know exactly all the form inputs. Is there a feature, function or something that would just send ALL the form inputs?
This is a simple reference:
// this is the id of the form
$("#idForm").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var actionUrl = form.attr('action');
$.ajax({
type: "POST",
url: actionUrl,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
You can use the ajaxForm/ajaxSubmit functions from Ajax Form Plugin or the jQuery serialize function.
AjaxForm:
$("#theForm").ajaxForm({url: 'server.php', type: 'post'})
or
$("#theForm").ajaxSubmit({url: 'server.php', type: 'post'})
ajaxForm will send when the submit button is pressed. ajaxSubmit sends immediately.
Serialize:
$.get('server.php?' + $('#theForm').serialize())
$.post('server.php', $('#theForm').serialize())
AJAX serialization documentation is here.
Another similar solution using attributes defined on the form element:
<form id="contactForm1" action="/your_url" method="post">
<!-- Form input fields here (do not forget your name attributes). -->
</form>
<script type="text/javascript">
var frm = $('#contactForm1');
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
});
</script>
There are a few things you need to bear in mind.
1. There are several ways to submit a form
using the submit button
by pressing enter
by triggering a submit event in JavaScript
possibly more depending on the device or future device.
We should therefore bind to the form submit event, not the button click event. This will ensure our code works on all devices and assistive technologies now and in the future.
2. Hijax
The user may not have JavaScript enabled. A hijax pattern is good here, where we gently take control of the form using JavaScript, but leave it submittable if JavaScript fails.
We should pull the URL and method from the form, so if the HTML changes, we don't need to update the JavaScript.
3. Unobtrusive JavaScript
Using event.preventDefault() instead of return false is good practice as it allows the event to bubble up. This lets other scripts tie into the event, for example analytics scripts which may be monitoring user interactions.
Speed
We should ideally use an external script, rather than inserting our script inline. We can link to this in the head section of the page using a script tag, or link to it at the bottom of the page for speed. The script should quietly enhance the user experience, not get in the way.
Code
Assuming you agree with all the above, and you want to catch the submit event, and handle it via AJAX (a hijax pattern), you could do something like this:
$(function() {
$('form.my_form').submit(function(event) {
event.preventDefault(); // Prevent the form from submitting via the browser
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function(data) {
// Optionally alert the user of success here...
}).fail(function(data) {
// Optionally alert the user of an error here...
});
});
});
You can manually trigger a form submission whenever you like via JavaScript using something like:
$(function() {
$('form.my_form').trigger('submit');
});
Edit:
I recently had to do this and ended up writing a plugin.
(function($) {
$.fn.autosubmit = function() {
this.submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function(data) {
// Optionally alert the user of success here...
}).fail(function(data) {
// Optionally alert the user of an error here...
});
});
return this;
}
})(jQuery)
Add a data-autosubmit attribute to your form tag and you can then do this:
HTML
<form action="/blah" method="post" data-autosubmit>
<!-- Form goes here -->
</form>
JS
$(function() {
$('form[data-autosubmit]').autosubmit();
});
You can also use FormData (But not available in IE):
var formData = new FormData(document.getElementsByName('yourForm')[0]);// yourForm: form selector
$.ajax({
type: "POST",
url: "yourURL",// where you wanna post
data: formData,
processData: false,
contentType: false,
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
},
success: function(data) {console.log(data)}
});
This is how you use FormData.
Simple version (does not send images)
<form action="/my/ajax/url" class="my-form">
...
</form>
<script>
(function($){
$("body").on("submit", ".my-form", function(e){
e.preventDefault();
var form = $(e.target);
$.post( form.attr("action"), form.serialize(), function(res){
console.log(res);
});
});
)(jQuery);
</script>
Copy and paste ajaxification of a form or all forms on a page
It is a modified version of Alfrekjv's answer
It will work with jQuery >= 1.3.2
You can run this before the document is ready
You can remove and re-add the form and it will still work
It will post to the same location as the normal form, specified in
the form's "action" attribute
JavaScript
jQuery(document).submit(function(e){
var form = jQuery(e.target);
if(form.is("#form-id")){ // check if this is the form that you want (delete this check to apply this to all forms)
e.preventDefault();
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(), // serializes the form's elements.
success: function(data) {
console.log(data); // show response from the php script. (use the developer toolbar console, firefox firebug or chrome inspector console)
}
});
}
});
I wanted to edit Alfrekjv's answer but deviated too much from it so decided to post this as a separate answer.
Does not send files, does not support buttons, for example clicking a button (including a submit button) sends its value as form data, but because this is an ajax request the button click will not be sent.
To support buttons you can capture the actual button click instead of the submit.
jQuery(document).click(function(e){
var self = jQuery(e.target);
if(self.is("#form-id input[type=submit], #form-id input[type=button], #form-id button")){
e.preventDefault();
var form = self.closest('form'), formdata = form.serialize();
//add the clicked button to the form data
if(self.attr('name')){
formdata += (formdata!=='')? '&':'';
formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
}
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
success: function(data) {
console.log(data);
}
});
}
});
On the server side you can detect an ajax request with this header that jquery sets HTTP_X_REQUESTED_WITH
for php
PHP
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//is ajax
}
This code works even with file input
$(document).on("submit", "form", function(event)
{
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});
I really liked this answer by superluminary and especially the way he wrapped is solution in a jQuery plugin. So thanks to superluminary for a very useful answer. In my case, though, I wanted a plugin that would allow me to define the success and error event handlers by means of options when the plugin is initialized.
So here is what I came up with:
;(function(defaults, $, undefined) {
var getSubmitHandler = function(onsubmit, success, error) {
return function(event) {
if (typeof onsubmit === 'function') {
onsubmit.call(this, event);
}
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function() {
if (typeof success === 'function') {
success.apply(this, arguments);
}
}).fail(function() {
if (typeof error === 'function') {
error.apply(this, arguments);
}
});
event.preventDefault();
};
};
$.fn.extend({
// Usage:
// jQuery(selector).ajaxForm({
// onsubmit:function() {},
// success:function() {},
// error: function() {}
// });
ajaxForm : function(options) {
options = $.extend({}, defaults, options);
return $(this).each(function() {
$(this).submit(getSubmitHandler(options['onsubmit'], options['success'], options['error']));
});
}
});
})({}, jQuery);
This plugin allows me to very easily "ajaxify" html forms on the page and provide onsubmit, success and error event handlers for implementing feedback to the user of the status of the form submit. This allowed the plugin to be used as follows:
$('form').ajaxForm({
onsubmit: function(event) {
// User submitted the form
},
success: function(data, textStatus, jqXHR) {
// The form was successfully submitted
},
error: function(jqXHR, textStatus, errorThrown) {
// The submit action failed
}
});
Note that the success and error event handlers receive the same arguments that you would receive from the corresponding events of the jQuery ajax method.
I got the following for me:
formSubmit('#login-form', '/api/user/login', '/members/');
where
function formSubmit(form, url, target) {
$(form).submit(function(event) {
$.post(url, $(form).serialize())
.done(function(res) {
if (res.success) {
window.location = target;
}
else {
alert(res.error);
}
})
.fail(function(res) {
alert("Server Error: " + res.status + " " + res.statusText);
})
event.preventDefault();
});
}
This assumes the post to 'url' returns an ajax in the form of {success: false, error:'my Error to display'}
You can vary this as you like. Feel free to use that snippet.
jQuery AJAX submit form, is nothing but submit a form using form ID when you click on a button
Please follow steps
Step 1 - Form tag must have an ID field
<form method="post" class="form-horizontal" action="test/user/add" id="submitForm">
.....
</form>
Button which you are going to click
<button>Save</button>
Step 2 - submit event is in jQuery which helps to submit a form. in below code we are preparing JSON request from HTML element name.
$("#submitForm").submit(function(e) {
e.preventDefault();
var frm = $("#submitForm");
var data = {};
$.each(this, function(i, v){
var input = $(v);
data[input.attr("name")] = input.val();
delete data["undefined"];
});
$.ajax({
contentType:"application/json; charset=utf-8",
type:frm.attr("method"),
url:frm.attr("action"),
dataType:'json',
data:JSON.stringify(data),
success:function(data) {
alert(data.message);
}
});
});
for live demo click on below link
How to submit a Form using jQuery AJAX?
I know this is a jQuery related question, but now days with JS ES6 things are much easier. Since there is no pure javascript answer, I thought I could add a simple pure javascript solution to this, which in my opinion is much cleaner, by using the fetch() API. This a modern way to implements network requests. In your case, since you already have a form element we can simply use it to build our request.
const form = document.forms["orderproductForm"];
const formInputs = form.getElementsByTagName("input");
let formData = new FormData();
for (let input of formInputs) {
formData.append(input.name, input.value);
}
fetch(form.action,
{
method: form.method,
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error.message))
.finally(() => console.log("Done"));
Try
fetch(form.action,{method:'post', body: new FormData(form)});
function send(e,form) {
fetch(form.action,{method:'post', body: new FormData(form)});
console.log('We submit form asynchronously (AJAX)');
e.preventDefault();
}
<form method="POST" action="myapi/send" onsubmit="send(event,this)" name="orderproductForm">
<input hidden name="csrfToken" value="$0meh#$h">
<input name="email" value="aa#bb.com">
<input name="phone" value="123-456-666">
<input type="submit">
</form>
Look on Chrome Console > Network after/before 'submit'
consider using closest
$('table+table form').closest('tr').filter(':not(:last-child)').submit(function (ev, frm) {
frm = $(ev.target).closest('form');
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert(data);
}
})
ev.preventDefault();
});
You may use this on submit function like below.
HTML Form
<form class="form" action="" method="post">
<input type="text" name="name" id="name" >
<textarea name="text" id="message" placeholder="Write something to us"> </textarea>
<input type="button" onclick="return formSubmit();" value="Send">
</form>
jQuery function:
<script>
function formSubmit(){
var name = document.getElementById("name").value;
var message = document.getElementById("message").value;
var dataString = 'name='+ name + '&message=' + message;
jQuery.ajax({
url: "submit.php",
data: dataString,
type: "POST",
success: function(data){
$("#myForm").html(data);
},
error: function (){}
});
return true;
}
</script>
For more details and sample Visit:
http://www.spiderscode.com/simple-ajax-contact-form/
To avoid multiple formdata sends:
Don't forget to unbind submit event, before the form submited again,
User can call sumbit function more than one time, maybe he forgot something, or was a validation error.
$("#idForm").unbind().submit( function(e) {
....
If you're using form.serialize() - you need to give each form element a name like this:
<input id="firstName" name="firstName" ...
And the form gets serialized like this:
firstName=Chris&lastName=Halcrow ...
I find it surprising that no one mentions data as an object. For me it's the cleanest and easiest way to pass data:
$('form#foo').submit(function () {
$.ajax({
url: 'http://foo.bar/some-ajax-script',
type: 'POST',
dataType: 'json',
data: {
'foo': 'some-foo-value',
'bar': $('#bar').val()
}
}).always(function (response) {
console.log(response);
});
return false;
});
Then, in the backend:
// Example in PHP
$_POST['foo'] // some-foo-value
$_POST['bar'] // value in #bar
This is not the answer to OP's question,
but in case if you can't use static form DOM, you can also try like this.
var $form = $('<form/>').append(
$('<input/>', {name: 'username'}).val('John Doe'),
$('<input/>', {name: 'user_id'}).val('john.1234')
);
$.ajax({
url: 'api/user/search',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: $form.serialize(),
success: function(data, textStatus, jqXHR) {
console.info(data);
},
error: function(jqXHR, textStatus, errorThrown) {
var errorMessage = jqXHR.responseText;
if (errorMessage.length > 0) {
alert(errorMessage);
}
}
});
JavaScript
(function ($) {
var form= $('#add-form'),
input = $('#exampleFormControlTextarea1');
form.submit(function(event) {
event.preventDefault();
var req = $.ajax({
url: form.attr('action'),
type: 'POST',
data: form.serialize()
});
req.done(function(data) {
if (data === 'success') {
var li = $('<li class="list-group-item">'+ input.val() +'</li>');
li.hide()
.appendTo('.list-group')
.fadeIn();
$('input[type="text"],textarea').val('');
}
});
});
}(jQuery));
HTML
<ul class="list-group col-sm-6 float-left">
<?php
foreach ($data as $item) {
echo '<li class="list-group-item">'.$item.'</li>';
}
?>
</ul>
<form id="add-form" class="col-sm-6 float-right" action="_inc/add-new.php" method="post">
<p class="form-group">
<textarea class="form-control" name="message" id="exampleFormControlTextarea1" rows="3" placeholder="Is there something new?"></textarea>
</p>
<button type="submit" class="btn btn-danger">Add new item</button>
</form>
There's also the submit event, which can be triggered like this $("#form_id").submit(). You'd use this method if the form is well represented in HTML already. You'd just read in the page, populate the form inputs with stuff, then call .submit(). It'll use the method and action defined in the form's declaration, so you don't need to copy it into your javascript.
examples

sending outerhtml with json makes trouble

I want to send some parts of the html source code with an ajax call.
If I define the data to be sent for the ajax call in this way:
var content={};
content['mypart1']='my content 1';
content['mypart2']='my content 2';
content=JSON.stringify(content);
In the console I see this string for sending:
... , content: "{\"mypart1\":\"my content 1\",\"mypart2\":\"my content 2\"}" ...
It works. After $test=json_decode($post['content']); I have the wanted array of my content parts.
Now I need to use it with real content parts, so i tried this;
$("[myselector]").each(function(i, part) {
content['mypart1']=$(part)[0].outerHTML;
content['mypart2']=$(part)[0].outerHTML;
});
content=JSON.stringify(content);
Now I see in the console, that the wanted html code is correctly inside the string.
But if I send this, I see in the console that inside the string there are multiple ///-signs and the keys are also inside \" now.
"{\"mypart1\":\"<div id=\\\"myid\\\" data-mydataid=\\\"123456\\\" class=\\\".....
I think it was because this faulty string that the jason_decode won't work correctly.
$test=json_decode($post['content']);
With this data I won't receive the wanted array, $test is empty.
What caused the multiple ///-signs and /-around the keys and how I can prevent this?
Thanks a lot for helping and explaining.
Maybe i have to unserialize the outerhtml part before add them to a stringify string?
This is the Ajax call
do_ajax_call({
'content': content,
...
});
function do_ajax_call(data,ajaxurl){
....
$.ajax({ url: ajaxurl,
method: 'POST',
data: data,
dataType:'json',
success: function(result){
...
});
HTML:
<div class="progress-bar progress-primary" id="bar" role="progressbar" style="width: 0%"></div>
<b id="import"></b>
js:
var data = {};//js object
data["key1"] = document.getElementById('import').outerHTML;
data["key2"] = document.getElementById('bar').outerHTML;
$.ajax({
beforeSend: function () {
},
complete: function () {
},
type: "POST",
url: ajaxurl,
data: data,
success: function (data) {
setTimeout(function () {
}, 1000);
}
});
php :
echo'<pre>';print_r($_POST);die;
output :
<pre>Array
(
[key1] => <b id="import"></b>
[key2] => <div class="progress-bar progress-primary" id="bar" role="progressbar" style="width: 0%"></div>
)
This is tested code

Returing a list of strings and iterating over it

I am new to jQuery and I am trying to iterate through a list of strings after making an ajax call to a controller. In this controller, I am returning a list of strings and I want to iterate over this list in jquery and present it to the screen. Here is my code.
This is my controller
[HttpPost]
public ActionResult GetComments() {
var cmts = ex.GetComments(psts, psons);
var lstCmt = ex.GetCommentsList(cments, psons);
return Json(lstCmt);
}
This is my view:
<div>
<button id="ldBtn" class="btn btn-primary">Load</button>
</div>
<div id="cments">
</div>
<script src="~/Scripts/jquery-3.2.1.js"></script>
<script>
$(document).ready(function() {
$("#ldBtn").on('click', function(evt) {
$("#cments").empty();
$.ajax({
type: "POST",
dataType: "html",
url: '#Url.Action("GetComments")',
data: {},
success: function(lists) {
//Something needs to be fixed here
$.each(lists, function(i, name) {
$('#comments').append('<p>' + name.Value + '</p>');
});
}
});
});
});
</script>
When I return the list, I am getting a huge string. How do I fix this?
Thanks in Advance
There's a couple of issues in your JS code. Firstly you're telling jQuery to expect a HTML response in the dataType setting. This is why you see the response as a string. This should be changed to JSON instead, that way jQuery will deserialise the response for you.
Secondly you're attempting to concatenate a Value property on each item in the list, yet they are strings (as you state you're returning a List<string> from your action), and will not have that property. You can simply append the name itself. Try this:
$("#ldBtn").on('click', function(evt) {
$("#cments").empty();
$.ajax({
url: '#Url.Action("GetComments")',
type: "POST",
dataType: 'json',
success: function(comments) {
$('#cments').append('<p>' + comments.join('</p><p>') + '</p>');
}
});
});
I assume the #comments/#cments discrepancy is only due to amending parts of your code when creating the question.
Also note that I simplified the append() logic so that it appends all comments in a single call, which should be slightly faster.

How to write dynamic text between div tags?

I am typing with the div on the login screen. I want this article to be dynamic. That's why I am using ajax jQuery to pull data. I want it to be written in the div. How do you do that?
<div class ="bas">Write here(title)</div>
$.ajax({
type: "GET",
url: MY,
success: function (msg, result, status, xhr) {
var obj = jQuery.parseJSON(msg);
title = obj[0].Write;
}
});
You can use either text() or html() to set the content of the required div element. Try this:
<div class="bas">Write here(title)</div>
$.ajax({
type: "GET",
url: MY,
dataType: 'json',
success: function(msg) {
$('.bas').text(msg[0].Write);
}
});
Note that by using dataType: 'json' jQuery will deserialise the response for you, so you don't need to call JSON.parse manually.
Use .text() function
<div class ="bas">Write here(title)</div>
$.ajax({
type: "GET",
url:MY,
success: function (msg, result, status, xhr) {
var obj = jQuery.parseJSON(msg);
title= obj[0].Write;
$(".bas").text(title);
}
});
You can do it by html() or text() depends on what object contains. If containing data includes html tags such as <strong> or .. use html() but if it's plain text use text() instead.
$.ajax({
type: "GET",
url:MY,
success: function (msg, result, status, xhr) {
var obj = jQuery.parseJSON(msg);
title= obj[0].Write;
$('.bas').html(title); // this line
}
});
if only remote read text file
<div class="bas">Write here (title)</div>
jQuery.get(myURL, /*ifMyParams,*/ function(data){
jQuery('.bas').text(data);
})
Use hanlderbars.js or <div class ="bas">Write here<span class="title"></span></div>

jQuery AJAX submit form

I have a form with name orderproductForm and an undefined number of inputs.
I want to do some kind of jQuery.get or ajax or anything like that that would call a page through Ajax, and send along all the inputs of the form orderproductForm.
I suppose one way would be to do something like
jQuery.get("myurl",
{action : document.orderproductForm.action.value,
cartproductid : document.orderproductForm.cartproductid.value,
productid : document.orderproductForm.productid.value,
...
However I do not know exactly all the form inputs. Is there a feature, function or something that would just send ALL the form inputs?
This is a simple reference:
// this is the id of the form
$("#idForm").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var actionUrl = form.attr('action');
$.ajax({
type: "POST",
url: actionUrl,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
You can use the ajaxForm/ajaxSubmit functions from Ajax Form Plugin or the jQuery serialize function.
AjaxForm:
$("#theForm").ajaxForm({url: 'server.php', type: 'post'})
or
$("#theForm").ajaxSubmit({url: 'server.php', type: 'post'})
ajaxForm will send when the submit button is pressed. ajaxSubmit sends immediately.
Serialize:
$.get('server.php?' + $('#theForm').serialize())
$.post('server.php', $('#theForm').serialize())
AJAX serialization documentation is here.
Another similar solution using attributes defined on the form element:
<form id="contactForm1" action="/your_url" method="post">
<!-- Form input fields here (do not forget your name attributes). -->
</form>
<script type="text/javascript">
var frm = $('#contactForm1');
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log('Submission was successful.');
console.log(data);
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
});
</script>
There are a few things you need to bear in mind.
1. There are several ways to submit a form
using the submit button
by pressing enter
by triggering a submit event in JavaScript
possibly more depending on the device or future device.
We should therefore bind to the form submit event, not the button click event. This will ensure our code works on all devices and assistive technologies now and in the future.
2. Hijax
The user may not have JavaScript enabled. A hijax pattern is good here, where we gently take control of the form using JavaScript, but leave it submittable if JavaScript fails.
We should pull the URL and method from the form, so if the HTML changes, we don't need to update the JavaScript.
3. Unobtrusive JavaScript
Using event.preventDefault() instead of return false is good practice as it allows the event to bubble up. This lets other scripts tie into the event, for example analytics scripts which may be monitoring user interactions.
Speed
We should ideally use an external script, rather than inserting our script inline. We can link to this in the head section of the page using a script tag, or link to it at the bottom of the page for speed. The script should quietly enhance the user experience, not get in the way.
Code
Assuming you agree with all the above, and you want to catch the submit event, and handle it via AJAX (a hijax pattern), you could do something like this:
$(function() {
$('form.my_form').submit(function(event) {
event.preventDefault(); // Prevent the form from submitting via the browser
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function(data) {
// Optionally alert the user of success here...
}).fail(function(data) {
// Optionally alert the user of an error here...
});
});
});
You can manually trigger a form submission whenever you like via JavaScript using something like:
$(function() {
$('form.my_form').trigger('submit');
});
Edit:
I recently had to do this and ended up writing a plugin.
(function($) {
$.fn.autosubmit = function() {
this.submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function(data) {
// Optionally alert the user of success here...
}).fail(function(data) {
// Optionally alert the user of an error here...
});
});
return this;
}
})(jQuery)
Add a data-autosubmit attribute to your form tag and you can then do this:
HTML
<form action="/blah" method="post" data-autosubmit>
<!-- Form goes here -->
</form>
JS
$(function() {
$('form[data-autosubmit]').autosubmit();
});
You can also use FormData (But not available in IE):
var formData = new FormData(document.getElementsByName('yourForm')[0]);// yourForm: form selector
$.ajax({
type: "POST",
url: "yourURL",// where you wanna post
data: formData,
processData: false,
contentType: false,
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
},
success: function(data) {console.log(data)}
});
This is how you use FormData.
Simple version (does not send images)
<form action="/my/ajax/url" class="my-form">
...
</form>
<script>
(function($){
$("body").on("submit", ".my-form", function(e){
e.preventDefault();
var form = $(e.target);
$.post( form.attr("action"), form.serialize(), function(res){
console.log(res);
});
});
)(jQuery);
</script>
Copy and paste ajaxification of a form or all forms on a page
It is a modified version of Alfrekjv's answer
It will work with jQuery >= 1.3.2
You can run this before the document is ready
You can remove and re-add the form and it will still work
It will post to the same location as the normal form, specified in
the form's "action" attribute
JavaScript
jQuery(document).submit(function(e){
var form = jQuery(e.target);
if(form.is("#form-id")){ // check if this is the form that you want (delete this check to apply this to all forms)
e.preventDefault();
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(), // serializes the form's elements.
success: function(data) {
console.log(data); // show response from the php script. (use the developer toolbar console, firefox firebug or chrome inspector console)
}
});
}
});
I wanted to edit Alfrekjv's answer but deviated too much from it so decided to post this as a separate answer.
Does not send files, does not support buttons, for example clicking a button (including a submit button) sends its value as form data, but because this is an ajax request the button click will not be sent.
To support buttons you can capture the actual button click instead of the submit.
jQuery(document).click(function(e){
var self = jQuery(e.target);
if(self.is("#form-id input[type=submit], #form-id input[type=button], #form-id button")){
e.preventDefault();
var form = self.closest('form'), formdata = form.serialize();
//add the clicked button to the form data
if(self.attr('name')){
formdata += (formdata!=='')? '&':'';
formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
}
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
success: function(data) {
console.log(data);
}
});
}
});
On the server side you can detect an ajax request with this header that jquery sets HTTP_X_REQUESTED_WITH
for php
PHP
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//is ajax
}
This code works even with file input
$(document).on("submit", "form", function(event)
{
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
},
error: function (xhr, desc, err)
{
}
});
});
I really liked this answer by superluminary and especially the way he wrapped is solution in a jQuery plugin. So thanks to superluminary for a very useful answer. In my case, though, I wanted a plugin that would allow me to define the success and error event handlers by means of options when the plugin is initialized.
So here is what I came up with:
;(function(defaults, $, undefined) {
var getSubmitHandler = function(onsubmit, success, error) {
return function(event) {
if (typeof onsubmit === 'function') {
onsubmit.call(this, event);
}
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function() {
if (typeof success === 'function') {
success.apply(this, arguments);
}
}).fail(function() {
if (typeof error === 'function') {
error.apply(this, arguments);
}
});
event.preventDefault();
};
};
$.fn.extend({
// Usage:
// jQuery(selector).ajaxForm({
// onsubmit:function() {},
// success:function() {},
// error: function() {}
// });
ajaxForm : function(options) {
options = $.extend({}, defaults, options);
return $(this).each(function() {
$(this).submit(getSubmitHandler(options['onsubmit'], options['success'], options['error']));
});
}
});
})({}, jQuery);
This plugin allows me to very easily "ajaxify" html forms on the page and provide onsubmit, success and error event handlers for implementing feedback to the user of the status of the form submit. This allowed the plugin to be used as follows:
$('form').ajaxForm({
onsubmit: function(event) {
// User submitted the form
},
success: function(data, textStatus, jqXHR) {
// The form was successfully submitted
},
error: function(jqXHR, textStatus, errorThrown) {
// The submit action failed
}
});
Note that the success and error event handlers receive the same arguments that you would receive from the corresponding events of the jQuery ajax method.
I got the following for me:
formSubmit('#login-form', '/api/user/login', '/members/');
where
function formSubmit(form, url, target) {
$(form).submit(function(event) {
$.post(url, $(form).serialize())
.done(function(res) {
if (res.success) {
window.location = target;
}
else {
alert(res.error);
}
})
.fail(function(res) {
alert("Server Error: " + res.status + " " + res.statusText);
})
event.preventDefault();
});
}
This assumes the post to 'url' returns an ajax in the form of {success: false, error:'my Error to display'}
You can vary this as you like. Feel free to use that snippet.
jQuery AJAX submit form, is nothing but submit a form using form ID when you click on a button
Please follow steps
Step 1 - Form tag must have an ID field
<form method="post" class="form-horizontal" action="test/user/add" id="submitForm">
.....
</form>
Button which you are going to click
<button>Save</button>
Step 2 - submit event is in jQuery which helps to submit a form. in below code we are preparing JSON request from HTML element name.
$("#submitForm").submit(function(e) {
e.preventDefault();
var frm = $("#submitForm");
var data = {};
$.each(this, function(i, v){
var input = $(v);
data[input.attr("name")] = input.val();
delete data["undefined"];
});
$.ajax({
contentType:"application/json; charset=utf-8",
type:frm.attr("method"),
url:frm.attr("action"),
dataType:'json',
data:JSON.stringify(data),
success:function(data) {
alert(data.message);
}
});
});
for live demo click on below link
How to submit a Form using jQuery AJAX?
Try
fetch(form.action,{method:'post', body: new FormData(form)});
function send(e,form) {
fetch(form.action,{method:'post', body: new FormData(form)});
console.log('We submit form asynchronously (AJAX)');
e.preventDefault();
}
<form method="POST" action="myapi/send" onsubmit="send(event,this)" name="orderproductForm">
<input hidden name="csrfToken" value="$0meh#$h">
<input name="email" value="aa#bb.com">
<input name="phone" value="123-456-666">
<input type="submit">
</form>
Look on Chrome Console > Network after/before 'submit'
I know this is a jQuery related question, but now days with JS ES6 things are much easier. Since there is no pure javascript answer, I thought I could add a simple pure javascript solution to this, which in my opinion is much cleaner, by using the fetch() API. This a modern way to implements network requests. In your case, since you already have a form element we can simply use it to build our request.
const form = document.forms["orderproductForm"];
const formInputs = form.getElementsByTagName("input");
let formData = new FormData();
for (let input of formInputs) {
formData.append(input.name, input.value);
}
fetch(form.action,
{
method: form.method,
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error.message))
.finally(() => console.log("Done"));
consider using closest
$('table+table form').closest('tr').filter(':not(:last-child)').submit(function (ev, frm) {
frm = $(ev.target).closest('form');
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert(data);
}
})
ev.preventDefault();
});
You may use this on submit function like below.
HTML Form
<form class="form" action="" method="post">
<input type="text" name="name" id="name" >
<textarea name="text" id="message" placeholder="Write something to us"> </textarea>
<input type="button" onclick="return formSubmit();" value="Send">
</form>
jQuery function:
<script>
function formSubmit(){
var name = document.getElementById("name").value;
var message = document.getElementById("message").value;
var dataString = 'name='+ name + '&message=' + message;
jQuery.ajax({
url: "submit.php",
data: dataString,
type: "POST",
success: function(data){
$("#myForm").html(data);
},
error: function (){}
});
return true;
}
</script>
For more details and sample Visit:
http://www.spiderscode.com/simple-ajax-contact-form/
To avoid multiple formdata sends:
Don't forget to unbind submit event, before the form submited again,
User can call sumbit function more than one time, maybe he forgot something, or was a validation error.
$("#idForm").unbind().submit( function(e) {
....
If you're using form.serialize() - you need to give each form element a name like this:
<input id="firstName" name="firstName" ...
And the form gets serialized like this:
firstName=Chris&lastName=Halcrow ...
I find it surprising that no one mentions data as an object. For me it's the cleanest and easiest way to pass data:
$('form#foo').submit(function () {
$.ajax({
url: 'http://foo.bar/some-ajax-script',
type: 'POST',
dataType: 'json',
data: {
'foo': 'some-foo-value',
'bar': $('#bar').val()
}
}).always(function (response) {
console.log(response);
});
return false;
});
Then, in the backend:
// Example in PHP
$_POST['foo'] // some-foo-value
$_POST['bar'] // value in #bar
This is not the answer to OP's question,
but in case if you can't use static form DOM, you can also try like this.
var $form = $('<form/>').append(
$('<input/>', {name: 'username'}).val('John Doe'),
$('<input/>', {name: 'user_id'}).val('john.1234')
);
$.ajax({
url: 'api/user/search',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
data: $form.serialize(),
success: function(data, textStatus, jqXHR) {
console.info(data);
},
error: function(jqXHR, textStatus, errorThrown) {
var errorMessage = jqXHR.responseText;
if (errorMessage.length > 0) {
alert(errorMessage);
}
}
});
JavaScript
(function ($) {
var form= $('#add-form'),
input = $('#exampleFormControlTextarea1');
form.submit(function(event) {
event.preventDefault();
var req = $.ajax({
url: form.attr('action'),
type: 'POST',
data: form.serialize()
});
req.done(function(data) {
if (data === 'success') {
var li = $('<li class="list-group-item">'+ input.val() +'</li>');
li.hide()
.appendTo('.list-group')
.fadeIn();
$('input[type="text"],textarea').val('');
}
});
});
}(jQuery));
HTML
<ul class="list-group col-sm-6 float-left">
<?php
foreach ($data as $item) {
echo '<li class="list-group-item">'.$item.'</li>';
}
?>
</ul>
<form id="add-form" class="col-sm-6 float-right" action="_inc/add-new.php" method="post">
<p class="form-group">
<textarea class="form-control" name="message" id="exampleFormControlTextarea1" rows="3" placeholder="Is there something new?"></textarea>
</p>
<button type="submit" class="btn btn-danger">Add new item</button>
</form>
There's also the submit event, which can be triggered like this $("#form_id").submit(). You'd use this method if the form is well represented in HTML already. You'd just read in the page, populate the form inputs with stuff, then call .submit(). It'll use the method and action defined in the form's declaration, so you don't need to copy it into your javascript.
examples

Categories

Resources