Pass Multiple values via AJAX - javascript

I am stuck in passing the multiple value through AJAX call in Codeigniter.
My View is :
<script>
$( document ).ready(function() {
var current_id = 0;
$('#btn').click(function(){
nextElement($('#Outer_00'));
})
function nextElement(element){
var newElement = element.clone()
.find("input:text").val("").end();
var id = current_id+1;
current_id = id;
if(id <10)id = "0"+id;
$('input', newElement).attr("id", id );
newElement.appendTo($("#elements"));
if($('#elements').find('div').length=='5')
{
$('#btn').prop('disabled',true);
}
}
$('#exercises').on('click', '.remove', function() {
if($('#elements').find('div').length<'6')
{
$('#btn').prop('disabled',false);
}
if($('#elements').find('div').length=='1')
{
$('.remove').addAttr("disabled",true);
}
$(this).parent().remove();
return false; //prevent form submission
});
});
</script>
/******************************
<script>
var base_url = '<?=base_url()?>';
$(document).ready(function()
{
$('#Edit').click(function()
{
$('#Name').removeAttr("disabled");
});
$('#Add').click(function()
{
$('#Name').attr("disabled","disabled");
$('#Phone').attr("disabled","disabled");
$('#email').attr("disabled","disabled");
$('#CurrentlyLocated').attr("disabled","disabled");
$('#KeySkills').attr("disabled","disabled");
//var queryString = $('#form1').serialize();
$.ajax({
url: '<?php echo site_url('PutArtistProfile_c/formDataSubmit');?>',
type : 'POST', //the way you want to send datas to your URL
data: {Name:$("#Name").val(), Phone: $("#Phone").val(), email: $("#email").val(),
birthday: $("#birthday").val(), bornIn: $("#bornIn").val(),
CurrentlyLocated: $("#CurrentlyLocated").val(), KeySkills: $("#KeySkills").val(),
Audio1: $("#00").val(), Audio2: $("#01").val(), Audio3: $("#02").val(),Audio4: $("#03").val(), Audio5: $("#04").val(),
},
success : function(data)
{ //probably this request will return anything, it'll be put in var "data"
$('body').html(data);
}
});
});
});
</script>
<p>
<div id="elements">
<div id="Outer_00">
Audio: <input type="text" id="00" value="">
<input type="button" class="remove" value="x"></button>
</div>
</div>
<div id="count"></div>
<input type="button" id="btn" value="Add Audio"></button>
</p>
My Controller is :
public function formDataSubmit()
{
$queryAudio1 = $this->input->post('Audio1');
$queryAudio2 = $this->input->post('Audio2');
$queryAudio3 = $this->input->post('Audio3');
$queryAudio4 = $this->input->post('Audio4');
$queryAudio5 = $this->input->post('Audio5');
}
How can I pass Multiple Values of text box? The above code is passing the values to the controller. But on clicking 'x' Button the value of text box is been getting deleted, but the id of the textbox is getting Incremented, Thus I am not able to pass the further values of textbox to controller via AJAX. Please help me over here.

instead of doing :
data: {Name:$("#Name").val(), Phone: $("#Phone").val(), email: $("#email").val(),
birthday: $("#birthday").val(), bornIn: $("#bornIn").val(),
CurrentlyLocated: $("#CurrentlyLocated").val(), KeySkills: $("#KeySkills").val(),
Audio1: $("#00").val(), Audio2: $("#01").val(), Audio3: $("#02").val(),Audio4: $("#03").val(), Audio5: $("#04").val(),
},
You can do as
data:$("#Form_id").serialize(); // all form data will be passed to controller as Post data.

If you have a remove button then getting the value by id may result in a js error, Why don't you make use of html element array:
<div id="elements">
<div id="Outer_00">
Audio: <input type="text" name="audio[]" value="">
<input type="button" class="remove" value="x"></button>
</div>
</div>

IT is very simple:
Consider you want to pass: user name, surname, and country. These are
three input boxes then:
using Jquery do so:
Javascript side
$.post("url",{name:name,surname:surname,country:country},
function(data){
console.log("Query success");
});
In your Model or controller where your Query will be handled
$name=$this->input->post("name");
$surname=$this->input->post("surname");
$country=$this->input->post("country");
in your case just pass parameters that YOU need. I use codignitter and
this method works fine!

Related

google invisible recaptcha keeps running without execute

I'm trying to use google invisible recaptcha on my web form (php and codeigniter 3). but somehow whenever I click on the Submit button, the google recaptcha keeps generating questions as if ignoring all the other codes before the execute command. so none of the console.log and alert ever appear. what is wrong with my code?
my code looks like this:
HTML
<form id="form_signup" method="post" action="/signup">
<input type="text" name="username"/>
<div class="g-recaptcha"
id="form_signup-recaptcha"
data-size="invisible"
data-sitekey="<?php echo $mysitekey; ?>"
data-callback="onSubmitFormSignupUser">
</div>
<button type="button" id="formSignup-btnSubmit">
Submit
</button>
</form>
JS
var widgetId = '';
var onLoadRecaptcha = function() {
widgetId = grecaptcha.render('formSignup-btnSubmit', {
'sitekey' : $('#form_signup-recaptcha').attr('data-sitekey'),
'callback' : $('#form_signup-recaptcha').attr('data-callback'),
});
};
var onSubmitFormSignupUser = function(response) {
console.log('response', response);
if ($('[name="username"]').val()) {
alert('yes');
grecaptcha.execute(widgetId);
doSubmitFormToServer('#form_signup');
}
else {
alert('no');
grecaptcha.reset(widgetId);
}
}
var doSubmitFormToServer = function(selector) {
var myData = $(selector).serializeArray();
console.log('send form data', myData);
}
Well, you had a typo in the id, at least, here id="form_signup-recaptcha" and here: 'sitekey' : $('#formSignup-recaptcha').attr('data-sitekey'),, other than that, it is not clear, was it invoked at all, or not, as you've not provided the part of including the script, which should contain ?onload=onLoadRecaptcha parameter.
The code is below, but it won't work here, because of null origin. Check Codepen instead: https://codepen.io/extempl/pen/abOvBZv
sitekey used is one is for testing purposes only, as described here: https://developers.google.com/recaptcha/docs/faq#id-like-to-run-automated-tests-with-recaptcha-v2-what-should-i-do
var widgetId = "";
var onLoadRecaptcha = function() {
widgetId = grecaptcha.render("formSignup-btnSubmit", {
sitekey: $("#form_signup-recaptcha").attr("data-sitekey"),
callback: $("#form_signup-recaptcha").attr("data-callback")
});
};
var onSubmitFormSignupUser = function(response) {
console.log("response", response);
if ($('[name="username"]').val()) {
grecaptcha.execute(widgetId);
doSubmitFormToServer("#form_signup");
} else {
$(".status").text("failed");
grecaptcha.reset(widgetId);
}
};
var doSubmitFormToServer = function(selector) {
var myData = $(selector).serializeArray();
$(".status").text("submitted");
console.log("send form data", myData);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js?onload=onLoadRecaptcha"></script>
<body>
<form id="form_signup" method="post" action="/signup">
<input type="text" name="username" />
<div
class="g-recaptcha"
id="form_signup-recaptcha"
data-size="invisible"
data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"
data-callback="onSubmitFormSignupUser">
</div>
<button type="button" id="formSignup-btnSubmit">
Submit
</button>
<span class="status"></span>
</form>
</body>
it turns out that the solution is so simple.
this code
var onLoadRecaptcha = function() {
widgetId = grecaptcha.render("formSignup-btnSubmit", { // wrong element ID
sitekey: $("#form_signup-recaptcha").attr("data-sitekey"),
callback: $("#form_signup-recaptcha").attr("data-callback")
});
};
should be like this
var onLoadRecaptcha = function() {
widgetId = grecaptcha.render("form_signup-recaptcha", { // corrent element ID
sitekey: $("#form_signup-recaptcha").attr("data-sitekey"),
callback: $("#form_signup-recaptcha").attr("data-callback")
});
};
because the recaptcha element is like this
<div
class="g-recaptcha"
id="form_signup-recaptcha"
data-size="invisible"
data-sitekey="6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"
data-callback="onSubmitFormSignupUser">
</div>
so basically the parameters for grecaptcha.render should follow the properties in the element that has g-recaptcha class. my mistake was that I used the button id, even though the element with g-recaptcha class was the div.
I don't remember reading about this particular thing in the documentation. I guess I'm too stupid to realize that before this.. I hope this makes things clear for others with the same problem.

hold the value from form through keyup

I have an input field through which i am getting the value that user enters, although i am able to display it but instead of displaying it, i wish to store the user entry in a variable and then use it to get data from database. Below is the code that i have so far (#JSFiddle)
<form action="save.php" method="post">
<input type="text" value="" id="test">
<p></p>
<input type="text" value="">
<button type="button">submit</button>
</form>
<script>
$( "input" )
.keyup(function() {
var value = $( this ).val();
$( "p" ).text( value );
})
.keyup();
</script>
E.g: if a user enters 12 in input box and then click enter button, then 12 should get stored in a variable, but the whole form should not get submitted after every value of input field is filled then only the form should get submitted
$idd=12;
and then i wish to run a query as
$sql=" SELECT * from menu where id = '".$idd."' ";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result))
{
/*
*
* code to display data
*
*/
}
}
and the result that i need to display will come from the code running inside while loop
Can anyone please tell how to obtain the result
With this code, you store the result to a variable declared before the keyup event.
<input type="text" value="some text">
<p></p>
<script>
var inputValue;
$( "input" )
.keyup(function() {
inputValue = $(this).val();
})
.keyup();
</script>
Than you could do your AJAX call.
EDIT
Here's the code that only respond to the "enter" keycode
var value;
$('input').on('keyup', function(ev) {
if(ev.keyCode == 13) {
value = $(this).val();
}
});
You can do by two ways
<input type="text" value="some text" id="input_id" name="input_name">
<input type="submit" name="submit">
With jquery/ajax
$('#input_id').on('keyup', function() {
var field_value = $("#input_id").val();
jQuery.ajax({
type: 'post',
url: 'path_to_the_file',
data: { fieldValue: field_value },
success: function(successData) {
//do whatever want on success
}
});
});
Or without jquery/ajax On same page
if(isset($_POST['submit']))
{
$my_value = $_POST['input_name'];
//Execute your query
}
you can use ajax to post value of input box and get the result like this
<form action="save.php" method="post">
<input type="text" value="" id="test">
<p></p>
<input type="text" value="">
<button type="button" id="btnsubmit">submit</button>
</form>
<script>
var value
$("input").keyup(function () {
value = $(this).val();
})
$('#btnSubmit').click(function(){
$.ajax({
type: "POST",
url: "url_of_php_page",
data: {id: value},
success: function (html)
{
$("p").text(html);
}
});
});
</script>

