str_replace inside js from Ajax call data - javascript

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');

Related

Display value in dropdown based on first dropdown

I have a working form here which populating dropdown from the database, i want to do here is display the value of 2nd dropdown based on the selected value on the 1st dropdown, but how i'm gonna do it. My Class will only display on the 2nd drowpdown if error is selected which the 1st dropdown
//my screenshot, my only sample data
enter image description here
Backend code:
public JsonResult GetErrorCategory()
{
List<ErrorCategory> error = errorDataAccessLayer.GetAllError(Action);
return Json(error.Select(x => new
{
errorCode = x.ErrorCode,
errorDescription = x.ErrorDescription
}).ToList(), JsonRequestBehavior.AllowGet);
}
public JsonResult GetClassCategory()
{
List<ErrorClass> error = errorDataAccessLayer.GetAllClass(Action);
return Json(error.Select(x => new
{
classCode = x.ClassCode,
classDescription = x.ClassDescription
}).ToList(), JsonRequestBehavior.AllowGet);
}
View:
<form id="ticket_form" method="post" enctype="multipart/form-data">
<div class="row">
<div class="form-group col-md-4">
<label><strong>Error Type</strong></label>
<select name="ErrorType" id="ErrorDropdown" class="form-control ErrorType" >
</select>
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label><strong>Class Type</strong></label>
<select name="ClassType" id="ClassDropdown" class="form-control ClassType" >
</select>
</div>
</div>
<div class="form-group">
<input type="submit" id="addTicket" value="Create" class="btn btn-md btn-outline-secondary" style="margin:auto;display:block;" />
</div>
</form>
Javascript code:
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/Ticket/GetErrorCategory",
data: "{}",
success: function (data) {
var s = 'option value="-1">Please Select Error Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].errorDescription + '">' + data[i].errorDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ErrorDropdown").html(s);
}
});
$.ajax({
type: "POST",
url: "/Ticket/GetClassCategory",
data: "{}",
success: function (data) {
var s = 'option value="-1">Please Select Class Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].classDescription + '">' + data[i].classDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ClassDropdown").html(s);
}
});
});
</script>
First, in script section you need split functions like as following. You see I added code parameter to the second GetClassCategory method:
function GetErrorCategory() {
$.ajax({
type: "POST",
url: "/Ticket/GetErrorCategory",
data: "{}",
success: function (data) {
var s = 'option value="-1">Please Select Error Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].errorDescription + '">' + data[i].errorDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ErrorDropdown").html(s);
// This line applies onchange event for errorcategory dropdown
ApplyErrorCategoryDropDownOnChange();
}
}
}
function GetClassCategory(code) {
$.ajax({
type: "POST",
url: "/Ticket/GetClassCategory",
data: JSON.stringify({ code: code }),
success: function (data) {
var s = 'option value="-1">Please Select Class Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].classDescription + '">' + data[i].classDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ClassDropdown").html(s);
}
});
}
Second, you need handle onchange() event, because when another item of the first dropwdown selected then you need get it's value.
function ApplyErrorCategoryDropDownOnChange() {
$("#ErrorDropdown").change(function (data) {
GetClassCategory(this.value)
});
}
Third, you must call GetErrorCategory() method from document ready function.
$(function () {
GetErrorCategory();
});
Fourth, you need add code parameter in the backend section, and apply this parameter to your db query:
public JsonResult GetClassCategory(string code) // I added parameter
{
List < ErrorClass > error = errorDataAccessLayer.GetAllClass(Action);
return Json(
error
.Where(x => x.ClassCode = code) // I added this section
.Select(x => new
{
classCode = x.ClassCode,
classDescription = x.ClassDescription
}).ToList(), JsonRequestBehavior.AllowGet);
}
You have to change your code in your second ajax call, i mean it should be some dependent conditional to the first dropdown, For that you just need to get the value of the first dropdown to the second dropdown ajax call while it is selected. Just i mention below :
var error=document.getElementById("ErrorDropdown").value;
$.ajax({
type: "POST",
url: "/Ticket/GetClassCategory",
data: "{error:error}",
success: function (data) {
var s = 'option value="-1">Please Select Class Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].classDescription + '">' + data[i].classDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ClassDropdown").html(s);
}
});
Here i have the value of the first dropdown in variable named as error and i have passed it through the ajax call and use it in my database query with where clause.

