I used a tutorial to get the following ajax code. In the tutorial, they have the library jquery.form.js. Here is the code:
function onsuccess(response,status){
$("#onsuccessmsg").html(response);
alert(response);
}
$("#uploadform").on('change',function(){
var options={
url : $(this).attr("action"),
success : onsuccess
};
$(this).ajaxSubmit(options);
return false;
});
What if I don't want to have jquery.form.js implemented. What would be the equivalent code with normal ajax (without the library)?
Update
I tried the following code:
$("#uploadform").on('change',function(){
$.ajax({
url: $(this).attr("action"),
context: document.body,
success: function(){
$("#onsuccessmsg").html(response);
alert("asdf");
}
});
return false;
});
and it doesn't do anything now.
It would be something more like: (apologies for the formatting, I'm on my mobile)
$("#uploadform").on('submit',function(e){
e. preventDefault() ;
var formData = new FormData($(this)[0]);
$.ajax({
url: $(this).attr("action"),
context: document.body,
data: formData,
type: "POST",
contentType: false,
processData: false,
success: function(response, status, jqxhr){
$("#onsuccessmsg").html(response);
alert("asdf");
}
});
return false;
});
The data var will need to be built up manually by you by running through the form fields. You may also want to check out jquery post, which is a shorthand way of writing the above.
You can use this previously answered question to get the form data that you need to pass in to the ajax data field:
How can I get form data with Javascript/jQuery?
It's also worth noting that if you are posting a file from your form, your form must have enctype="multipart/form-data".
When submitting your form using ajax you need to set contentType: false, processData: false. See this post for reference.
I have updated the code snippet above to reflect this.
If this has answered your question please mark it as the correct answer.
Related
I'd like to create a google-docs add-on that sends an ajax call to a webhook.
I've tried the below, but I get the following error
Error
ReferenceError: "$" is not defined. (line 5, file "")
Code
function myFunction() {
var arr = 'data'
$.ajax({
url: 'webhook_url',
type: 'POST',
data: arr,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function () {
alert('Success');
}
});
}
If ajax can't be used here is there any other way to make a request to a server-side resource
This is an OLD question, so I don't know if you still have the issue, but, from the error you're getting Jquery is either not added, or not available.
You could try doing it with vanilla js, see this link for a walkthrough: https://www.sitepoint.com/guide-vanilla-ajax-without-jquery/
I am using the plugin jquery.form.js and I want to programmatically submit a form and include a file with it. The code and options I have set up with work with $.ajax but not .ajaxSubmit. According to the jquery.form.js documentation you can pass any standard $.ajax options to .ajaxSubmit but I can't seem to get it to work. I'd like to use .ajaxSubmit if possible so I can utilize some of the other features it offers.
$(document).ready(function() {
$('#file-form').submit(function(event) {
event.preventDefault();
var form = $("<form style='display:none;' method='post' action='video_upload.php' enctype='multipart/form-data'></form>");
var fd = new FormData();
fd.append('uploadedfile', $('#file')[0].files[0]);
var options = {
url: 'video_upload.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
beforeSend: function(xhr){
alert('start');
},
success: function(data){
alert(data);
}
};
$.ajax(options);
//form.ajaxSubmit(options);
return false;
});
});
Running $.ajax(options) works but form.ajaxSubmit(options) doesn't. What am I missing?
Thanks!
If you check the source code of the method ajaxSubmit - http://malsup.github.io/jquery.form.js you can see that the property data of the options is serialised/deserialised and converted several times. So most likely the content really submitted will be quite different from what happens in .ajax call. Later on the ajaxSubmit collects the files from form and submits them differently.
Basically, for me the specifying data while submitting with ajaxSubmit goes against the concept of this plugin, which is described as "The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process." Idiomatic way of using ajaxSubmit would be applying this method for the form with controls.
I've got some jquery that submits a form for me. It works just fine. The only major problem is how simple it is.
The form submits the info to the database using my php script without refreshing the page, but the page isn't updated in any way to show the new data. What are some good ways to update the page or div so my new data is displayed after submitting the form. Below is my code
$(function() {
$('#form').submit(function(e) {
var data = $(this).serialize();
// Stop the form actually posting
e.preventDefault();
// Send the request
$.ajax({
type: "POST",
url: "submit.php",
data: data,
cache: false,
success: function(html){
$('textarea#joke').val('');
}
});
});
});
You are very close, just use html() method or text() depend on your needs, for your example I think text is better, since you want put text into textarea
success: function(html){
$('textarea#joke').text(html);
}
but if you want put some html into custom div do
success: function(html){
$('#custom-div').html(html);
}
Suppose from the submit.php, you are returning some value as status = true if form submitted suceessfully else status = false
then in your ajax code, you can use it as
success: function(html){
if(html.status == true)
$('textarea#joke').html('Form submitted succcessfully');
else
$('textarea#joke').html('ERROR!');
}
OR
success: function(html){
$('textarea#joke').val(html.status);
}
This would update the div content of $('textarea#joke')
Hope this would help you.
Thanks.
I have lots of forms on a project I'm working on.
All the forms pretty much go through AJAX.
$.ajax({
type: "GET",
cache: false,
url: $(this).attr("action"),
data: ???,
success: function(msg){
}
});
I want to be able to intercept these POST's and instead run them through AJAX.
The code is written into a method that will be reused.
So the question is: How can I select all the data that was going to be passed, turn it into a query string and insert it into the data: ???, part.
Thanks
You need to intercept the submit event. Bind an event handler on your <form> elements. When encountered, stop its propagation and its default behavior by returning false from within that event handler.
Now, you can create your .ajax() request in that handler to. To create a serialized form of your form-data into a query-string, use jQuerys .serialize() method on that form aswell.
For instance:
$('#myFormId').on('submit', function( event ) {
$.ajax({
type: "GET",
cache: false,
url: $(this).attr("action"),
data: $(this).serialize(),
success: function(msg){
}
});
return false;
});
Or just create that as delegated event, which handles all of your forms, like
$(document).on('submit', 'form', function( event ) {
});
Use serialize method:
http://api.jquery.com/serialize/
Is it possible to tell jqGrid to send all search options in JSON format ? Hence I won't have to reformat it on the backend side.
There is no direct function like that mentioned in the documentation, so you will probably have realize that manually in the beforeSubmit method of the jqGrid. I would spontaneously use jQuerys serializeArray method for the form and a JSON Serializer. Then you will have to submit the serialized Form via Ajax. Just make sure, that you return success : false, so that jqGrid doesn't submit the form.
beforeSubmit : function(postdata, formid) {
var formarray = $('#' + formid).serializeArray();
var httpbody = JSON.stringify(formarray);
// Send accordingly via AJAX
$.ajax(...);
// This looks kind of weird, but we don't want jqgrid to continue cause it was sent already
return { success : false, message : "Successffully saved" };
}
Doesn't seem like the nicest sollution though but the beforeSubmit Event is probably the only place to dig into it.
I don't know how helpful this will be, but I found that I can return true here as long as I set my editurl to '#' ....
beforeSubmit : function(postdata, formid) {
if (isValid) {
$.ajax({
type: "POST",
async: false,
contentType: "application/json; charset=utf-8",
url: "/RateIQ/Main.aspx/Accessorial/AccessorialDetailSave",
data: JSON.stringify(postdata),
dataType: "json"
});
}
return [isValid, ""];
}
and I've experienced no side effects so far...