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.
Related
i'm trying to get details information from database according to input from id_card .
im already succeed getting the information after I'm typing the id_card in the input box by using keyup function. What i need to do now is I want result appear without I have to press any key after input was trigger. As information, the input will fill in by using QR scanner.
My HTML
<input type="text" id="id_card" placeholder="Capture by QR Code Scanner" name="id_card">
<input type="text" id="fullname" placeholder="Staf Name" name="fullname" readonly>
My Ajax
$(document).ready(function() {
$('#id_card').keyup(function() {
var id_card = $(this).val();
$.ajax({
url: "<?php echo base_url('index.php/scan/get_details'); ?>",
method: 'post',
data: {id_card: id_card},
dataType: 'json',
success: function(response) {
var len = response.length;
document.getElementById("fullname").value = "";
if (len > 0) {
$("#id_card").load();
var uname = response[0].id_card;
var name = response[0].fullname;
document.getElementById("fullname").value = response[0].fullname;
}
}
});
});
});
I'm trying to change keyup function to onchange but no luck.
Thank you for helping.
Try
$(function() {
$('#id_card').on("input", function(e) { // pasted or typed
let id_card = $(this).val();
if (id_card.replace(/\D+/g).length < 16) return
// here the ajax
I am adding the file type dynamically which is working but when I click on submit then I am getting only the first filename in the process page. how to get all the file name in process page? I tried var_dump($_FILES) to check but it is displaying only the first file name.
then I notice that if I remove numberIncr from the name ( name="workpic[]' + numberIncr + '" ) then it's working but my validation not working.
Process.php
if(isset($_FILES)){
echo"<pre>";
//var_dump($_FILES) ;
print_r($_FILES['workpic']['name']);
foreach($_FILES['workpic']['name'] as $key=>$val){
$fileName = basename($_FILES['workpic']['name'][$key]);
print_r($fileName);
}
}
$(document).ready(function() {
var maxField = 10; //Input fields increment limitation
var x = 1; //Initial field counter is 1
//var count = 2;
var numberIncr = 1; // used to increment the name for the inputs
// var addrm = '';
//Once add button is clicked
$(document).on('click', '#clicktoadd', function() {
//Check maximum number of input fields
if (x < maxField) {
$(".medication_info").append(' <input type="file" name="workpic[]' + numberIncr + '" class="dynamicVal"><br />');
x++; //Increment field counter
numberIncr++;
}
// count++;
});
});
$('#register').on('submit', function(event) {
event.preventDefault();
// adding rules for inputs with class 'comment'
$('.dynamicVal').each(function() {
$(this).rules("add", {
required: true
})
});
// test if form is valid
if ($('#register').validate().form()) {
var formData = new FormData(this);
$.ajax({
//url:"process.php",
url: "process2.php",
type: "POST",
dataType: "json",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function(data) {
alert("success");
},
}); // AJAX Get Jquery statment
}
//alert('hellow');
});
$('#register').validate({
errorPlacement: function(error, element) {
if (element.is("select")) {
error.insertAfter(element.parent());
} else {
error.insertAfter(element);
}
}
});
<div id="clicktoadd">Add More</div>
<form action="#" method="post" id="register" name="register" enctype="multipart/form-data">
<div class="row">
<div class="medication_info">
<input type="file" name="workpic[]" class="dynamicVal"><br />
</div>
</div>
<input type="submit" name="send" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/additional-methods.min.js"></script>
Can anyone help me out with this issue?
I am getting this output but I added 3 images and it's displaying only one.
Array
(
[0] =>bTml75QAfHo-unsplash.jpg
)
Would you help me out in this issue?
You shouldn't put numberIncr after name=workpic[]. Using a name ending in [] will automatically make it an array in PHP. So just do:
$(".medication_info").append(' <input type="file" name="workpic[]" class="dynamicVal"><br />');
If you need to give specific indexes, rather than letting them automatically increment from 0, you should put the index inside the [] rather than after it.
$(".medication_info").append(' <input type="file" name="workpic[' + numberIncr + ']" class="dynamicVal"><br />');
I inspected the form data being send when there are multiple input type="file" added with following code
var formData = new FormData(this);
console.log([...formData.entries()]);
Here's the structure
[
[
"workpic[]",
{
...
}
],
[
"workpic[]1",
{
...
}
],
[
"workpic[]2",
{
...
}
]
]
Based on that you can access files following way
print_r($_FILES['workpic[]']['name']);
print_r($_FILES['workpic[]1']['name']);
print_r($_FILES['workpic[]2']['name']);
Or
foreach($_FILES as $file){
echo $file['name'];
}
I want to post my form by ajax to php then get values from inputs ( I did it and it works fine ) but I also want to post a JS variable i one ajax.
There is my FORM section.
<form action="new_alias.php" method="post" id="theForm">
<div class="form-group">
<label for="exampleInputEmail1">Wpisz nazwę aliasu</label>
<input type="text" name="alias" id="alias" class="form-control" id="exampleInputEmail1"
aria-describedby="emailHelp" placeholder="Nazwa aliasu">
</div>
<div class="form-group">
<label class="col-form-label">Wybierz domenę</label>
<?php
if ($resultt->num_rows > 0) {
echo '<select name="name" class="custom-select">';
// output data of each row
while ($row = $resultt->fetch_assoc()) {
echo "<option value='$row[name],$row[id]'>$row[name]</option>";
}
echo '</select>';
} else {
echo "0 results";
}
?>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Wpisz adresy docelowe</label>
<input type="text" name="source" id="source" placeholder="Adresy mailowe" autocomplete="nope"
autocomplete="off" class="typeahead tm-input form-control tm-input-info" />
</div>
<button type="submit" name="add" id="add" class="btn btn-primary mt-4 pr-4 pl-4">Utwórz</button>
</form>
and there is my script
<script>
$(document).ready(function () {
var tagApi = $(".tm-input").tagsManager({
hiddenTagListName: 'hiddenTagListA'
});
var x = '';
var test = '';
jQuery(".typeahead").typeahead({
name: 'source',
displayKey: 'source',
source: function (query, process) {
return $.get('ajaxpro.php', {
query: query
}, function (data) {
data = $.parseJSON(data);
console.log(data);
return process(data);
});
},
afterSelect: function (item) {
tagApi.tagsManager("pushTag", item);
x = document.getElementsByName("hiddenTagListA");
test = x[0].value;
console.log('to jest z afterSlect: ', test);
}
});
$(".btn").click(function (e) {
e.preventDefault();
$.ajax({
type: "post",
url: 'new_alias.php',
data: {
$("#theForm").serialize()
},
success: function () {
alert("Form Submitted: ");
},
});
});
});
</script>
I am using tagsManager which created hidden input with ID hiddenTagListA
I am trying to put all values from hiddenTagListA to var testand it works.
But now I want to post this variable also to my php because I want to put it into my DB. Taking all values from form woks but I must also post test variable.
In my console I am getting value from test like: something, something2, something3... ( tags separated by comma) It can be just string
If you use .serialize then you need to parse the string first to get posted data using AJAX. PHP function parse_str reads string & convert that into array.
Refer: http://php.net/manual/en/function.parse-str.php
You can use .serializeArray function instead of .serialize which make sure to give data in array format, which is easily retrievable in PHP using $_POST variable.
JS CODE
$(".btn").click(function (e) {
e.preventDefault();
var inputData = $("#theForm").serializeArray(); // .serializeArray gives data in array format instead of string format.
// you can insert new variables like below
inputData.push({"name":"hiddenTagListA", "value": document.getElementsByName("hiddenTagListA")[0].value});
$.ajax({
type: "post",
url: 'new_alias.php',
data: inputData,
success: function () {
alert("Form Submitted: ");
},
});
});
if you got the value in test, just put it in ajax
$(".btn").click(function (e) {
e.preventDefault();
$.ajax({
type: "post",
url: 'new_alias.php',
data: {
form: $("#theForm").serialize(),
hiddenTagListA: test
},
success: function () {
alert("Form Submitted: ");
},
});
});
<script>
function autocomplet1() {
var min_length = 0; // min caracters to display the autocomplete
var keyword = $('#select01').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'barcode.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#barcode01').show();
$('#barcode01').html(data);
}
});
} else {
$('#barcode01').hide();
}
}
function set_item(item2) {
$('#select01').val(item2);
var customer = $("#customer").val();
$.post("sales/add", {"data[Sales][item]": item2 ,"data[Sales][customer_phone]": customer }, function (data) {
$('#details3').html(data);
$("#select01").val('');
});
// hide proposition list
$('#barcode01').hide();
}
</script>
<script>
// autocomplet : this function will be executed every time we change the text
function autocomplet() {
var min_length = 0; // min caracters to display the autocomplete
var keyword = $('#customer').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'abc.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#country_list_id').show();
$('#country_list_id').html(data);
}
});
} else {
$('#country_list_id').hide();
}
}
function set_item(item1) {
$('#customer').val(item1);
$.post("sales/add", {"data[Sales][customer]": item1 }, function (data) {
$('#details').html(data);
});
// hide proposition list
$('#country_list_id').hide();
}
</script>
<div class="input_container">
<input type="text" id='customer' onkeyup="autocomplet()" name="data[Sales][customer]" class="input-small focused">
<ul id="country_list_id" style='height: 500px;'></ul></div></div>
<div class="content">
<div class="input_container">
<input type="text" id='select01' onkeyup="autocomplet1()" name="data[Sales][item]" class="input-small focused">
<ul id="barcode01" style='height: 500px;'></ul></div></div>
Above is an autocomplete script. Both script having same function set_time . If i changed function name as set_time1, then autocomplete is not working . How to resolve this issue? . I need to use two autocomplete in a single page.
Okay, since this is hard to explain in the tiny comments, I'll write it here.
Take that script :
function set_item(){
alert("Hello!");
}
function set_item(){
alert("Goodbye!");
}
set_item();
What do you think will happen? What will be alerted?
Answer : "Goodbye!", because the second function definition overrode the first one. You will never see the "Hello!" alert.
This is what happens when two functions have the same name. And you have two functions with the same name. Placing them in different <script> tags won't change anything, it's still the same scope.
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;
}