JQuery - How to submit dynamically created form? - ajax

I am having trouble when submitting a dynamically created form.
This is how I create the form after a radio button is checked:
$(document).ready(function(){
$('input[name$="rad-tweet"]').click(function(){
var radio_value = $(this).val();
if(radio_value==='hash') {
$('#mainform2').empty();
$('#mainform2').remove();
$('#radio-buttons').after('<form action="" id="mainform" method="POST" ></form>');
$('#mainform').append('<label class="label" for="Location" > Location</label>'+
'<input class ="text-box" type="text" name="Location" id="Location"/>'+
'<label class="label" for="Since" >Since</label>'+
'<input class ="text-box" type="text" name="Since" id="Since" />'+
'<select name="Time" id="Time" style="width:80px;">'+
'<option value="MINUTE">Minute(s)</option>'+
'<option value="HOUR">Hour(s)</option>'+
'<option value="DAY">Day(s)</option>'+
'<option value="WEEK">Week</option>'+
'</select>'+
'<label class="label" for="Time" >Ago </label>'+
'<label class="label" for="Limit" >Up to</label>'+
'<input class ="text-box" type="text" name="Limit" id="Limit" />'+
'<label class="label" for="Limit" >Results </label>'+
'<input class ="submit-button" type="submit" id="submitButton" value="Get Hashtags" style="width:95px;" />');
}
else if(radio_value==='trends') {
$('#mainform').empty();
$('#mainform').remove();
$('#radio-buttons').after('<form action="" id="mainform2" method="POST" ></div>');
$('#mainform2').append('<label class="label" for="Location" > Location </label>'+
'<input class ="text-box" type="text" name="Location" id="Location"/> '+
'<input class ="submit-button" type="submit" id="submitButton" value="Get Trends" style="width:95px;" />');
}
});
This code follows the code above, and I try to make an XHR request to a php script when the from #mainform is submitted.
$('#mainform').submit(function(){
if(runProgram()){
//Loading div. To be hidden upon sucessful ajax. Disable submit button
document.getElementById("Loading").style.visibility="visible";
document.getElementById("submitButton").disabled=true;
$.ajax({
url: "indexProgram.php",
type: 'POST',
data: $(this).serialize(),
success:function(data, textStatus, jqXHR){
//take away loading div and reenable submit.
document.getElementById("Loading").style.visibility="hidden";
document.getElementById("submitButton").disabled=false;
var arr = data.split(",-,");
BeginTime = arr[3];
if(!(/^\s*$/).test(arr[0])) {
var lookAt = ge.createLookAt('');
data_array = arr[4].split("|");
alert(data);
// Set the position values.
lookAt.setLatitude(parseFloat(arr[0]));
lookAt.setLongitude(parseFloat(arr[1]));
//lookAt.setLatitude(43.653226);
//lookAt.setLongitude(-79.3831843);
lookAt.setTilt(50.0);
lookAt.setRange(9000.0); //default is 0.0
// Update the view in Google Earth.
ge.getView().setAbstractView(lookAt);
}
else{
alert("Location does not exist. Please try again with an existing Location")
}
},
complete : function(){
modDom(data_array);
}
});
}
//doesn't refresh pag
return false;
});
});
Before, when the form was static, the ajax xhr call completed successfully, now it doesn't.
I have been reading about what the issue might be, and about how the form is not in the DOM, and to use .live, and I have tried, but it still does not work.
Could somebody please help me out?

Your problem is that in the first place your document loads then jquery code is loaded. Then you create a dynamically created form which jquery does not get to post. Instead remove $('document').ready() and put a function let suppose submit_form(). call this form on the click event of you form and your form will be submitted. Another approach is that when dynamically you are creating form element assign them all an class. Before submitting the form loop through with this class to get all values and append the with the serialize form to submit.

Your answer lies in the depths of the Live event handler for jquery.
http://docs.jquery.com/Events/live
I don't really remember all that well, but i think its got to do something with the click event handler not binding dynamic elements, but the Live event handler does it, so try using that.
UPDATE
Sorry, its seem that the Live() event handler has been deprecated in the latest jQuery.
As of jQuery 1.7, the .live() method is deprecated. Use .on() to
attach event handlers. Users of older versions of jQuery should use
.delegate() in preference to .live().
The alternative is to use the jquery On() event handler.
http://api.jquery.com/on/
EXAMPLE USAGE
$("#dataTable tbody tr").on("click", function(event){
alert($(this).text());
});

