Convert Form Data into Request Data for an AJAX Request - javascript

I am trying to submit my form data via a POST AJAX request and cannot find any solutions.
I can't just get the values by ID or name etc because it is dynamically created depending on data from a database.
I have tried using the childNodes and think this may be a solution but cannot figure it out. Do I need to use JQuery? Can it be done with just JS as I'm a beginner.
Any ideas would be appreciated, cheers.

Did you tried below
$( "form" ).submit(function( event ) {
( var jsonData = $( this ).serializeArray() );
event.preventDefault();
// --- Your Ajax request
});

What you can do is just give an id (here i am giving form_id) to the form
$('#form_id').submit(function(){
e.preventDefault();
$.ajax({
type: "POST",
url: "your_url",
data: $('#form_id').serialize(),
success: function (data) {
alert('ok');
}
});
})
Cheers. :)

Related

Sending a POST request with Ajax on button click

I have a normal button, which triggers a basic function that prints the value of an element in my HTML to the console.
Now, instead of printing the value of that element i want to send it to my Django view with a POST request.
Here is the function:
$(document).on('click','.btnClick', function() {
var myvalue = $(this).data("myid");
console.log(myvalue);
});
Here, instead of printing that value, i want to send myvalue with a post request using Ajax.
I know how to do a POST request, the only difference is that this time, instead of using a form, i'm using a single button to trigger the request, and i'm not really used to that.
Here is how i would do it with a form:
$(document).ready(function () {
$("#myform").submit(function (event) {
$.ajax({
type: "POST",
url: "/myurl/",
data: {
'myvalue': $('id').val()
},
});
return false;
});
});
So, basically i just need to know how to integrate this piece of code inside the first function, so that the Ajax call is triggered not by the form (as it is in the second code) but from a button.
Just put your jquery ajax function inside into the click event function.
$(document).on('click','.btnClick', function() {
var myvalue = $(this).data("myid");
$.ajax({
type: "POST",
url: "/myurl/",
data: {
'myvalue': myvalue
},
});
});
Hope this will help.

How can I submit a form and then have the browser return to the same place on the page?

I am trying to create a form that when submitted, sends the data and then when the page reloads the user is returned to the same place on the page they were before submitting the form using either javascript or jquery.
Untested, but you would do something along the lines of:
$(function() {
var lst = localStorage.getItem('lastScrollTop');
if(lst !== null) {
$(window).scrollTop(lst);
localStorage.removeItem('lastScrollTop');
}
$("form").on('submit', function() {
//use whatever persistence method you'd like, I'm using HTML5 localStorage for brevity
localStorage.setItem('lastScrollTop', $(window).scrollTop());
});
});
First of all, it is much better to use JQuery as it has lot of inbuilt methods.
I normally use .ajax as it is very flexible and can be used to GET and POST data very quickly.
Now coming onto how to do it..
$.ajax({
url : "AJAX_POST_URL",
type: "POST",
data : formData, //The best way to formulate is using JSON and server to accept it
success: function(data, textStatus, jqXHR)
{
//data - response from server
},
error: function (jqXHR, textStatus, errorThrown)
{
}
});
You could prevent default submission, then submit using Ajax, so you don't leave the page.
$(document).ready(function(){
// your form
var $myForm = $('form');
$myForm.on('submit', function(e){
// stops the from from submitting and loading a new page.
e.preventDefault();
// use jQuery post to post the form fields to the default from action
$.post($myForm.attr('action'), $myForm.serialize(), function(data){
console.log(data);
});
});
});