Debugging failing jQuery validate addMethod

I have a page where almost every click is handled by delegate().
http://itsneworleans.com/shows/midnight-menu-plus-1/blogs/after-midnight?preview=1
I set up jQuery validate like so
$(document).ready(function(){
$(".commentform form").validate({
rules: {
antispam: { equalToParam: "INO" }
}
});
jQuery.validator.addMethod("equalToParam", function(value, element, param) {
return value == param;
},
"Anti-spam field does not match requested value.");
});
if I check in console with
$.validator.methods['equalToParam']
I get back
function (value, element, param) { return value == param; }
so that looks good.
The validation works on the form submission BUT the equalToParam method has no effect. Only the "required" events occur for it.
The field HTML is
<input name="antispam" type="text" class="required" id="antispam" size="5" />
Where am I going wrong?
EDIT Here is whole form code (generated from PHP script and added to page via AJAX):
<? if ($post = (int) $_POST['pID']) { ?>
<div class="commentform">
<form>
<div class="commenttext">Comment:<br>
<textarea name="comment" class="required"></textarea>
</div>
<div class="commenttext">Your name:<br>
<input type="text" name="name" class="required">
</div>
<div class="commenttext">Your email (will not be publically visible):<br>
<input type="text" name="email" class="required email">
</div>
<div class="commenttext">Type the letters INO here to help us beat spam!<br>
<input name="antispam" type="text" class="required" id="antispam" size="5" />
</div>
<div class="commenttext">
<input type="button" name="submitcomment" class="submitcomment" value="Submit Comment">
<input type="hidden" name="post" value="<?=$post?>">
<? if ($parentComment = (int) $_POST['cID']) { ?>
<input type="hidden" name="parent" value="<?=$parentComment?>">
<? } ?>
</div>
</form>
</div>
<? } ?>
EDIT AGAIN And here's the click delegation code...
$("body").delegate(".submitcomment", "click", function(e) {
e.preventDefault();
var theform = $(this).closest("form");
console.log('Posting comment');
if ($(".commentform form").valid()) {
$.ajax({
type: "POST",
url: "/addComment.php",
data: theform.serialize()
}).done(function(html) {
if (html == 'OK') {
$(theform).html("<div class='commentposted'>Your comment has been received. Thank you. A moderator will review it for public viewing.</div>");
} else {
alert(html);
}
});
}
});
EDIT Here is the code which populates the form into the space where the Reply to Post link was:
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
});
When you need to apply the .validate() method to more than one form, you must wrap it within a jQuery .each().
$(".commentform form").each(function() {
$(this).validate({
rules: {
antispam: {
equalToParam: "INO"
}
}
});
});
EDIT:
You need to initialize the plugin AFTER the form is inserted into the page. Assuming this code properly inserts the form... put your .validate() call as the last item inside...
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
$(".commentform form").validate({ // <- initialize plugin AFTER form is inserted
// your rules & options
});
});
EDIT 2:
Include the equalToParam function someplace on your page within a DOM ready event handler.