Related

Play framework write Action with Ok(...) that doesn't load new page

Play framework 2.4.x. A button is pressed on my home page that executes some code via Ajax, and returns its results beneath the button without loading a new page. The results wait for a user to input some text in a field and press "submit". Those results Look like this:
<li class="item">
<div>
<h3>Email: </h3>
<a>#email.tail.init</a>
<h3>Name: </h3>
<a>#name</a>
</div>
<div>
<h3>Linkedin: </h3>
<form class="linkedinForm" action="#routes.Application.createLinkedin" method="POST">
<input type="number" class="id" name="id" value="#id" readonly>
<input type="text" class="email" name="email" value="#email" />
<input type="text" class="emailsecondary" name="emailsecondary" value="" />
<input type="text" class="name" name="email" value="#name" />
<input type="text" class="linkedin" name="linkedin" value="" />
<input type="submit" value="submit" class="hideme"/>
</form>
</div>
<div>
<form action="#routes.Application.delete(id)" method="POST">
<input type="submit" value="delete" />
</form>
</div>
</li>
Along with some jquery that slides up a li after submission:
$(document).ready(function(){
$(".hideme").click(function(){
$(this).closest('li.item').slideUp();
});
});
However, since a form POST goes inside an Action that must a return an Ok(...) or Redirect(...) I can't get the page to not reload or redirect. Right now my Action looks like this (which doesn't compile):
newLinkedinForm.bindFromRequest.fold(
errors => {
Ok("didnt work" +errors)
},
linkedin => {
addLinkedin(linkedin.id, linkedin.url, linkedin.email, linkedin.emailsecondary, linkedin.name)
if (checkURL(linkedin.url)) {
linkedinParse ! Linkedin(linkedin.id, linkedin.url, linkedin.email, linkedin.emailsecondary, linkedin.name)
Ok(views.html.index)
}else{
Ok(views.html.index)
}
}
)
Is it possible to return Ok(...) without redirecting or reloading? If not how would you do a form POST while staying on the same page?
EDIT: Here is my attempt at handling form submission with jquery so far:
$(document).ready(function(){
$(".linkedinForm").submit(function( event ) {
var formData = {
'id' : $('input[name=id]').val(),
'name' : $('input[name=name]').val(),
'email' : $('input[name=email']).val(),
'emailsecondary' : $('input[name=emailsecondary]').val(),
'url' : $('input[name=url]').val()
};
jsRoutes.controllers.Application.createLinkedin.ajax({
type :'POST',
data : formData
})
.done(function(data) {
console.log(data);
});
.fail(function(data) {
console.log(data);
});
event.preventDefault();
};
});
This is an issue with the browser's behavior on form submission, not any of Play's doing. You can get around it by changing the behavior of the form when the user clicks submit.
You will first want to attach a listener to the form's submission. You can use jQuery for this. Then, in that handler, post the data yourself and call .preventDefault() on the event. Since your javascript is now in charge of the POST, you can process the data yourself and update your page's HTML rather than reloading the page.
What you need is use ajax to submit a form, check this: Submitting HTML form using Jquery AJAX
In your case, you can get the form object via var form = $(this), and then start a ajax with data from the form by form.serialize()
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
alert('ok');
}
});
In order to accomplish this task, i had to use play's javascriptRouting
This question's answer helped a lot.
I'm not experienced with jquery so writing that correctly was difficult. For those that find this, here is my final jquery that worked:
$(document).ready(function(){
$("div#results").on("click", ".hideme", function(event) {
var $form = $(this).closest("form");
var id = $form.find("input[name='id']").val();
var name = $form.find("input[name='name']").val();
var email = $form.find("input[name='email']").val();
var emailsecondary = $form.find("input[name='emailsecondary']").val();
var url = $form.find("input[name='url']").val();
$.ajax(jsRoutes.controllers.Application.createLinkedin(id, name, email, emailsecondary, url))
.done(function(data) {
console.log(data);
$form.closest('li.item').slideUp()
})
.fail(function(data) {
console.log(data);
});
});
});
Note that my submit button was class="hideme", the div that gets filled with results from the DB was div#results and the forms were contained within li's that were class="item". So what this jquery is doing is attaching a listener to the static div that is always there:
<div id="results">
It waits for an element with class="hideme" to get clicked. When it gets clicked it grabs the data from the closest form element then sends that data to my controller via ajax. If the send is successful, it takes that form, looks for the closest li and does a .slideUp()
Hope this helps

