Adding dynamic form data to ajax post request - javascript

Say i have a form in html with the following content
<form>
<div id="si-main">
<button id="si-btn">Add new content</button>
<div class="si-content">
<input type="text" class="si-input" name="content">
</div>
</div>
<input type="submit" id="si-submit" value="Submit">
</form>
Now i wanna append the ".si-content" div when i click the "#si-btn" i do that using this script in JS
$('#si-btn').click(function() {
$('#si-main').append('<div class="si-content"><input type="text" class="si-input" name="content"></div>')
})
I then submit the form like this in JS
$('form #si-submit').click(function() {
var data_to_send = {}
$('form').find('.si-input').each(function() {
if ($(this).hasClass('si-input')) {
data_to_send[$(this).attr('name')] = $(this).val()
}
})
//NEXT I SEND THE AJAX REQUEST AND HANDLE THE RESPONSE
})
Now the problem is each i append it adds a new "si-content" div. But when i send the data it only sends the content of the first div. Can someone tell me what would be the best way add the data in this case ?

try:
$('#si-main').append('<div class="si-content"><input type="text" class="si-input" name="content[]"></div>');
$('form #si-submit').click(function() {
var data_to_send = $(this).parent('form').serialize();
//NEXT SEND THE AJAX REQUEST AND HANDLE THE RESPONSE
})

Related

Using AJAX to submit form

