create form dynamically and submit it - javascript

So I have a jQuery plugin I wrote below, in plugin.js. I want to be able to also submit the form via JSON/AJAX every time it's created.
(function ( $ ) {
$.fn.create = function() {
var form = '<div id="form" class="container">';
form += '<div>User Login</div>';
form += '<form action="/create/one" method="post">';
form += '<input type="text" name="name" placeholder="name">';
form += '<input type="email" name="email" placeholder="email">';
form += '<button type="submit">Login</button>';
form += '</form>';
form += '</div>';
$('#form').submit(function(e)
{
var postData = form.find('form').serializeArray();
if(postData.name === "someREGEXstring" || postData.email === "someREGEXstring") {
console.log("empty inputs not cool");
}
var formURL = $('form').attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault(); //STOP default action
});
$('#form').submit(); //SUBMIT FORM
return this.append(form);
};
}( jQuery ));
in HTML view
<div id="newForm"></div>
<script>
$(document).ready(function(){
$("#newForm").create();
});
</script>
Is this the correct way to make this or should I:
Create a another namespace under the same file for the AJAX portion
Create another namespace under a different file the AJAX portion

If the question is purely about how to arrange the code, I would suggest you pull the form template out of the code completely and make your plugin more flexible.
Option 1. Create the form as a template in the page and pass the
template selector to plugin as an option
Option 2: Pass the template to your plugin
Here is an example of the first technique: http://jsfiddle.net/TrueBlueAussie/c8bmw/7/
Template in HTML:
<script id="template" type="template">
<div id="form" class="container">
<div>User Login</div>
<form action="/create/one" method="post"/>
<input type="text" name="name" placeholder="name"/>
<input type="email" name="email" placeholder="email"/>
<button type="submit">Login</button>
</form>
</div>
</script>
Create with:
$(document.body).create('#template');
And plugin simplified to:
(function ( $ ) {
$.fn.create = function(template) {
form = $($(template).text());
form.submit(function(e) {
// This is the actual form object now
var $form = $(this).find('form');
// Test contents of form here
// If values are correct proceed with Ajax call
var postData = $form.serializeArray();
var formURL = $form.attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault(); // Stop default action
});
return this.append(form);
};
}( jQuery ));
Now your plugin code will work with any form.
Based on your comment I have removed the automatic submit of the form, as that made no sense

This should work:
(function ( $ ) {
$.fn.create = function() {
var form = '<div id="form" class="container">';
form += '<div>User Login</div>';
form += '<form action="/create/one" method="post">';
form += '<input type="text" name="name" placeholder="name">';
form += '<input type="email" name="email" placeholder="email">';
form += '<button type="submit">Login</button>';
form += '</form>';
form += '</div>';
form = $(form);
form.submit(function(e) {
var postData = form.find('form').serializeArray();
var formURL = form.find('form').attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
},
error: function(jqXHR, textStatus, errorThrown)
{
}
});
e.preventDefault(); //STOP default action
});
form.submit(); //SUBMIT FORM
return this.append(form);
};
}( jQuery ));
Here is a demo in JSFiddle.
What is fixed:
form = $(form) is used in order to create the DOM elements based on the form string.
Change the way postData, formURL are initialized.

<div id="#newForm"></div>
should be
<div id="newForm"></div>
to load this form element