Automate AJAXed forms with Jquery

I want to improve my website and figured out a good way to do it was by submitting forms via AJAX. But, I have so many forms that it would be inpractical to do $('#formx').submit(). I was wondering if there was a way to do this automatically by making an universal markup like;
<form class="ajax_form" meta-submit="ajax/pagename.php">
<input type="text" name="inputx" value="x_value">
<input type="text" name="inputy" value="y_value">
</form>
And have this submit to ajax/pagename.php, where it automatically includes inputx and inputy?
This would not only save me a lot of time but also a lot of lines of code to be written.
First question so I hope it's not a stupid one :)
Something like this should work for all forms. It uses jQuery - is this available in your project? This specific code chunk hasn't been tested per say, but I use this method all the time. It is a wonderful time saver. Notice I changed meta-submit to data-submit so that its value can be fetched using $('.elemenet_class').data('submit');
HTML
<!-- NOTE: All Form items must have a unique 'name' attribute -->
<form action="javascript:void(0);" class="ajax_form" data-submit="ajax/pagename.php">
<input type="text" name="inputx" value="x_value">
<input type="text" name="inputy" value="y_value">
<input type="submit" value="go" />
</form>
JavaScript
$('.ajax_form').submit(function(e){
var path = $(this).attr('data-submit'); //Path to Action
var data = $(this).serialize(); //Form Data
$.post(path, {data:data}, function(obj){
});
return false;
})
PHP
//DEBUGGING CODE
//var_dump($_POST);
//die(null);
$data = $_POST['data'];
$inputx = $data['inputx'];
$inputy = $data['inputy'];
you can create ajax fot text boxes so that it can update to database whenever change the focus from it.
<form id="ajax_form1">
<fieldset>
<input type="text" id="inputx" value="x_value" />
<input type="text" id="inputy" value="y_value" />
</fieldset>
</form>
<script>
$(document).ready(function()
{
$("form#ajax_form1").find(":input").change(function()
{
var field_name=$(this).attr("id");
var field_val=$(this).val();
var params ={ param1:field_name, param2:field_val };
$.ajax({ url: "ajax/pagename.php",
dataType: "json",
data: params,
success: setResult
});
});
});
</script>

Clicking on POST link on page desn't not calling the onchange ajax event to save the modified field

Saving a field on change ajax to server works when click outside the box but doesn't change the value if click on any POST link on the page immediately after changing the value.
Below is the code html:
<input type="text" name="title" id="title" size="40" value="${fieldValue}" onchange="doAJAXSubmit(this.name, this.value)"/>
JS:
function doAJAXSubmit(fieldSaved, fieldValue)
{
alert(fieldSaved);
var url = "<c:url value="/home/home.jsp"/>";
url = url+fieldSaved+ "=" + fieldValue;
new Request({url: url}).send();
}
have you tried the document.ready .change binding from jquery
$('#title').change(function() {
alert(fieldSaved);
var url = "<c:url value="/cart/view_cart.jspa"/>";
url = url+fieldSaved+ "=" + fieldValue;
new Request({url: url}).send();
});
Without Jquery do the following:
Then change your code to the following:
using onkeyup
<input type="text" name="title" id="title" size="40" value="${fieldValue}" onkeyup="doAJAXSubmit(this.name, this.value)"/>

Ajax form perfect until inside another page

