I want to send all input in a form with ajax .I have a form like this.
<form action="target.php" method="post" >
<input type="text" name="lname" />
<input type="text" name="fname" />
<input type="buttom" name ="send" onclick="return f(this.form ,this.form.fname ,this.form.lname) " >
</form>
And in .js file we have following code :
function f (form ,fname ,lname ){
att=form.attr("action") ;
$.post(att ,{fname : fname , lname :lname}).done(function(data){
alert(data);
});
return true;
But this is not working.i don't want to use Form data .
as far as we want to send all the form input fields which have name attribute, you can do this for all forms, regardless of the field names:
First Solution
function submitForm(form){
var url = form.attr("action");
var formData = {};
$(form).find("input[name]").each(function (index, node) {
formData[node.name] = node.value;
});
$.post(url, formData).done(function (data) {
alert(data);
});
}
Second Solution: in this solution you can create an array of input values:
function submitForm(form){
var url = form.attr("action");
var formData = $(form).serializeArray();
$.post(url, formData).done(function (data) {
alert(data);
});
}
In your function form is a DOM object, In order to use attr() you need to convert it to jQuery object.
function f(form, fname, lname) {
action = $(form).attr("action");
$.post(att, {fname : fname , lname :lname}).done(function (data) {
alert(data);
});
return true;
}
With .serialize()
function f(form, fname, lname) {
action = $(form).attr("action");
$.post(att, $(form).serialize() ).done(function (data) {
alert(data);
});
return true;
}
Additionally, You can use .serialize()
$.ajax({
url: "target.php",
type: "post",
data: "fname="+fname+"&lname="+lname,
}).done(function(data) {
alert(data);
});
I have written myself a function that converts most of the stuff one may want to send via AJAX to GET of POST query.
Following part of the function might be of interest:
if(data.tagName!=null&&data.tagName.toUpperCase()=="FORM") {
//Get all the input elements in form
var elem = data.elements;
//Loop through the element array
for(var i = 0; i < elem.length; i++) {
//Ignore elements that are not supposed to be sent
if(elem[i].disabled!=null&&elem[i].disabled!=false||elem[i].type=="button"||elem[i].name==null||(elem[i].type=="checkbox"&&elem[i].checked==false))
continue;
//Add & to any subsequent entries (that means every iteration except the first one)
if(data_string.length>0)
data_string+="&";
//Get data for selectbox
if (elem[i].tagName.toUpperCase() == "SELECT")
{
data_string += elem[i].name + "=" + encodeURIComponent(elem[i].options[elem[i].selectedIndex].value) ;
}
//Get data from checkbox
else if(elem[i].type=="checkbox")
{
data_string += elem[i].name + "="+(elem[i].value==null?"on":elem[i].value);
}
//Get data from textfield
else
{
data_string += elem[i].name + (elem[i].value!=""?"=" + encodeURIComponent(elem[i].value):"=");
}
}
return data_string;
}
It does not need jQuery since I don't use it. But I'm sure jquery's $.post accepts string as seconf argument.
Here is the whole function, other parts are not commented though. I can't promise there are no bugs in it:
function ajax_create_request_string(data, recursion) {
var data_string = '';
//Zpracovani formulare
if(data.tagName!=null&&data.tagName.toUpperCase()=="FORM") {
//Get all the input elements in form
var elem = data.elements;
//Loop through the element array
for(var i = 0; i < elem.length; i++) {
//Ignore elements that are not supposed to be sent
if(elem[i].disabled!=null&&elem[i].disabled!=false||elem[i].type=="button"||elem[i].name==null||(elem[i].type=="checkbox"&&elem[i].checked==false))
continue;
//Add & to any subsequent entries (that means every iteration except the first one)
if(data_string.length>0)
data_string+="&";
//Get data for selectbox
if (elem[i].tagName.toUpperCase() == "SELECT")
{
data_string += elem[i].name + "=" + encodeURIComponent(elem[i].options[elem[i].selectedIndex].value) ;
}
//Get data from checkbox
else if(elem[i].type=="checkbox")
{
data_string += elem[i].name + "="+(elem[i].value==null?"on":elem[i].value);
}
//Get data from textfield
else
{
if(elem[i].className.indexOf("autoempty")!=-1) {
data_string += elem[i].name+"=";
}
else
data_string += elem[i].name + (elem[i].value!=""?"=" + encodeURIComponent(elem[i].value):"=");
}
}
return data_string;
}
//Loop through array
if(data instanceof Array) {
for(var i=0; i<data.length; i++) {
if(data_string!="")
data_string+="&";
data_string+=recursion+"["+i+"]="+data[i];
}
return data_string;
}
//Loop through object (like foreach)
for(var i in data) {
if(data_string!="")
data_string+="&";
if(typeof data[i]=="object") {
if(recursion==null)
data_string+= ajax_create_request_string(data[i], i);
else
data_string+= ajax_create_request_string(data[i], recursion+"["+i+"]");
}
else if(recursion==null)
data_string+=i+"="+data[i];
else
data_string+=recursion+"["+i+"]="+data[i];
}
return data_string;
}
The code you've posted has two problems:
First: <input type="buttom" should be <input type="button".... This probably is just a typo but without button your input will be treated as type="text" as the default input type is text.
Second: In your function f() definition, you are using the form parameter thinking it's already a jQuery object by using form.attr("action"). Then similarly in the $.post method call, you're passing fname and lname which are HTMLInputElements. I believe what you want is form's action url and input element's values.
Try with the following changes:
HTML
<form action="/echo/json/" method="post">
<input type="text" name="lname" />
<input type="text" name="fname" />
<!-- change "buttom" to "button" -->
<input type="button" name="send" onclick="return f(this.form ,this.form.fname ,this.form.lname) " />
</form>
JavaScript
function f(form, fname, lname) {
att = form.action; // Use form.action
$.post(att, {
fname: fname.value, // Use fname.value
lname: lname.value // Use lname.value
}).done(function (data) {
alert(data);
});
return true;
}
Here is the fiddle.
you can use serialize method of jquery to get form values. Try like this
<form action="target.php" method="post" >
<input type="text" name="lname" />
<input type="text" name="fname" />
<input type="buttom" name ="send" onclick="return f(this.form) " >
</form>
function f( form ){
var formData = $(form).serialize();
att=form.attr("action") ;
$.post(att, formData).done(function(data){
alert(data);
});
return true;
}
can you try this :
function f (){
fname = $("input[name='fname']").val();
lname = $("input[name='fname']").val();
att=form.attr("action") ;
$.post(att ,{fname : fname , lname :lname}).done(function(data){
alert(data);
});
return true;
}
Related
When i Focusout on AGE module only first row array inserted,how can i multiple array insert?
HTML Form:
$j=2;
for($i=0;$i< $j; $i++)
{
?>
First name :: <input name="firstname[]" type="text" id="firstname" value=""/><br>
Age :: <input name="age[]" type="text" id="age" value="" /><br>
<?php
}
Jquery Code:
$(document).ready(function () {
for (var i = 0; i < 2; i++) {
$('#age').focusout(function () {
var fname = $('#firstname').val();
var ag = $('#age').val();
$.ajax({
type: 'POST',
url: 'responce_for_jquery_loop.php',
data: { firstname: fname, age: ag },
success(result) {
if (result == 1) {
alert('Added. Thank you');
} else {
alert(result);
}
}
});
});
}
})
In Javascript remove for loop and both variable containing value for inputs. just use this code to send form data to php page.
$.ajax({
type:'POST',
url:'responce_for_jquery_loop.php',
data:$('#formID").serialize(),
success:function(result) {...}
});
now in PHP use $_REQUEST['firstName] or $_POST['firstName] and now it will return one array to you containing all input field for having same input name.
Let me know if it doesn't work.
I have a problem with JQuery, I have a multiple select that i can populate in 2 ways, manually taking some value from another select with a add button, and dynamically, with parsing a json returned from a spring call.
I have no problem to take the value when I add it manually, but, when I populate dynamically the select, the JQuery code doesn't take any value although int the html code there're values in the select.
Here my code:
The empty html selects
<div id="enti_disp_box">
<label>Enti disponibili</label>
<select id="ente" multiple> </select>
<button class="btn" onclick="addEnteInBox();" type="button">Aggiungi</button>
</div>
<div id="enti_att_box">
<label>Enti attivi*</label>
<select id="entiAttivi" multiple></select>
<button class="btn" onclick="removeEnteInBox();" type="button">Rimuovi</button>
</div>
JQuery for populate the second select manually
function addEnteInBox(){
var selectedOptions = document.getElementById("ente");
for (var i = 0; i < selectedOptions.length; i++) {
var opt = selectedOptions[i];
if (opt.selected) {
document.getElementById("entiAttivi").appendChild(opt);
i--;
}
}
}
function removeEnteInBox(){
var x = document.getElementById("entiAttivi");
x.remove(x.selectedIndex);
}
JQuery for populate the second select dynamically
function getEntiByIdUtente(idutente) {
var action = "getEntiByidUtente";
var payload = {
"idUtente": idutente,
"action": action,
"token": token
};
$.ajax({
type: "POST",
url: '../service/rest/enti/management_utenti',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(payload),
resourceType: 'json',
success: function(obj, textstatus) {
obj = obj.trim();
var json = JSON.parse(obj);
//parse response
if (obj.stato == 'error') {
alert('Errore');
} else {
$('#entiAttivi').empty();
//fetch obj.data and populate table
$(json.data).each(function() {
$("#piva").val(this.piva);
$("#codiceipa").val(this.codiceipa);
$('#entiAttivi').append($('<option>', {
value: this.idente,
text: this.ragionesociale
}));
});
}
return json;
},
error: function(obj, textstatus) {
alert('Errore di comunicazione col server!');
}
});
}
JQuery for taking the value of the second select
var entiList = $("#entiAttivi").val();
This line seems to be wrong, it's not working for me
$('#entiAttivi').append($('<option>', {
value: this.idente,
text: this.ragionesociale
}));
would you try replacing by
$('#entiAttivi').append($('<option value="' + this.idente + '">' + this.regionesociale + '</option>');
The append, is trying to create an option with the json as parent, this is not working. please try my code.
I am only getting the email address even though I entered my name on the form. Please forgive me I am not an expert in coding. I only know basic html and I just get some codes I find on the internet.
My newsletter form looks like this:
<form id="subscribe" class="form" action="<?=$_SERVER['PHP_SELF']; ?>" method="post">
<div class="form-group form-inline">
<input size="15" type="text" class="form-control required" id="NewsletterName"
name="NewsletterName" placeholder="Your name" />
<input size="25" type="email" class="form-control required" id="NewsletterEmail"
name="NewsletterEmail" placeholder="your#email.com" />
<input type="submit" class="btn btn-default" value="SUBSCRIBE" />
<span id="response">
<? require_once('assets/mailchimp/inc/store-address.php'); if($_GET['submit']){ echo
storeAddress(); } ?>
</span>
</div>
</form>
my js file looks like this:
jQuery(document).ready(function() {
jQuery('#subscribe').submit(function() {
// update user interface
jQuery('#response').html('<span class="notice_message">Adding email address...</span>');
var name = jQuery('#NewsletterName').val().split(' ');
var fname = name[0];
var lname = name[1];
if ( fname == '' ) { fname=""; }
if ( lname == '' || lname === undefined) { lname=""; }
// Prepare query string and send AJAX request
jQuery.ajax({
url: 'assets/mailchimp/inc/store-address.php',
data: 'ajax=true&email=' + escape(jQuery('#NewsletterEmail').val()),
success: function(msg) {
if (msg.indexOf("Success") !=-1) {
jQuery('#response').html('<span class="success_message">Success! You are now
subscribed to our newsletter!</span>');
} else {
jQuery('#response').html('<span class="error_message">' + msg + '</span>');
}
}
});
return false;
});
});
and my php file looks like this:
<?php
function storeAddress(){
require_once('MCAPI.class.php'); // same directory as store-address.php
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('mymailchimpapi');
$merge_vars = Array(
'EMAIL' => $_GET['email'],
'FNAME' => $_GET['fname'],
'LNAME' => $_GET['lname']
);
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "myuniqueid";
if($api->listSubscribe($list_id, $_GET['email'], $merge_vars , $_GET['emailtype']) === true) {
// It worked!
return 'Success! Check your inbox or spam folder for a message containing a
confirmation link.';
}else{
// An error ocurred, return error message
return '<b>Error:</b> ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
I don't know if i should also add
if($api->listSubscribe($list_id, $_GET['fname'], $merge_vars , $_GET['fname']) === true)
on the php file. Does anyone know where the problem is? Or is there something wrong in the JS file?
Your ajax query string only includes ajax=true&email= so $_GET['fname'] will be undefined. It would help if you did some validation of user input at server for security
A simpler way to compile the data from form is to use serialize()
jQuery('#subscribe').submit(function() {
var formData= $(this).serialize() ;
jQuery.ajax({
url: 'assets/mailchimp/inc/store-address.php',
data: formData,
success: function(....
........................
return false;
});
Reference: serialize() API Docs
Fixed!!!! Thanks Charlietfl for pointing out the problem. I Googled that part and was able to find a solution. I tried adding the serialize() code, but it's giving a page error upon clicking the submit button.
I added this on my JS file:
data: 'ajax=true&email=' + escape(jQuery('#NewsletterEmail').val()) + '&fname=' + escape(jQuery('#NewsletterName').val()),
so the whole code is:
jQuery(document).ready(function() {
jQuery('#subscribe').submit(function() {
// update user interface
jQuery('#response').html('<span class="notice_message">Adding email address...</span>');
var name = jQuery('#NewsletterName').val().split(' ');
var fname = name[0];
var lname = name[1];
if ( fname == '' ) { fname=""; }
if ( lname == '' || lname === undefined) { lname=""; }
// Prepare query string and send AJAX request
jQuery.ajax({
url: 'assets/mailchimp/inc/store-address.php',
data: 'ajax=true&email=' + escape(jQuery('#NewsletterEmail').val()) + '&fname=' +
escape(jQuery('#NewsletterName').val()),
success: function(msg) {
if (msg.indexOf("Success") !=-1) {
jQuery('#response').html('<span class="success_message">Success! You are now
subscribed to our newsletter!</span>');
} else {
jQuery('#response').html('<span class="error_message">' + msg + '</span>');
}
}
});
return false;
});
});
I'm developing an application (a kind of social network for my university). I need to add a comment (insert a row in a specific database). To do this, I have a HTML form in my html page with various fields. At time of submit I don't use the action of form but i use a custom javascript function to elaborate some data before submitting form.
function sendMyComment() {
var oForm = document.forms['addComment'];
var input_video_id = document.createElement("input");
var input_video_time = document.createElement("input");
input_video_id.setAttribute("type", "hidden");
input_video_id.setAttribute("name", "video_id");
input_video_id.setAttribute("id", "video_id");
input_video_id.setAttribute("value", document.getElementById('video_id').innerHTML);
input_video_time.setAttribute("type", "hidden");
input_video_time.setAttribute("name", "video_time");
input_video_time.setAttribute("id", "video_time");
input_video_time.setAttribute("value", document.getElementById('time').innerHTML);
oForm.appendChild(input_video_id);
oForm.appendChild(input_video_time);
document.forms['addComment'].submit();
}
The last line submits the form to the correct page. It works fine. But I'd like to use ajax for submitting the form and I have no idea how to do this because I have no idea how to catch the form input values. anyone can help me?
Nobody has actually given a pure javascript answer (as requested by OP), so here it is:
function postAsync(url2get, sendstr) {
var req;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
// req.overrideMimeType("application/json"); // if request result is JSON
try {
req.open("POST", url2get, false); // 3rd param is whether "async"
}
catch(err) {
alert("couldnt complete request. Is JS enabled for that domain?\\n\\n" + err.message);
return false;
}
req.send(sendstr); // param string only used for POST
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) // only if "OK"
{ return req.responseText ; }
else { return "XHR error: " + req.status +" "+req.statusText; }
}
}
alert("req for getAsync is undefined");
}
var var_str = "var1=" + var1 + "&var2=" + var2;
var ret = postAsync(url, var_str) ;
// hint: encodeURIComponent()
if (ret.match(/^XHR error/)) {
console.log(ret);
return;
}
In your case:
var var_str = "video_time=" + document.getElementById('video_time').value
+ "&video_id=" + document.getElementById('video_id').value;
What about
$.ajax({
type: 'POST',
url: $("form").attr("action"),
data: $("form").serialize(),
//or your custom data either as object {foo: "bar", ...} or foo=bar&...
success: function(response) { ... },
});
You can catch form input values using FormData and send them by fetch
fetch(form.action,{method:'post', body: new FormData(form)});
function send(e,form) {
fetch(form.action,{method:'post', body: new FormData(form)});
console.log('We send post asynchronously (AJAX)');
e.preventDefault();
}
<form method="POST" action="myapi/send" onsubmit="send(event,this)">
<input hidden name="crsfToken" value="a1e24s1">
<input name="email" value="a#b.com">
<input name="phone" value="123-456-789">
<input type="submit">
</form>
Look on chrome console>network before 'submit'
You can add an onclick function to your submit button, but you won't be able to submit your function by pressing enter. For my part, I use this:
<form action="" method="post" onsubmit="your_ajax_function(); return false;">
Your Name <br/>
<input type="text" name="name" id="name" />
<br/>
<input type="submit" id="submit" value="Submit" />
</form>
Hope it helps.
Here is a universal solution that iterates through every field in form and creates the request string automatically. It is using new fetch API. Automatically reads form attributes: method and action and grabs all fields inside the form. Support single-dimension array fields, like emails[]. Could serve as universal solution to manage easily many (perhaps dynamic) forms with single source of truth - html.
document.querySelector('.ajax-form').addEventListener('submit', function(e) {
e.preventDefault();
let formData = new FormData(this);
let parsedData = {};
for(let name of formData) {
if (typeof(parsedData[name[0]]) == "undefined") {
let tempdata = formData.getAll(name[0]);
if (tempdata.length > 1) {
parsedData[name[0]] = tempdata;
} else {
parsedData[name[0]] = tempdata[0];
}
}
}
let options = {};
switch (this.method.toLowerCase()) {
case 'post':
options.body = JSON.stringify(parsedData);
case 'get':
options.method = this.method;
options.headers = {'Content-Type': 'application/json'};
break;
}
fetch(this.action, options).then(r => r.json()).then(data => {
console.log(data);
});
});
<form method="POST" action="some/url">
<input name="emails[]">
<input name="emails[]">
<input name="emails[]">
<input name="name">
<input name="phone">
</form>
It's much easier to just use jQuery, since this is just a task for university and you do not need to save code.
So, your code will look like:
function sendMyComment() {
$('#addComment').append('<input type="hidden" name="video_id" id="video_id" value="' + $('#video_id').text() + '"/><input type="hidden" name="video_time" id="video_time" value="' + $('#time').text() +'"/>');
$.ajax({
type: 'POST',
url: $('#addComment').attr('action'),
data: $('form').serialize(),
success: function(response) { ... },
});
}
I would suggest to use jquery for this type of requirement . Give this a try
<div id="commentList"></div>
<div id="addCommentContainer">
<p>Add a Comment</p> <br/> <br/>
<form id="addCommentForm" method="post" action="">
<div>
Your Name <br/>
<input type="text" name="name" id="name" />
<br/> <br/>
Comment Body <br/>
<textarea name="body" id="body" cols="20" rows="5"></textarea>
<input type="submit" id="submit" value="Submit" />
</div>
</form>
</div>
$(document).ready(function(){
/* The following code is executed once the DOM is loaded */
/* This flag will prevent multiple comment submits: */
var working = false;
$("#submit").click(function(){
$.ajax({
type: 'POST',
url: "mysubmitpage.php",
data: $('#addCommentForm').serialize(),
success: function(response) {
alert("Submitted comment");
$("#commentList").append("Name:" + $("#name").val() + "<br/>comment:" + $("#body").val());
},
error: function() {
//$("#commentList").append($("#name").val() + "<br/>" + $("#body").val());
alert("There was an error submitting comment");
}
});
});
});
I would like to add a new pure javascript way to do this, which in my opinion is much cleaner, by using the fetch() API. This a modern way to implements network requests. In your case, since you already have a form element we can simply use it to build our request.
const formInputs = oForm.getElementsByTagName("input");
let formData = new FormData();
for (let input of formInputs) {
formData.append(input.name, input.value);
}
fetch(oForm.action,
{
method: oForm.method,
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error.message))
.finally(() => console.log("Done"));
As you can see it is very clean and much less verbose to use than XMLHttpRequest.
I have a JQuery suggest box using a key and a value. The key is the saved value, for example a userId and the value is the shown value such as a username.
When having a blank field it works great. I type a few characters, select a name and the value is added as the value that is posted with the HTTP request. Now, how should I prefill a form's suggest with when it already has a value. When placing the saved userId as the value the suggest shows the userId but, obviously I want to show the username. I also tried to echo the username that was selected but than, if the username is not changed the posted value will be the username.
<script>
<!--
$(document).ready(function() {
$("#creatorUserId").autocomplete("Gateway.php?action=UserAction&subAction=suggest",{
parse: function(data) {
var parsed = [];
data = data.data;
for (var i = 0; i < data.length; i++) {
parsed[parsed.length] = {
data: data[i],
value: data[i].key,
result: data[i].value
};
}
return parsed;
},
formatItem:function(item, index, total, query){
return item.value;
},
formatResult:function(item){
return item.id;
},
dataType: 'json'
});
});
-->
</script>
<input type="text" name="creatorUserId" id="creatorUserId" value="3" size="40" />
How could I solve this?
Try this
<script>
<!--
$(document).ready(function() {
$("#creatorUserId").autocomplete("Gateway.php?action=UserAction&subAction=suggest",{
parse: function(data) {
var parsed = [];
data = data.data;
for (var i = 0; i < data.length; i++) {
parsed[parsed.length] = {
data: data[i],
key: data[i].key,
value: data[i].value
};
}
return parsed;
},
formatItem:function(item, index, total, query){
return item.value;
},
formatResult:function(item){
return item.id;
},
dataType: 'json'
});
});
-->
</script>
Deleting the current value of the text box on click (If and only if the text box has not yet been edited).
When the input looses focus, and if the input was un-edited, put the initial value back.