I have some chages, like:
$('#form').submit(function(e) should be $(form).submit(function(e) as variable form contains all the HTML of form wrapped within DIV.
in the submit of form, $(this) will refer to the form element itself.
Here is the modified code:
(function ($) {
$.fn.create = function () {
var formContainer = $("<div />", {
id : "form",
class : "container"
}).append("<div>User Login</div>");
var form = $("<form />", {
action: "/create/one",
method : "post",
submit : function(e){
var actionUrl = $(this).attr("action");
alert(actionUrl); // just to check if this is working or not
$.ajax({
url : actionUrl,
type : "POST",
data : $(this).serializeArray(),
success : function (data, textStatus, jqXHR) {},
error : function (jqXHR, textStatus, errorThrown) {}
});
e.preventDefault();
}
})
.append('<input type="text" name="name" placeholder="name"><input type="email" name="email" placeholder="email"><button type="submit">Login</button>')
.appendTo(formContainer);
return this.append(formContainer);
};
}(jQuery));
$("#test").create();
HTML for testing:
<div id="test"></div>
JS fiddle: http://jsfiddle.net/ashishanexpert/y99mt/2/
I have created the HTML nodes via jquery instead of just HTML string. attaching events to nodes is easier than converting string to HTML first and then attaching event to them. Hope you like it.

Related

Pushing array of values from a form into Google Spreadsheet comes through as 'undefined'

I have a form with text fields which the user can "Add New" by clicking a button. These fields share the same name. I'm trying pass the values into Google Spreadsheets, but the values all come through as 'undefined' with the following code, even though console.log prints the answers as strings which look okay to me.
So if the user for example submits 3 separate entries for SUNDAY_NOTES[], all 3 strings should end up in one cell broken up by new lines, but instead I'm just getting "undefined".
<form action="" method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]"> // the user can create multiples of these ^ for each day of the week
<input type="submit" id="submit" />
</form>
<script>
$(document).ready(function() {
var $form = $('form#timesheet'),
url = 'https://script.google.com/macros/s/AKf45XRaA/exec'
$('#submit').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeArray().map((e) => {
return e.value
}).join('\n')
});
})
});
</script>
Your code works. In the snippet below I am storing the data split by \n in a variable and logging it. You can check the output.
Although your JS is correct, I suspect that you actually want to be using a different HTTP method. Perhaps POST or PUT? I can't be specific as you have not said which API endpoint you are using.
$(document).ready(function() {
var $form = $('form#timesheet'),
url = 'https://script.google.com/macros/s/AKf45XRaA/exec'
$('#submit').on('click', function(e) {
e.preventDefault();
var data = $form.serializeArray().map((e) => {
return e.value
}).join('\n');
console.log(data);
var jqxhr = $.ajax({
url: url,
method: "POST",
dataType: "json",
data: data
}).done(response => {
console.log(response);
}).fail((jqXHR, textStatus) => {
console.log("Request failed: " + textStatus);
});
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="submit" id="submit" />
</form>
remove the [] from your input's name as this is needed if you want to receive an array in the server side, then create a function that groups the values according to the inouts' keys :
function group(arr) {
var tempArr = [];
arr.forEach(function(e) {
var tempObj = tempArr.find(function(a) { return a.name == e.name });
if (!tempObj)
tempArr.push(e)
else
tempArr[tempArr.indexOf(tempObj)].value += ', ' + e.value;
});
return tempArr;
}
and use it like :
$('#submit').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: group($form.serializeArray()),
//... rest of your code
this will keep the original structure that works,
here's a snippet :
var $form = $('form#timesheet');
function group(arr) {
var tempArr = [];
arr.forEach(function(e) {
var tempObj = tempArr.find(function(a) { return a.name == e.name });
if (!tempObj)
tempArr.push(e)
else
tempArr[tempArr.indexOf(tempObj)].value += ', ' + e.value;
});
return tempArr;
}
$form.submit(function(e) {
e.preventDefault();
var grouped = group($form.serializeArray());
console.log(JSON.stringify(grouped))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES"><br />
<input type="text" name="SUNDAY_NOTES"> // user can click a button to keep adding more SUNDAY_NOTES fields
<input type="text" name="MONDAY_NOTES"> // and so forth
<input type="submit" id="submit" />
</form>

Submit form using ajax and pass the value submitted to new page

i have form that need the previous value inserted....i'm using ajax,but the success: function(data) wont let me moved to the next page...
here is my code
HTML
<form>
<input type="text" name="id_1" id="id_1>
<input type="text" name="id_2" id="id_2>
<input type="text" name="id_3" id="id_3>
<button type="button" onclick="next();">
</form>
<div id="tabelna"></div>
JQuery
var id_1 = $('#id_1').val();
var id_2= $('#id_2').val();
var id_3= $('#id_3').val();
var datana = 'id_1='+id_1+'&id_2='+id_2+'&id_3='+id_3;
var urlna="<?=base_url()?>something/something/something";
$.ajax({
type: 'POST',
url: urlna,
data: datana,
beforeSend:function(data){
},
message:"<center>><h3>Loading Data. . .</h3></center>"
});
},
error: function(data) {
jAlert('Failed');
},
success: function(data) {
load();
}
})
return false;
}
function load()
{
$('#tabelna').load('<?=base_url()?>something/something/something') (This is my mistake)
}
CONTROLLER
function set_value()
{
extract($_POST);
$d['id1'] = $this-db->query('SELECT * FROM TBL1 where id='.$id_1);
$d['id2'] = $this-db->query('SELECT * FROM TBL2 where id='.$id_2);
$d['id3'] = $this-db->query('SELECT * FROM TBL3 where id='.$id_3);
$this->load->view('something/v_add',$d); (this is my mistake)
}
How can i pass the submitted value to the controller and shows new form ?
we can call controller function using window.location
function load()
{
window.location.href = "<?php echo site_url('controller_d/login/admin_link_delete_user');?>";
}

How to use ajax in PHP foreach?

I have a form with two select html tags and an input submit. To populate the value of option tags and to display the equivalent values of selected option tag, I use PHP, please see snippet below.
Now, I want to use AJAX using JS to avoid the reloading of the browser when the user clicked the button. But I don't know how. Please help me
Here's the link
Snippet:
if(isset($_POST['mall_list'])){
$mall_list= $_POST['mall_list'];
$malls= $wpdb->get_results($wpdb->prepare("SELECT stores FROM tablename WHERE malls = '" . $mall_list. "' GROUP BY stores ORDER BY stores", OBJECT));
echo '<div class="\record\">';
foreach ($malls as $record){
echo '<div>' . $record->stores . '</div>';
}
echo '</div>';
} elseif(isset($_POST['store_list'])){
$store_list= $_POST['store_list'];
$stores= $wpdb->get_results($wpdb->prepare("SELECT malls FROM tablename WHERE stores= '" . $store_list. "' GROUP BY malls ORDER BY malls", OBJECT));
echo '<div class="\record\">';
foreach ($stores as $record){
echo '<div>' . $record->malls. '</div>';
}
echo '</div>';
}
HTML
<form name="ajaxform" id="ajaxform" action="ajax-form-submit.php" method="POST">
First Name: <input type="text" name="fname" value =""/> <br/>
Last Name: <input type="text" name="lname" value ="" /> <br/>
Email : <input type="text" name="email" value=""/> <br/>
</form>
JAVASCRIPT
//callback handler for form submit
$("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
//data: return data from server
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#ajaxform").submit(); //Submit the FORM
if you want to post data through ajax jquery. this code work for you.
$( "form" ).submit(function( event ) {
event.preventDefault();
$.ajax({
type: "POST",
url: "your post url",
data: $('#yourformname').serialize(),
success: function (data)
{
}
});
});
javascript
$("#form").submit(function(e){
var data = $(this).serialize();
var url = $(this).attr("action");
$.post({
url,
data,
function(res)
{
if(res.code == 0)
{
//success
//code somthing when the server response
alert(res.message);
}
}
});
})
server
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
#is ajax request
# code your business logic
#response data
$response = [
'code' => 0,
'message' => 'success',
'data' => []
];
echo json_encode($response);exit;
} else {
#is normal request
}

jQuery validation submitHandler not work in $.ajax post form data

I have Send data using $.ajax and validation with jQuery validation plugin like this :
<div class="" id="ajax-form-msg1"></div>
<form id="myform" action="load.php">
<input type="input" name="name" id="name" value="" />
<input type="hidden" name="csrf_token" id="my_token" value="MkO89FgtRF^&5fg#547#d6fghBgf5" />
<button type="submit" name="submit" id="ajax-1">Send</button>
</form>
JS:
jQuery(document).ready(function ($) {
$('#myform').validate({
rules: {
name: {
required: true,
rangelength: [4, 20],
},
},
submitHandler: function (form) {
$("#ajax-1").click(function (e) {
e.preventDefault(); // avoid submitting the form here
$("#ajax-form-msg1").html("<img src='http://www.drogbaster.it/loading/loading25.gif'>");
var formData = $("#myform").serialize();
var URL = $("#myform").attr("action");
$.ajax({
url: URL,
type: "POST",
data: formData,
crossDomain: true,
async: false
}).done(function (data, textStatus, jqXHR) {
if (data == "yes") {
$("#ajax-form-msg1").html(' < div class = "alert alert-success" > ' + data + ' < /div>');
$("#form-content").modal('show');
$(".contact-form").slideUp();
} else {
$("#ajax-form-msg1").html('' + data + '');
}
}).fail(function (jqXHR, textStatus, errorThrown) {
$("#ajax-form-msg1").html(' < div class = "alert alert-danger" >AJAX Request Failed < br / > textStatus = ' + textStatus + ', errorThrown = ' + errorThrown + ' < /code></pre > ');
});
});
}
});
});
In action my form validate using jQuery validation but after validation not submit and not send data.
how do fix this problem?!
DEMO HERE
The submitHandler is expecting a submit and you have a click event inside it and then an ajax call.
If you have a button type="submit" inside a form you don't even need a click event, the plugin will do the validation automatically. So just make the ajax call inside the submitHandler.
If you need to bind the action to a button using the click event, the proper approach should be something like this:
$('#button').click(function(){
var form = $('#myform').validate({...}); #store the validator obj
if (form.is_valid()){
// submit using ajax
} else {
// dont do anything
}
});
Call form.submit() at the end of your done function.
See: http://jqueryvalidation.org/validate/
Also, you do not need $("#ajax-1").click() because the submitHandler will be called automatically when you click on that button anyways. You can test this yourself by putting a console.log as the first line of submitHandler. Then fill out the form and press the button. See if it prints out your log message.
In submitHandler you are handling the submit , then again why did you write click event?
Here is the fix.
jQuery(document).ready(function($) {
$('#myform').validate({
rules: {
name: {
required: true,
rangelength: [2, 20],
},
},
submitHandler: function(a, e) {
//a is form object and e is event
e.preventDefault(); // avoid submitting the form here
$("#ajax-form-msg1").html("<img src='http://www.drogbaster.it/loading/loading25.gif'>");
var formData = $("#myform").serialize();
var URL = $("#myform").attr("action");
$.ajax({
url: URL,
type: "POST",
data: formData,
crossDomain: true,
async: false,
success: function(data) {
console.log(data)
},
error: function(err) {
console.log(err)
}
}).done(function(data, textStatus, jqXHR) {
if (data == "yes") {
$("#ajax-form-msg1").html(' < div class = "alert alert-success" > ' + data + ' < /div>');
$("#form-content").modal('show');
$(".contact-form").slideUp();
} else {
$("#ajax-form-msg1").html('' + data + '');
}
}).fail(function(jqXHR, textStatus, errorThrown) {
$("#ajax-form-msg1").html(' < div class = "alert alert-danger" >AJAX Request Failed < br / > textStatus = ' + textStatus + ', errorThrown = ' + errorThrown + ' < /code></pre > ');
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.validation/1.14.0/jquery.validate.min.js"></script>
<form id="myform" action="load.php">
<input type="input" name="name" id="name" value="" />
<input type="hidden" name="csrf_token" id="my_token" value="MkO89FgtRF^&5fg#547#d6fghBgf5" />
<button type="submit" name="submit" id="ajax-1">Send</button>
</form>
Use success and error call backs to get data or error messages.
Note: Here (In StackOverflow) you will get 404 Page Not Found error when you submit. So try in your local.

No Data Posted in a form

I use a form which sends data with a POST method to a php file via AJAX. Everything is ok and I can see the results in the html table in its id div name. But now this very same table contains input fields (second form) with the same method. All ids and names are different, I can see the fields values with
alert( $("input[name=id]").val() );';
Am I missing something ?
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<form name="ajaxform" id="ajaxform" action="edit.php" method="POST">
<select name="user" id="simple-post" onchange="this.value.submit()">
<option value="">Select a person:</option>
<option value="0">John</option>
<option value="1">Peter</option>
<option value="1">Heinrich</option>
</select>
</form>
<div id="simple-msg">
</div>
<script>
$(document).ready(function()
{
$("#simple-post").click(function()
{
$("#ajaxform").submit(function(e)
{
$("#simple-msg").html("<img src='loading.gif'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
$("#simple-msg").html('<pre><code class="prettyprint">'+data+'</code></pre>');
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#simple-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
$("#ajaxform").submit(); //SUBMIT FORM
});
});
</script>
</body>
Now the edit.php page
<?php
$json_a=json_decode(json_encode($_POST),true);
$output=array();
$i=0;
foreach ($json_a as $key => $value){
echo $key . ':' . $value; // peut-ĂȘtre branchĂ©!
$output[$i]= $value;
$i++;
}
$array_user=array();
$array_user[0]=$output[0];
$array_user[1] ="Yes";
$array_user[2] ="mypass";
echo '<form name="ajaxform1" id="ajaxform1" action="SQL_user.php" method="POST">
';
echo '<input type="text" name="id" size="3" value="' .$array_user[0]. '"/>';
echo '<input type="text" name="online" size="3" value="' .$array_user[1]. '"/>';
echo '<input type="text" name="password" size="20" value="' .$array_user[2]. '"/>';
echo '<input type="button" id="simple-post1" value="Apply" />';
echo '</form>';
echo '<br>';
echo'<div id ="simple-msg1">';
echo'</div>';
echo '<script>
$(document).ready(function()
{
$("#simple-post1").click(function()
{
$("#ajaxform1").submit(function(e)
{
$("#simple-msg1").html("<img src='."'loading.gif'".'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
$("#simple-msg1").html('."'<pre><code class=".'"prettyprint"'.">'+data+'</code></pre>');
},
error: function(jqXHR, textStatus, errorThrown)".'"
{
$("#simple-msg1").html('."'<pre><code class=".'"prettyprint">AJAX Request Failed<br/> textStatus='."'+textStatus+', errorThrown='+errorThrown+'</code></pre>');
}
});
e.preventDefault();
e.unbind();
});
".'$("#ajaxform1").submit();
});
});
</script>';
?>
The second form doesn't work...
you have put the following code to run if an element with id=simple-post gets clicked. notice, .submit is nested inside .click
$(document).ready(function () {
$("#simple-post").click(function () {
$("#ajaxform").submit(function(e){
//code to execute on submit action goes here
}
$("#ajaxform").submit(); //SUBMIT FORM
});
});
so the EventHandler on form submit will registered ONLY AFTER an element with id=simple-post gets clicked which is the reason, ajax request is not happening & form gets submitted normally.
Did you mean the following:
$(document).ready(function () {
$("#ajaxform").submit(function (e) {
$("#simple-msg").html("<img src='loading.gif'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function (data, textStatus, jqXHR) {
$("#simple-msg").html('<pre><code
class="prettyprint">' + data + '</code></pre>');
},
error: function (jqXHR, textStatus, errorThrown) {
$("#simple-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus=' + textStatus + ', errorThrown=' + errorThrown + '</code></pre>');
}
});
e.preventDefault(); //STOP default action
e.unbind();
});
$("#simple-post").click(function () {
$("#ajaxform").submit(); //SUBMIT FORM
});
});
The above code will set EventHandler on form submit on $(document).ready. The form will get submitted via ajax/xhr either when:
Submit button form is pressed.
An element with id=simple-post gets clicked.(Run Code button)
Is this what you intend on doing?

Categories

Resources