I have a page which uses ajax to submit a comment form, add it to a db, then redisplay the page, hopefully without reloading the page its on.
If I access the script on it's own it works great, yet when I load it into another page it doesn't add the data and also refreshes the page on submit, which I want to avoid, which is the whole point of doing things this way.
Anyway, here's how I load the page:
<div id="wall_comments" class="msgs_holder"></div>
<script type="text/javascript">
$('#wall_comments').load('/pages/comment.php', { wl_id:"<?=$wl_id?>" });
</script>
and then the page itself with jquery code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<div style="width:100%; overflow:auto;">
<form method=post>
<input type="text" class="inp" name="comment" id="comment">
<input type=submit value="do it" name="action" onclick="update()">
<input type=hidden name="wl_id" value="<?=$_REQUEST[wl_id]?>" id="wl_id">
<input type=hidden name="user_id" value="<?=$userfromcookie?>" id="user_id">
</form>
</div>
<script type="text/javascript">
function update(){
var wl_idVal = $("#wl_id").val();
var commentVal = $("#comment").val();
var user_idVal = $("#user_id").val();
$.ajax({
type: "POST",
url: "/pages/comment.php",
cache: false,
data: { submit: "", wl_id: wi_idVal, comment: commentVal, user_id: user_idVal }
});
}
</script>
And finally enter info into db (I know this should be mysqli and it will be)
if(isset($_POST['action'])){
$wl_id = mysql_real_escape_string($_POST['wl_id']);
$comment = mysql_real_escape_string($_POST['comment']);
$user_id = mysql_real_escape_string($_POST['user_id']);
$addcomment = mysql_query("insert into list_wall (
event_id,
user_id,
comment
) VALUES (
'$wl_id',
'$user_id',
'$comment'
) ",$db);
if(!$addcomment) { echo 'result error add comment'; echo mysql_error(); exit; } // debug
}
The problem is when you click the submit button, the page is submitted and the function update couldn't work. You have to cancel the default submit mechanism by using return false;
<input type=submit value="do it" name="action" onclick="update() return false;">
Another thing.
The onclick on the submitbutton will not work as excpected if the submit is caused without clicking the button.
For example mobile safari on iPhone can submit forms directly without triggering the button.
If you add UmairP's version of the onclick to the form element as an onsubmit method you should get the same result on every platform as far as I know.
You can see more details on iPhone forms in my own question on another issue.
How can I prevent the Go button on iPad/iPhone from posting the form

Submitting form into a div

Can anyone tell me why this is not working or give me another way into doing what I want.
I have a form on a page when click submit I want it to process into add.php and for it to open up in a DIV called right.
Form page
<script>
$("#Submit").click(function() {
var url = "add.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#myForm").serialize(), // serializes the form's elements.
success: function(html){ $("#right").html(html); }
});
return false; // avoid to execute the actual submit of the form.
});
</script>
</head>
<body>
<form action="add.php" method="post" enctype="multipart/form-data" id ="myForm">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name = "email"><br>
Phone: <input type="text" name = "phone"><br>
Photo: <input type="file" name="photo"><br>
<input type="submit" value="Upload">
</form>
</body>
Now if I add action to form to direct it to add.php all works fine so other script is ok yet when i do it this way,nothing happens it does not load add.php into the 'right' div like I want it to.
Anyone got any suggestions?
Your $("#Submit") selector does not match anything (the submit button has no id and is defined after that bind attempt), so the function is not bound to any event, thus never executed.
Instead the form acts the way it should: upon submit it posts its content to the url specified in the 'action' attribute. This is what happens, that div is never touched.
you have to go back to understand how jquery selectors work. How to bind a function to an event.
Is this your exact code? There are a few issues:
$("#Submit").click should be wrapped in a document ready
handler so it doesnt run before the page has actually loaded.
There is no button that matches #Submit
There is no div that matches #right
Try
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#Submit").click(function() {
var url = "add.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#myForm").serialize(), // serializes the form's elements.
success: function(html){ $("#right").html(html); }
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
</head>
<body>
<div id="right">
</div>
<form action="add.php" method="post" enctype="multipart/form-data" id ="myForm">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name = "email"><br>
Phone: <input type="text" name = "phone"><br>
Photo: <input type="file" name="photo"><br>
<input type="submit" value="Upload" id="Submit">
</form>
you have to create on div in body tag which id will be right and
<input id="submit" type="submit" name="upload" >
add new div in body tag like this
<div id="right"></div>

Resources