dynamic select option and dynamic data from php

I tried develop add several selectbox dynamically and get data from selectbox my codes:
this codes add new selectbox and work
var y = 1;
var z = 1;
$('#add_kind').on('click', function () {
var html = '';
html += '<div class="prInput-row">';
html += '<select name="kind_id" class="halfselect kinds">';
html += '<option value="0">Kinds</option>';
html += '<?php foreach($kinds as $kind): ?>';
html += '<option value="<?php echo $kind->id;?>"><?php echo $kind->name;?></option>';
html += '<?php endforeach; ?>';
html += '</select>';
html += '<select name="kind_desc_id" class="halfselect kind_descriptions">';
html += '<option value="0">Kind Descriptions/option>';
html += '</select>';
html += '<input type="text" name="stock_piece" class="halfselect" placeholder="Stock Piece"/>';
html += '</div>';
$('#kind_area').append(html);
$('.kinds').each(function () {
$(this).attr('class', 'halfselect kinds_'+y);
y++;
});
$('.kind_descriptions').each(function () {
$(this).attr('class', 'halfselect kind_descriptions_'+z);
z++;
});
});
$('.kinds').each(function () {
$(this).attr('class','halfselect kinds_'+y);
y++;
});
$('.kind_descriptions').each(function () {
$(this).attr('class','halfselect kind_descriptions_'+z);
z++;
});
this codes get data from db and not work,
var i = 1;
$(".kinds_"+i).on('change', function() {
var kindID = $(this).val();
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
i++;
});
how can change those codes and how can get dynamically datas
this picture my example
#anon, I solved thank you so much but 2 times write codes but how can write one time ?
$("#add_kind").click(function(){
$.each($("[class*='kinds_']"), function() {
$(this).on('change', function() {
var kindID = $(this).val();
var i = $(this).attr("class").substr(-1, 1);
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
});
});
});
$.each($("[class*='kinds_']"), function() {
$(this).on('change', function() {
var kindID = $(this).val();
var i = $(this).attr("class").substr(-1, 1);
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
});
});
you can get all element that have class started with "kinds_" with selector $("[class^=kinds_]") then do a loop to get your class index. So maybe something like this will work:
$.each($("[class^='kinds_']"), function() {
var selector = "."+$(this).attr("class");
$(document).on('change', selector, function() {
var kindID = $(this).val();
var i = $(this).attr("class").substr(-1, 1);
if(kindID) {
$.ajax({
type: "POST",
url: baseUrl+"products/getSelectedKind",
data: 'kind_id='+kindID,
success: function(data) {
$('.kind_descriptions_'+i).html(data);
}
});
} else {
$('.kind_descriptions_'+i).html('<option value="0">Kind Descriptions</option>');
}
});
})

Change Ajax Post parameters & returned HTML based on alternating dependant dropdowns