I have developed a Python API and am now integrating it with a HTML template I have downloaded. It is a simple one page HTML template with a form to accept a album name and artist name. I am looking to process the form using AJAX. So once the form has been successfully submitted, it is replaced with a message returned by the API.
The (simplified) html snippet is:
<div class="form">
<form role="form" action="form.php" id="signup">
<div class="form-group">
<label>Artist Name</label>
<input type="text" name="artist" id="artist">
</div>
<div class="form-group">
<label>Tracking Number</label>
<input type="text" name="album" class="album">
</div>
<button type="submit" class="btn">Submit!</button>
</form>
</div>
Then I have a JS file I import at the beginning of the html file. Below is the JS file.
$(function() {
var form = $('#signup');
var formMessages = $('#form-messages');
$(form).submit(function(e) {
e.preventDefault();
var formData = {
'artist' : $('input[name=artist]').val(),
'album' : $('input[name=album]').val(),
};
// process the form
$.ajax({
type : 'POST',
url : 'form.php',
data : formData,
dataType : 'json'
})
.done(function(data) {
var content = $(data).find('#content');
$("#result").empty().append(content);
});
});
I think the issue is with the .done(function(data)) however, the website I found the code on wasn't clear.
form.php returns a JSON string. At the moment when I use the form, it sends the information to the Python API and the Python API returns a JSON message. But I cannot access the JSON message. It is in contains
'code': X, 'message':'returned messaged...'
ideally I would like to do a if/else statement. So
if code = 1:
display: Success
etc but I have no idea where to start with it in PHP/JS.
I was able to get it working eventually after seeing a few other stack overflow answers and another website.
I added one div to the html file under the button before the end of the form to make:
<form>
...
...
<button type="submit" class="btn">Submit!</button>
<div id="thanks" style="display:none;"></div>
</form>
Then, in the JS file I amended .done(function(data)) to be:
.done(function(data) {
if (data.result == '1') {
$('#thanks').show().text("Success!");
$('input[type="text"],text').val('');
} else if (data.result == '2') {
$('#thanks').show().text("Album and Artist already exists");
} else {
$('#thanks').show().text("Uh Oh. Something has gone wrong. Please try again later or contact me for more help");
}
});

on form submit send id using js function to the mvc controller

I have mvc razor view form which on submit form calls javascript function which then sends particular selected comboboxid to the controller to further processing.
<input type="submit" value="Save" onclick="submitForm()"/>
function submitForm()
{
var selComboBoxId = $('#comboboxId').val();
// send selComboBoxId to the controller ..
}
is there better way to send this id on form submit, without this js function?
Try this:
<form>
<input name="comboboxId" type="text" id="comboboxId">
<button type="submit">Submit</button>
</form>
$('form').on('submit', function(e){
e.preventDefault();
var params = $(this).serialize();
console.log(params);
// do your ajax here
})
DEMO

Using results from a post request in a javascript variable

I have a very basic question (I'm sure) - I have an Zoho application and I'm using their REST API to recover a single result from a table.
I want to use that result in a javascript variable - the form request is here:
<form id="Latest" method="POST" action="https://creator.zoho.com/api/xml/my-company-culture/view/PageFeed_Report">
<input type="hidden" name ="authtoken" value="**********************">
<input type="hidden" name ="scope" id="scope" value="creatorapi">
<input type="submit" value="View Records">
</form>
I can auto submit the form using this
<script type="text/javascript">
document.getElementById("Latest").submit();
</script>
Which recovers a the result - but I want to assign this result to a javascript variable and use it in a following piece of code (within the same frame).
I am new to this, so please be gentle! Any help appreciated.
This is easily done with jQuery:
<form id="Latest">
<input type="hidden" name ="authtoken" value="**********************">
<input type="hidden" name ="scope" id="scope" value="creatorapi">
<input type="submit" value="View Records">
</form>
<div id="result"></div>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$('#Latest').submit(function(event) {
// Stop form from submitting normally
event.preventDefault();
var url = "https://creator.zoho.com/api/xml/my-company-culture/view/PageFeed_Report";
// Get some values from elements on the page:
var $form = $( this );
var authtokenData = $('#authtoken').attr('value');
var scopeData = $('#scope').attr('value');
// Send the data using post
var posting = $.post( url,
{
authtoken: authtokenData,
scope: scopeData
}
);
// Put the results in a div
posting.done(function( data ) {
// empty results div
$("#result").empty()
// write POST result to results div
$("#result").append("<p>" + data + "</p>);
});
});
</script>

Response from AJAX request is only displayed once

I've got some code that sends an ajax request when a form is being submitted. This works the first time the form is submitted (it's a search module), but only once. I've added an effect to highlight the table when data is returned, and you can only see it once (the data changes only once as well).
When I look at the response in the chrome dev tools, I can see it contains the data of the new search query but this isn't shown. Why can I only display results once?
JS:
$(function () {
// Creates an ajax request upon search form submit
var ajaxFormSubmit = function () {
var $form = $(this);
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var $target = $($form.attr("data-nn-target"));
var $newHtml = $(data);
$target.replaceWith($newHtml);
$newHtml.effect("highlight");
});
// Prevent default action
return false;
};
$("form[data-nn-ajax='true']").submit(ajaxFormSubmit);
});
HTML:
<form method="GET" action="#Url.Action("Index", "Show")" data-nn-ajax="true" data-nn-target="#contentlist" class="form-search">
<div class="input-append mysearch">
<input type="search" class="span5 search-query" name="query" data-nn-autocomplete="#Url.Action("AutoComplete")" />
<input type="submit" class="btn" value="Search" />
</div>
</form>
<div id="contentlist">
#Html.Partial("_Shows", Model)
</div>
I think you should use html() instead of replaceWith() method:
$target.html($newHtml);
just an idea... try
$target.html(data);
instead of
$target.replaceWith($newHtml);
By replaceWith, you might actually remove the div that you want to fill your content in. Then, the second time, it doesnt find the div to insert the content into.

Jquery post function not working with two forms and two post requests

I was trying to add a second form to a javascript/jquery script that I wrote, however, when i implemented and began testing it, when I would try to send the firm form via a jquery post request, it would instead send a get request. I know that this has to do with the second form, because commenting the script out for the second form makes the site work again. Hopefully a pair of fresh eyes can help!(the loadpage function works as well)
The register function seems to be where the problem is:
//when the user first goes to the page
$(document).ready(function(){
var user = $("#username");
var pass = $("#password");
var submit = $("#submit");
//both of these methods work, I'm not sure if one is better than the other
//$("#submitbutton").click(function(event){
$("#loginform").on('submit', function(event){
event.preventDefault();
$('.loginerror').remove();
$.post("login.php", {username:user.val(), password:pass.val()}, function(data){
if(!data)
{
$("#login").append("<h3 class='loginerror'>Incorrect Username or Password</h3>");
}
else
{
loadpage();
}
}, "json");
});
//if the user clicks the username prompt him with the login div
$("#registerbutton").click(function(event){
register();
});
});
function register()
{
$("#login").hide("slow");
$("#registerdiv").css("display", "block");
//initiate some variables
var regusername = $("#regusername");
var reg1password = $("#reg1password");
var reg2password = $("#reg2password");
var regemail = $("#regemail");
var regfirstname = $("#regfirstname");
var reglastname = $("#reglastname");
//TODO: check to make sure form is filled out properly
$("#registerform").on('submit', function(event){
event.preventDefault();
//send post request
$.post("register.php", {regusername:regusername.val(), password1:reg1password.val(), password2:reg2password.val(), email:regemail.val(), firstname:regfirstname.val(), lastname:reglastname.val()}, function(data){
if(!data)
$("#registerdiv").append("<h3> class='loginerror'>Server error, retry</h3>");
else
$("#registerdiv").hide("slow");
$("#loginiv").slidedown("slow");
}, "json");
}
And here's the HTML with the two forms:
<body>
<Div id="welcome"> Welcome </div>
<Div id="login">
<br><br><h2>Welcome to QuotesLib</h2>
<br><br><br><form id="loginform"> Username:
<input type = "text" name = "username" id ="username"> <br> Password:
<input type = "password" name = "password" id = "password"> <br>
<input type = "submit" name="submitbutton" id="submitbutton" class = "bluebutton">
</form>
<form><br><br><br>Don't have an account yet?<br><button id="registerbutton" name="registerbutton" href="register.html">Register Now</button>
</Div>
<Div id="registerdiv">
<br><br><h2>Sign Up For QuotesLib</h2>
<br><form id="registerform"> Username:
<input type ="text" id="regusername"> <br> Password:
<input type ="password" id="reg1password"> <br> Repeat Password:
<input type ="password" id="reg2password"> <br> First Name:
<input type ="text" id="regfirstname"> <br> Last Name:
<input type ="text" id="reglastname"> <br> email:
<input type ="text" id="regEmail"> <br>
<input type ="submit" id ="registersubmitbutton">
<br> </form>
</Div>
It would be super helpful if someone could give me an answer to this question!
$("#registerdiv").append("<h3> class='loginerror'>Server error, retry</h3>");
should be
$("#registerdiv").append("<h3 class='loginerror'>Server error, retry</h3>");
see the difference:
<h3>... and <h3 ...
The code has some mistakes,
first,
<form><br><br><br>Don't have an account yet?<br><button id="registerbutton" name="registerbutton" href="register.html">Register Now</button>
You are having a form open tag but not a close tag, the form tag even not needed for this button, and that was the main reason for the problem
second, the end of the JS code,
}, "json");
}
should be
}, "json");
});
}​
I'm not sure whether you missed while copying,
Third,
The <h3> tag within the append method, though it is not the matter for the problem you are having.
It is better to use some text editors which hi-lights the code open, end tags, braces.
Here the working code

Categories