jquery code to change the parameters submitted by a form

In a web form in a PHP program, the form is a regular HTML form.
Now, the form has 3 separate text boxes. Let their IDs/names be box1, box2 and box3 respectively
What I want to happen is, when the form gets posted --
The following text gets posted--> box1 + box2+ box3 contents, separated by commas.
I wish to do this using JQuery- I looked up JQuery "submit" function but could not find any direct way to replace the parameters-- how can I implement the above?
You could do this :
$('#yourForm').submit(function(e){
var form = $(this)
//Do you validation
if(isValid){
var mergedInput = $('<input/>');
var inputToMerge = ['#box1','#box2','#box3'];
var valueToMerge = $.map(inputToMerge, function(selector){
val = $(selector).val()
$(selector).remove()
return val;
})
mergedInput.val(valueToMerge.join(','));
mergedInput.prop('name', 'mergedInput')
mergedInput.appendTo(form);
}else{
return false;
}
})
Basicly, it is merging your input into one accessible via php with ['mergedInput'].
i think you can do this easily using ajax .. Kindly check Change contents of submitted form on submit
if you want to do this without ajax, you may have to use hidden fields .. Kindly check jquery-add-additional-parameters-on-submit-not-ajax
You can use AJAX to solve your problem
Your HTML
<form onsubmit="return sendBoxes()">
<input type="text" id="box1">
<input type="text" id="box1">
<input type="text" id="box1">
<input type="submit">
</form>
And JS
function sendBoxes(){
var values = "'"+$('#box1').val()+"'"+$('#box2').val()+"'"+$('#box3').val()+"'";
jQuery.ajax({
url: "ajax_ajax.php",
data: "boxes="+values,
cache: false,
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error.\n" + textStatus + " " + errorThrown);
}
});
return false;
}
HTML
<input id="box1" type="text" />
<input id="box2" type="text" />
<input id="box3" type="text" />
<input id="submit_button" type="submit" />
JS
function submit(){
$.ajax({
type: "POST",
url: "someurl.php",
data:{'boxes':$('#box1').val()+","+$('#box2').val()+","+$('#box3').val()}
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
$("#submit_button").click(function(e) {
submit();
e.preventDefault();
return false;
});
This would check whether submit button is clicked and sends three box values separated by comma

updating SQL database using ajax and grails

I am working with grails, in springsource tool suite, and I am facing a problem updating the SQL databse. In the page, the user is asked to enter details of his property, say address, city etc., and once clicking on button 'save' the details need to be saved in the database. Now what I need to do is, dynamically add the input fields (of address, city, etc) to the page, everytime the user clicks on button 'add'. So because of this, i need to use AJAX to post the data to the server. However, I am having trouble updating it. Here is the code of the view(.gsp file)-
<head>
<script type="text/javascript">
var rad1, rad2, button1, button2;
function add() {
var newP = document.createElement("p");
var input1, input2,
area = document.getElementsByTagName("form")[0];
input1 = document.createElement("input");
input1.type = "text";
input1.placeholder = "street";
input1.id = "address";
newP.appendChild(input1);
input2 = document.createElement("input");
input2.type = "text";
input2.placeholder = "city";
input2.id = "city"
newP.appendChild(input2);
area.appendChild(newP);
}
</script>
</head>
<body>
<form name='prop' method="post" action="save">
<g:hiddenField name="owners.id" value="${session.user.id }" />
<input type="button" value="+Add" onclick= "add();" ><br>
<input type="button" name="create" id="save_button" class="save" value="save" />
</form>
<script type="text/javascript" src="ajax.js"></script>
</body>
Here is what my Ajax code looks like in a separate ajax.js file-
$('#save_button').click(function() {
var street = $('#address').val();
var city = $('#city').val();
$.ajax({
type: "POST",
url: "${createLink(controller: 'property', action: 'save')}",
data: { address: street, city: city },
success: function(data) {
alert(data);
}
});
});
And here is the code in my property controller(save action)-
def save = {
def propertyInstance = new Property(params)
if (propertyInstance.save(flush: true)) {
flash.message = "Property successfully added."
redirect(controller:"user", action: "show", id:params.owners.id)
}
else {
render(view: "create", model: [propertyInstance: propertyInstance, id:params.owners.id])
}
}
What am I doing wrong here? I am not at all familiar with Ajax, so sorry if its an obvious mistake.. please help.
$('#address').val(); and $('#city').val(); will get you the value of the first #address or #city element jQuery finds. If you want to make, let's say, an array for all the address and city values provided you could do this:
var cities = [];
var addresses = [];
$('#address​​​​').each(function() {
addresses.push($(this).val());
});​
$('#cities​​​​').each(function() {
cities.push($(this).val());
});​
If there's two address and city inputs on the page, the result will look something like this:
console.log(addresses); // [address1, address2]
console.log(cities); // [city1, city2]
Edit: To reset the fields on submission (or "add" if you change the jQuery selector), you could do this:
$('#save_button').click(function() {
// ... all your regular ajax stuff ...
// reset the fields
$('#address').val('');
$('#city').val('');
// ... and so on until you reset all fields
});

Categories

Resources