I have 3 dropdowns containing values that are populated on page load
<select class='form-control' id='make' placeholder='Make:'>
<select class='form-control' id='model' placeholder='Model:'>
<select class='form-control' id='version' placeholder='Version:'>
I have a function that updates the values in the 'other' dropdowns that aren't clicked, based on the value of the dropdown that is clicked - but I have this function repeated 3 times, for each dropdown
$('#model').change(function(){
let selectedModel = $(this).val();
$.ajax({
url: 'php/dropdown.php',
type: 'POST',
data: {model: selectedModel},
success:function(data)
{ $('#make').html('');
$('#version').html('');
let makeJSON = JSON.parse(data)[0];
let versionJSON = JSON.parse(data)[2];
for (let i = 0; i < makeJSON.length; i++) {
if (makeJSON[i].mMake!= '' && makeJSON[i].mMake!= null) {
$('#make').html($('#make').html() + '<option value="' + makeJSON[i].mMake + '">' + makeJSON[i].mMake + '</option>');
}
}
for (let i = 0; i < versionJSON.length; i++) {
if (versionJSON[i].mVersion != '' && versionJSON[i].mVersion != null) {
$('#version').html($('#version').html() + '<option value="' + versionJSON[i].mVersion + '">' + versionJSON[i].mVersion + '</option>');
}
}
}
});
});
And the PHP looks something like this:
$model = $_REQUEST['model'];
$sqlupdateModel = "SELECT DISTINCT mMake, mVersion FROM Cars WHERE mModel = '$model';
$stmtModel = sqlsrv_query( $conn, $sqlupdateModel);
if( $stmtModel === false)
{
die( print_r( sqlsrv_errors(), true));
}
$updateModel = [];
while( $row = sqlsrv_fetch_array( $stmtModel, SQLSRV_FETCH_ASSOC)){
$updateModel[] = $row;
}
echo json_encode(array($updateMake, $updateModel, $updateVersion));
...and this all works fine,
Basically, I'm looking for a simpler solution for reusing the function (both JS & PHP) instead of rewriting it 3 times!
In terms of what I have attempted,
$('#make, #model, #version').change(function(){
let columnValue = $(this).val();
.......
data: {model: columnValue},
success:function(data)
{$(this).html(''); //this doesn't work obviously!
After this I'm snookered
This one should work for JS side, you will have to check mapping function for response
$('#make, #model, #version').change(function(ev){
let selected = $(this).val();
let id = ev.target.id;
let data = {};
data[id] = selected;
$.ajax({
url: 'php/dropdown.php',
type: 'POST',
data: data,
success:function(data)
{
let options = ['make', 'model', 'version']
const response = {
make: JSON.parse(data[0].map(make => make.mMake)),
model: JSON.parse(data[1].map(make => make.mModel)),
version: JSON.parse(data[2].map(make => make.mVersion))
}
options.filter(option => option !== id).forEach(option => setDropdown(option, response[option]));
}
});
});
function setDropdown(id, data) {
const id = `#${id}`
$(id).html('');
for (let i = 0; i < data.length; i++) {
if (data[i] != '' && data[i] != null) {
$(id).html($(id).html() + '<option value="' + data[i] + '">' + data[i] + '</option>');
}
}
}

Display JSON result in Table Format

$.ajax({
type: 'GET',
url: 'die_issue_result.php',
data: {
vals: die_no
},
dataType: "json", //to parse string into JSON object,
success: function (data) {
if (data) {
var len = data.length;
var txt = "";
if (len > 0) {
for (var i = 0; i < len; i++) {
if (data[i].die_no && data[i].status && data[i].location) {
txt += "<tr><td>"+data[i].die_no+"</td><td>"+data[i].status+"</td><td>"+data[i].location+"</td></tr>";
}
}
if (txt != "") {
$("#table").append(txt).removeClass("hidden");
}
}
}
}
Controller page
$die_no = array();
$status = array();
$location = array();
while ($row = mysql_fetch_array($query)) {
$die_no[] = $row["die_no"]; // or smth like $row["video_title"] for title
$status[] = $row["status"];
$location[] = $row["location"];
}
$res = array($die_no, $status, $location);
echo json_encode($res);
HTML page
<p>
<table id="table" class="hidden">
<tr>
<th>die_no</th>
<th>Status</th>
<th>Location</th>
</tr>
I would like to display result in HTML table format, so I have passed my result in array format to Json but the results are not displayed in HTML page.
I could see the response by using chrome Inspect element under network option . Please help me to display the retrieved results in HTML tabular format.
If you add console.log(data) in your succes response,you can see how the object is structured.
To access the desired json value you should try data['die_no'][i],data['status'][i],data['location'][i].
You can insert the response like this:
<table id="tbl">
</table>
Javascript:
$.ajax({
type: 'GET',
url: 'die_issue_result.php',
data: {
vals: die_no
},
dataType: "json", //to parse string into JSON object,
success: function (data) {
if (data) {
var len = data.length;
if (len > 0) {
for (var i = 0; i < len; i++) {
$('$tbl').append("<tr><td>"+data['die_no'][i]+"</td><td>"+data['status'][i]+"</td><td>"+data['location'][i]+"</td></tr>");
}
}
}
}
}); //you missed this in your question
Use this
$.ajax({
type: 'GET',
url: 'die_issue_result.php',
data: {
vals: die_no
},
dataType: "json", //to parse string into JSON object,
success: function (data) {
if (data) {
var len = data.length;
var txt = "";
if (len > 0) {
for (var i = 0; i < len; i++) {
if (data[0][i] || data[1][i] || data[2][i]) {
txt += "<tr><td>" + data[0][i] + "</td><td>" + data[1][i] + "</td><td>" + data[2][i] + "</td></tr>";
}
}
if (txt != "") {
$("#table").append(txt).removeClass("hidden");
}
}
}
}
});
Actually your php code is not returning key value pair. So in your js you cannot use data.die_no etc
Use this like just I did:
data[0][i]
You have syntax error:
use
txt += <tr><td>
instead of
txt += tr><td>
after if condition

Pulling in JSON via AJAX to populate a Drop-Down

I am pulling in some JSON data that will vary... for instance:
Data returned could be:
[{"userID":"2779","UserFullName":" Absolute Pro-Formance"},{"userID":"2780","UserFullName":" AR Fabrication"},{"userID":"2781","UserFullName":" Banda Lucas Design Group"}]
or:
[{"orderID":"112958","OrderName":"Order ID: 112958"},{"orderID":"112957","OrderName":"Order ID: 112957"},{"orderID":"112956","OrderName":"Order ID: 112956"}]
What I am attempting to do is process this JSON to build a <select> list.
// Load in a drop-down as JSON
function LoadDropDown($url, $where, $id, $selectName){
var $loading = '<div class="pageLoader" style="margin:0 auto !important;padding:0 !important;"><img src="/assets/images/ajax-loader.gif" alt="loading..." height="11" width="16" /></div>';
var $t = Math.round(new Date().getTime() / 1000);
var $container = jQuery($where);
var options = {
url: $url + '?_=' + $t,
cache: false,
type: 'POST',
beforeSend: function(){
$container.html($loading);
},
success: function(data, status, jqXhr){
$html = '<select class="form-control" id="'+$selectName+'" name="'+$selectName+'">';
$html += '<option value="0">- Select an Option -</option>';
for(var i = 0; i < data.length-1; ++i) {
var item = data[i];
console.log(item.userID);
}
$html += '</select>';
$container.html('<pre>' + data + '</pre>');
},
complete: function(jqXhr, status){},
error: function(jqXhr, status, error){
$container.slideDown('fast').html('<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><i class="fa fa-exclamation-triangle fa-4x pull-left"></i><p><strong>Danger Will Robinson!</strong><br />There was an issue pulling in this page. Our support team has been notified, please check back later.</p></div>');
}
};
jQuery.ajax(options);
}
The issue I am having is... #1 console.log(item.userID); always shows undefined, and #2 how can I effecitvely dynamically build the options? The returned JSON will ALWAYS contain 2 items per row and id, and a name
UPDATE
for(var $key in data){
var $val = data[$key];
for($j in $val){
console.log('name:' + $j + ' = ' + $val[$j]);
}
}
Is showing me what I need in Firefox Console... But 1 item per line, for each (for example the 1st JSON) name:userID = 1234 next line name:UserFullName = TheName
How can I get them so I can build my <options>?
With:
for(var k in data) {
console.log(k, data[k]);
}
I am returned:
2955 Object { orderID="8508", OrderName="Order ID: 8508"}
and
2955 Object { userID="1355", UserFulleName="Me Myself And I"}
You don't need to use such messy code. Also in your Ajax setup dataType:"json"
success:function() {
var listB=$('#yourdropdownId');
listB.empty();
$.each(result, function (index, item) {
listB.append(
$('<option>', {
value: item.userID,
text: item.UserFullName
}, '<option/>'))
});
}
Also the $.getJson instead of ajax if you only want retrieve json from server
$.getJSON('#Url.Action(" "," ")',
{ "youparametername": yourdata}, function (data) {
$.each(data, function (index, item) {
})
});
inside the options object, make sure to use the
dataType: 'json'
Or in the success handler you can use
JSON.parse(data)
Cured: Changed my loop to cycle through each item in the returned JSON, got their keys, etc...
var $dl = data.length;
for(var $i = 0; $i < $dl - 1; ++$i) {
var $keys = Object.keys(data[$i]);
$html += '<option value="' + data[$i][$keys[0]] + '">' + data[$i][$keys[1]] + '</option>';
}

Categories

Resources