create input and send value whit jQuery but value dosnt send - javascript

I want to add input whit js and send value whit jQuery but value dosnt send.
Actually fields value dosn't define in jQuery.
function addElement(myDiv, type) {
var ni = document.getElementById(myDiv);
var numi = document.getElementById('theValue');
var num = (document.getElementById('theValue').value - 1) + 2;
numi.value = num;
var newdiv = document.createElement('div');
var divIdName = 'my' + num + 'Div';
newdiv.setAttribute('id', divIdName);
newdiv.innerHTML = '<input class="name" name="name[]" value="" placeholder="عنوان"><input class="value" name="value[]" value="" placeholder="توضیحات"><input type="hidden" class="type" name="type[]" value="' + type + '"><input type="hidden" class="position" name="position[]" value="' + myDiv + '">'
ni.appendChild(newdiv);
}
$('#add_field').live('click', function() {
var id = $('#id').val();
var name = $('#name').val();
var value = $('#value').val();
var type = $('#type').val();
var position = $('#position').val();
var name = [];
var value = [];
var type = [];
var position = [];
$(".name").each(function() {
name.push($(this).val());
});
$(".value").each(function() {
type.push($(this).val());
});
$(".position").each(function() {
size.push($(this).val());
});
$.ajax({
type: 'POST',
url: '../inc/add.field.php?id=' + id,
data: {
name: name,
type: value,
size: type,
position: position
},
success: function(data) {
$('#result').html(data);
}
});
});
PHP
print_r($_POST['name']);
print_r($_POST['value']);
print_r($_POST['type']);
print_r($_POST['position']);
echo $_GET['id'];
Notice: Undefined index: name
Notice: Undefined index: value
Notice: Undefined index: type
Notice: Undefined index: position

Use this ajax. Note that the $('form') selector needs to be a valid selector that targets your <form> tag. If you serialize, the arrays will be passed as arrays in HTTP, not as a javascript array value. With this mode, PHP will recognize them as arrays, not as [OBJECT object] value
$.ajax({
type: 'POST',
url: '../inc/add.field.php?id=' + id,
data: $('form').serialize(); // that's the change
success: function(data) {
$('#result').html(data);
}
});
EDIT
Test with serializeArray():
$.ajax({
type: 'POST',
url: '../inc/add.field.php?id=' + id,
data: $('form').serializeArray(); // that's the change
success: function(data) {
$('#result').html(data);
}
});
More info: https://api.jquery.com/serializeArray/
EDIT 2
As I said in comments, you can make it with serialize():
http://jsfiddle.net/tZPg4/15519/
It works perfectly.

Related

str_replace inside js from Ajax call data

i want to replacement character from data loop ajax (data[i]) to some values,
i have this js
<script type="text/javascript">
$(document).ready(function() {
$('select[name="parameter"]').on('change', function() {
var idpar = $(this).val();
var subdir = $('input[name="subdirid"]').val();
var year = $('input[name="added_year"]').val();
var i = 0;
if (idpar != '') {
$.ajax({
url: "{{URL::to('myform/myformColaborate')}}/" + idpar + "/" + subdir + "/" + year,
type: "GET",
dataType: "json",
success: function (data) {
$.each(data, function (key, city2) {
$('select[name="type2"]').empty();
$('select[name="type2"]').append(
'<option disabled selected>Select Request Colaborate</option>'
);
for (var i = 0; i < data.length; i++) {
$('select[name="type2"]').append(
'<option value="'+ data[i] +'">Request Colaborate with '+ data[i] +'</option>'
);
}
});
}
});
}
});
});
</script>
and the controller
public function myformColaborate($idpar, $subdir, $year) {
$cities = DB::table("pra_kpis")
->where('subdir_colaborate','like','%'.$subdir.'%')
->where('added_year',$year)
->where('kpi_parameters_id',$idpar)
->distinct()
->pluck("subdirs_id");
return response()->json($cities, 200);
}
for example , i have script replacement outside js like this, how to define it inside js
<?php
$roles = DB::table('pra_kpis')->where('id','=',$l->id)->pluck('subdir_colaborate');
$dir2 = DB::table('subdirs')->select('name')->pluck('name');
$iddir = DB::table('subdirs')->select('id')->pluck('id');
?>
#foreach($roles as $drop)
{{$drop = str_replace($iddir, $dir2, $drop)}}
#endforeach
Try this:
Do it from front-end only,
Use data[i].replace('search string', 'replace string');

Getting the value of appended select list in jquery

