Submitting form data as JSON using ajax POST - javascript

So I have a form with a 3 hidden pre-filled input fields and 2 text input fields. I am trying to submit this form data using AJAX post as a JSON.
Upon hitting the submit button, I get the url as :
http:myurl.com:7001/pagename/?obj1=val1&obj2=val2&obj3=val3&obj4=val4
after this I wrote some code which I have mentioned to convert these as JSON and then post it.
The problem which I am getting is:
How can I integrate the code I mentioned into the submit button, so that, as soon as the user click the submit button, the url as mentioned above is obtained and everything else (as mentioned in the code) happens in the background and the ajax post request is made.
Thanks.
I am sorry if anything is unclear.
//This is the code, and If I run it in console after clicking the submit button then I am able to do the ajax post successfully. I want to integrate this code to the submit button.
var urlvalue = location.search.substring(1).replace(/\+/g, '%20');
var postdata = JSON.parse('{"' + decodeURIComponent(urlvalue).replace(/&/g, '","').replace(/=/g,'":"') + '"}');
console.log(urlvalue);
const URL = myurl;
$.ajax({
url:URL,
type:'POST',
data: postdata,
success: function(result){
console.log(result);
},
error: function(error){
console.log(`Error $(error)`);
}
});

I'm not sure I understand your question exactly, but if you just want the form submission to POST the data somewhere, you will have to provide a function to the form's onsubmit attribute.
That function should contain pretty much the working code you have at the bottom of your question (as well as cancelling the default form action with event.preventDefault()).

Related

Validate a Form Submit before submitting and writing a result into a field, that will then be submitted - using Prevent default and Ajax requests

When I press the Form Submit button, I want to action some validation (via an Ajax call), and change a screen value, before the Form is actually submitted.
My issue is that when I try this, and I manually action the Submit button, the screen value is not actually updated until the Form has been submitted. Too late!
Is there any way around this issue? I've tried to comment in the code exactly what I mean.
$("form").submit(function (event) {
// we prevent teh default action of the udpate button
event.preventDefault();
alert('In Jquery/JS.. button pressed / Prevented default');
// variables for "self" so we can access the form
// nativley using javascript and not jquery
var self = this,
root = 'https://jsonplaceholder.typicode.com';
// Now call Ajax, get results, and if good, manually call the
// submit button.
$.ajax({
url: root + '/posts/1',
method: 'GET',
success: function (data) {
alert('in ajax success');
}
}).done(function (data) {
alert('in ajax done - Title data = : ' + data.title);
if (data.title !== "") {
// We assign our Input Text field some data
$('#textfield').val(data.title);
// The on screen value actually hasn't updated :o(
alert('about to self submit');
// We go to submit... but our form isn't actually
// updated with the Ajax text yet...
// is that possible before we action the submit???
self.submit();
}
}).fail(function () {
alert('error');
});
});
See JSFiddle : https://jsfiddle.net/dave_pace/890zmj1f/
It is not what you think. JavaScript is single-threaded. Therefore, an alert statement is executed just after its previous statement. It doesn't wait for the previous statement to finish.
Adding to that, alert is quicker than setting the value in the textbox, and it actually blocks the thread until it is dismissed. That's why you cannot see the value set in the textbox, but can see the submit alert first.
Your fiddle is fine, and works as it should. If you want to test this, try to remove all the alert statements from your code, and try to submit your form to an actual URL, for example https://www.google.com.
Though submitting to Google will result in an error, you can actually see that the textbox is being populated before the submit happens.

Update page from POST response

Is there any way to preserve the default behavior of a form POST submit action in a javascript http request? Normally when I submit the forms, the url is redirected to the action and the page is replaced with the response html, but if you use preventDefault() or return false on a submit event you will get the response in HTML sent as a string to the callback.
Right now I have to add some extra data to my form submission, but I would like to update the page based on the response.
$("#"+target).on('submit', function (e)
const counselors_list = counselors.list.map(e=>e.name);
const groups_list = ...
const data = $(this).serialize() + "&" + $.param({patient: {counselors: counselors_list, groups_attended: groups_list}});
$.post(action, data, e=>e)//Data gets returned as e, instead of updating the page
return false;
});
The only way I can think of is replacing the whole DOM with the response, but that seems very hacky. Is there any way to preserve the default form behavior while still adding this data?