html form submission via an ajax request? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
jQuery AJAX submit form
I have a form on a page A, and instead of me posting to a new page, is there a way that i can do onSubmit ajax request it instead? I want to make the page to be able to load in the result into a div.
I know how to write the script for the call sort of, but i wasn't sure if i had to hand write it or it if was possible to take all the form information and send it without having to code it all into the attributes. i was thinking I could just do some sort of thing like: onClick, post form but return results into a div.
Thoughts? Ideas?
Try using JQuery's serialize (API ref here)
EDIT: something like this:
$("input.submit").click( function() {
$.ajax( {
type: "POST",
url: $("form").attr( 'action' ),
data: $("form").serialize(),
success: function( response ) {
//Code to process the response
}
});
return false;
} );
$.ajax({
url: 'mypage.html',
success: function(data){
$('.result').html(data);
},
error: function(){
alert('failure');
}
});
Then you have a div:
<div class="result"> </div>
This will automatically populate with the result of your ajax post.
http://api.jquery.com/jQuery.post/
Also see TONS of related questions: Jquery checking success of ajax post

Can ajax call on return add new javascript function to the page?

I have a jQuery ajax call that returns html of a table. Now I need to let user to do some javascript action on the table.
Can the return ajax response contain the javascript code or do I have to load the javascript code in the page on the first load of the page?
The user has the option of triggering the 'new' javascript. It doesn't have to triggered on ajax call.
To answer the actual question, the return response can contain the script. Simplest is to place it after the html, as the ready event has already fired in page it is being loaded into
You can use the success (or other event) callbacks provided with jQuery .ajax() to perform this JS action. Something like this:
$.ajax({
success: function(){
// Perform JS action
}
}
The jQuery API lists all such event callbacks available for AJAX calls. Check this for more info.
The returned ajax response can contain javascript code as a string. Then you can eval(response).
If you want to request a script with ajax that will be run when retrieved, then you can use jQuery's getScript() method to retrieve it and then execute it.
Per the jQuery doc, getScript() is a shorthand for:
$.ajax({
url: url,
dataType: "script",
success: success
});
Which shows that jQuery's ajax command will handle a returned script for you automatically if you set the data type appropriately.
You can make your request a variable and extend upon it after the set up.
// Make the request to the server
var dataID = $("#WhatINeedForAParameter").val();
var request = $.ajax({
url: "PageOrControllerOrWebApi/MethodName",
type: "POST",
data: { id : dataID },
dataType: "json"
});
// When the request is done process
// what you need done
request.done(function(msg) {
alert('You got this ' + msg);
});
// If the request failed you can
// see what the problem was and
// handle the situation accordingly
request.fail(function(jqXHR, textStatus) {
alert( "Your request failed: " + textStatus );
});
you can do it using success callback i think this can be a way please try
$.ajax({
.....,
.....,
success:
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = url;
$("#tableID").append( script );
});
i hope it should help.

Iterate over the data to show Autocomplete suggestions

This is an API which returns results in an array, for auto suggestions
For Eg. if I query "google" I get the results as follows
["google","google maps","google translate","google earth","google images","google docs","google voice","google scholar","google chrome","google calendar",]
You can try it yourself here
Here's my code that I m using to query this API but it doesnt seem to return results.
Here's the code that I m using for it
$(function() {
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "q.php",
dataType: "json",
data: {
"q" : request.term
},
success: function( data ) {
response(data[1]);
}
});
},
minLength: 2
});
});
I dont understand where am I going wrong in the code
Please correct me ! Because it doesnt seem to be working as I wanted
Edit: Accessing the Data from the same server
You forgot to add jquery-ui library in your fiddle. But if you do code will not work anyway, because you can't access data from another domain via ajax request. Only from same domain on what js code executes.
This might be helpful
$(document).ready(function() {
$.getJSON('http://twitter.com/users/usejquery.json?callback=?', function(json) { //get information about the user usejquery from twitter api
$('#twitter_followers').text(json.followers_count); //get the follower_count from the json object and put it in a span
});
});
Look for something called as cross-domain ajax.
http://usejquery.com/posts/the-jquery-cross-domain-ajax-guide
You can read here about using jQuery autocomlete for cross-domain environment: http://1300grams.com/2009/08/17/jquery-autocomplete-with-json-jsonp-support-and-overriding-the-default-search-parameter-q/
Also you need to add jquery.autocomplete.js to your jsFiddle environment.

Categories

Resources