I just want to ask how to get the selected value from appended select list using jquery. Please help me. Thanks in advance.
var wrapper1 = $(".column1");
array1 = ["sample1", "sample2", "sample3"];
var myRoot = window.location.origin + "/";
$.ajax({
url: myRoot + 'Payslip/GetDataFromAppend',
type: 'GET',
contentType: "application/json; charset=utf-8",
//data: JSON.stringify({ id: $this }),
async: true,
success: function (data) {
$(wrapper1).append(appendOption(data, array1[0]));
}
});
var appendOption = function (data, txtData) {
var appendfor = '<label class="col-sm-4 control-label"><label> ' + txtData + '...</label></label><div class="col-sm-7">' +
'<select class="form-control" asp-for="PayslipID" asp- items="ViewBag.PayslipID" data- val="true" data- val - required="The Payslip ID field is required." id= "PayslipID" >';
for (var i = 0; i < data.length; i++) {
console.log(data[i].value);
appendfor += '<option value="' + data[i].value + '">' + data[i].value + '</option>';
}
appendfor += '</select ></div >';
return appendfor;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group column1"></div>
The 'form-control' element is added to the page dynamically so you need to use event delegation, try this:
$(document).on('change', ".form-control", function(){
alert($(this).val())
});
'column1' should also work in place of 'document' assuming that it is a static element.

Populating select box options from previous select box value

I am getting problem while populating select box options depend on previous select box
Problem is Whenever I select the value from first select box (i.e. #city) it gives me the result of city value which is fine but as soon as I select the second value it gives me the result of second values as well as first values.
below is my code
HTML CODE
<lable>City</lable>
<select id="city" style="width:100%;text-align:left;" onchange="getSchool()"></select>
<span id='paymentform_city_errorloc' class='error'></span>
<br>
<br>
<lable>School</lable>
<select id="school" style="width:100%;">
</select>
<span id='paymentform_school_errorloc' class='error'></span>
<br>
<br>
JS CODE
var cityname, city, schoolname, schooldata, cityid, city1;
var cityarray = [];
var schoolarray = [];
function getCity() {
jQuery.ajax({
url: baseurl + "getcity.php",
async: true
, success: function (data) {
data = $.trim(data);
if (data == "false") {
console.log(data);
} else {
var myArray = jQuery.parseJSON(data);
jQuery(myArray).each(function (index, element) {
cityname = element.cityname;
cityid = element.city_id;
cityarray.push([cityname, cityid])
});
for (var i = 0; i < cityarray.length; i++) {
city1 += '<option value="' + cityarray[i][1] + '">' + cityarray[i][0] + '</option>';
}
$('#city').html("<option disabled selected></option>" + city1);
}
}
});
}
function getSchool() {
var city_id = $('#city').val();
jQuery.ajax({
url: baseurl + "getschool.php"
, data: 'cityid=' + city_id
, type: "POST"
, success: function (response) {
response = $.trim(response);
if (response == "false") {
$('#school').prop('disabled', 'disabled');
} else {
$('#school').prop('disabled', false);
console.log(response);
$('#school').append(response);
}
}
, error: function () {}
});
}
function getSchool() {
var city_id = $('#city').val();
schoolarray = []; //Add this code.
Make the above change. And your school array will reset every-time a new city is selected.

Adding JSON data to table in AJAX

Ok i have some search results from input box. I used keyup to get results. Then tis results send to AJAX, and i want to append it to table. My problem is because i use append i will get more than one table headers if i have more results, on the other side i cant use html() because script use for loop so i will only get one result. Can someone help me to solve this problem. I try something like this...
$("#search").keyup(function ()
{
var value = $(this).val(); // varijabla iz input polja
// provera za minimalnu duzinu pretrage
if(value.length > 3)
{
$.ajax({
type: "POST",
url: "crud/searching/",
data: { 'var' : value },
dataType: "json",
success: function(response)
{ alert(response);
$('#warning').html(response.msg);;
$('#result').html('');
for(var i=0; i<response.result.length; i++) //petlja za pristup json
{
$('#result').append('<table class="page-list"><thead><tr><th>#</th><th>Naslov</th><th>Autor</th><th>Cena</th><th>Valuta</th></tr><thead><tbody><tr><td>'+ response.result[i].id +'</td><td>'+ response.result[i].naslov +'</td><td>'+ response.result[i].autor +'</td><td>'+ response.result[i].cena +'</td><td>'+ response.result[i].valuta +'</td></tr> </tbody></table> ' );//dodavanje rezultata u div
}
}
})
}
});
Just create the table once and then append trs in the loop to its tbody
$('#warning').html(response.msg);
if (response.result.length) {
var $table = $('<table class="page-list"><thead><tr><th>#</th><th>Naslov</th><th>Autor</th><th>Cena</th><th>Valuta</th></tr><thead><tbody></tbody></table>').appendTo($('#result').html(''));
var $tbody = $table.find('tbody');
for (var i = 0; i < response.result.length; i++) //petlja za pristup json
{
$tbody.append('<tr><td>' + response.result[i].id + '</td><td>' + response.result[i].naslov + '</td><td>' + response.result[i].autor + '</td><td>' + response.result[i].cena + '</td><td>' + response.result[i].valuta + '</td></tr> '); //dodavanje rezultata u div
}
} else {
$('#result').html('')
}
Try this :
$("#search").keyup(function ()
{
var value = $(this).val(); // varijabla iz input polja
// provera za minimalnu duzinu pretrage
if(value.length > 3)
{
$.ajax({
type: "POST",
url: "crud/searching/",
data: { 'var' : value },
dataType: "json",
success: function(response)
{ alert(response);
$('#warning').html(response.msg);
// Store jQuery objects if used more than once
var $table = $('<table class="page-list">').appendTo($('#result')),
$thead = $('<thead><tr><th>#</th><th>Naslov</th><th>Autor</th><th>Cena</th><th>Valuta</th></tr><thead>').appendTo($table),
$tbody = $('<tbody>').appendTo($table);
innerHTML = '';
for(var i=0; i<response.result.length; i++) //petlja za pristup json
{
innerHTML += '<tr><td>'+ response.result[i].id +'</td><td>'+ response.result[i].naslov +'</td><td>'+ response.result[i].autor +'</td><td>'+ response.result[i].cena +'</td><td>'+ response.result[i].valuta +'</td></tr>' );//dodavanje rezultata u div
}
// Append to HTML only once, when you have the full HTML to append
$tbody.append(innerHTML);
}
})
}
});

Validating dynamically created group of check box

I have constructed a table dynamically using Xml file for Multiple choice questions having input type as check boxes instead of radio button.
I wanna know to how to restrict user to check only one check box in a question having for options
Preview of my xml file is
<QA id="1">
<number>1</number>
<q><![CDATA[ <span id="q">Which of the Following is Called "SHRIMP CAPITAL OF INDIA"?</span>]]></q>
<inputType><![CDATA[ <input type = "checkbox" name="UserID" >]]></inputType>
<a><![CDATA[ <label>Stratosphere</lable>]]></a>
<a><![CDATA[ <label>Troposphere</lable>]]></a>
<a><![CDATA[ <label>Mesosphere</lable>]]></a>
<a><![CDATA[ <label>Thermosphere</lable>]]></a>
</QA>
<QA id="2">
<number>2</number>
<q><![CDATA[ <span id="q">Which of the Following is Called "SHRIMP CAPITAL OF INDIA"?</span>]]></q>
<inputType><![CDATA[ <input type = "checkbox" name="UserID1">]]></inputType>
<a><![CDATA[ <label>GOA_MANGLORE</lable>]]></a>
<a><![CDATA[ <label>ROHA-MANGLORE</lable>]]></a>
<a><![CDATA[ <label>KANYAKUMARI-MANGLORE</lable>]]></a>
<a><![CDATA[ <label>KANYAKUMARI-MUMBAI</lable>]]></a>
script for dynamic table ...
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "GET",
url: "data1.xml",
dataType: "xml",
success:function(xml){
$(xml).find('Root').each(function()
{
var title = $(this).find('title').text();
var submit = $(this).find('submit').text();
var subtitle = $(this).find('subtitle').text();
var image = $(this).find('image').text();
var inputType1=$(this).find('inputType1').text();
var inputType2=$(this).find('inputType2').text();
document.getElementById("yt1").value = title;
document.getElementById("yt2").value = submit;
document.getElementById("sub").innerHTML = subtitle;
document.getElementById("middle").src = image;
document.getElementById("yt1").type = inputType1;
document.getElementById("yt2").type = inputType2;
});
var data = "";
var startTag = "<table width='50%'CELLPADDING='1' CELLSPACING='1' id='example'><tbody>";
var endTag = "</tbody></table>";
$(xml).find('QA').each(function() {
var $qa = $(this);
var number =$qa.find('number').text();
var inputType=$qa.find('inputType').text();
var q = $qa.find('q').text();
data += '<tr><td><h3>' + number + '</h3></td>';
data +='<td><h3>'+ q +'</h3></td>';
$(this).find('a').each(function() {
data += '<tr><td>'+ inputType + '</td>';
data += '<td>' + $(this).text()+ '</td></tr></tr>';
});
});
$(xml).find('inputType').each(function() {
$('input:checkbox').click(function() {
$(this).siblings(':checked').attr('checked', false);
});
});
$("#content").html(startTag + data + endTag);
} }); });
</script>

Categories

Resources