JQUERY AJAX Login Form with ASP Classic

I have a modal menu that I'm using as a login form that has input for the username and password utilizing JQUERY AJAX methods seen here:
function ajaxSubmit(){
$.post("verify.asp",$("#Form-Submit").serialize());
$("#Modal-Menu-Status").load("verify.asp");
};
I'm trying to submit the data that was put into the form, process it to verify.asp which outputs a login status(Logged In, Incorrect Information), and then get that status back to my menu.
It's loading my verify.asp info into the menu, but it always comes back as "Incorrect information". Its not processing any information from the serialize data how can I communicate properly with this page? Any help would be greatly appreciated. Thanks!
You're actually creating two separate requests to verify.asp. The first one sends the form data correctly, but its response is ignored. On the second one you do get the response onto #Modal-Menu-Status, but there isn't any parameter being sent, so that "incorrect information" is being returned.
You should use JQuery's ajax() method:
function ajaxSubmit(){
$.ajax({
url: "verify.asp",
data: $("#Form-Submit").serialize(),
method: "POST",
success: function(response){
$("#Modal-Menu-Status").html(response);
}
});
}

Form loads, but fails to submit, django-ajax

I am having trouble getting my form to submit. The problem seems to be unique to loading the form into a particular page. The form functions perfectly if not loaded and accessed manually by typing the url. Also, the form accessed manually doesn't function if method="POST" is removed from the form designation.
excerpt from views.py to manage form
if request.method == 'POST':
form = SelectMyBookForm(request.POST, choices=choices)
# do stuff
So my question is this:
Is the reason the form is not submitting properly in the loaded case because the "POST" request is not taking place at the correct url? How can I get the "POST" request to be recognized? Can I use Ajax (as in activate.js) to get around this condition in django?
I used the JQuery load() function to load a form on another page. The form renders correctly, but fails to submit when the button is pressed. I attempted to write a function in Javascript to help correct this issue. #submitform refers to the button that will submit the form #bookselect is the id of the form itself.
from activate.js
$("#bookselect").submit(function(e) {
e.preventDefault();
var elem = getElementsByTagName('course_link');
var pk = elem.attr('data');
var cond = $("li.tab.ui-tabs-selected").attr("id");
$.ajax({
type: "POST",
url: selectConditionURL(pk, cond),
success: function(response) {
console.log(response)
}
});
})

using Blobstore Python API with ajax

there is any sample showing how to use the blobstore api with ajax?
when i use forms works fine, but if i use jquery i don't know how to send the file and i get this error:
blob_info = upload_files[0]
IndexError: list index out of range
I have this code in javascript
function TestAjax()
{
var nombre="Some random name";
ajax={
type: "POST",
async:true,
//dataType:"json",
url:"{{upload_url}}",
data:"nombreEstudio="+nombre,
error: function ()
{
alert("Some error");
$("#buscando").html("");
},
success: function()
{ alert("it's ok") }
};
$.ajax(ajax);
}
When i use forms the file it's sended with a input tag (exactly like the doc's sample)
I wrote a series of posts about exactly this.
Somehow you still need to get the multipart form data request to the server... so when you're using forms, I assume your <form> tag has something like this on it: enctype="multipart/form-data", right?
When you're just sending a "POST" via ajax, you're losing that multipart request, which is where your file is.
There are some jQuery "ajax file upload" plugins out there that may help you out.
Hope this helps!
** EDIT **
I guess one thing I can add to this is usually ajax file uploads (on the client) are implemented by either creating a hidden iframe, and using that iframe to submit a form, or using a form and posting it via JavaScript.

Categories

Resources