I'm implementing default edit mode on razor view. All things works except the filling function for drop-down list . Regarding my work i have to fill my state drop-down list based on current selected country value at on load event. To accomplish ,i have implemented ajax inside a for loop.
razor
#foreach (CustomerModel customer in Model)
{
<tr>
<td class="CustomerId">
<span id="spn_#customer.CustomerId">#customer.CustomerId</span>
</td>
<td class="Name">
#Html.TextBoxFor(model => customer.Name,new { id = "txtName_" + #customer.CustomerId , onkeyup = "getID(this.id)" })
#*<input id="txtName_#customer.CustomerId" type="text" onkeyup="getID(this.id)" value="#customer.Name"/>*#
</td>
<td class="State">
<select id="ddlState_#customer.CustomerId" style="width:200px;">
#*<option>#customer.StateName</option>*#
</select>
</td>
<td class="Country">
<select id="ddlCountry_#customer.CustomerId" onfocus="fillCountry(this.id)" onchange="fillState(this.id,this.value)" style="width:200px;">
<option>#customer.CountryName</option>
</select>
</td>
<td>
<button id="#customer.CustomerId" onclick="update(this.id)">Save</button>
</td>
</tr>
<script>
arrayID.push('#customer.CustomerId');
</script>
}
Script
var ids;
var txtName;
var txtCountry;
var onchangeFlag = 0;
s = 0;
var idOf;
var idArray = [];
var length = 2;
var flag = 1;
$(document).ready(function () {
// alert(arrayID);
var ido;
var ddlCountryID;
var index = 0;
var countryValue;
var ddlStateidElement;
var s = 0;
var ddlStateID;
var lenthof = arrayID.length;
for (var i = 0; i < lenthof; i++) {
// alert(lenthof);
ido = arrayID[i];
//index = ido;
ddlCountryID = "ddlCountry_" + ido;
ddlStateID = "ddlState_" + ido;
countryValue = $('#' + ddlCountryID).val();
// alert(countryValue);
$.ajax({
type: "POST",
url: "/New/GetOnState",
contentType: "application/json; charset=utf-8",
data: '{"country":"' + countryValue + '"}',
dataType: "html",
success: function (result, status, xhr) {
// alert("success");
// alert(arrayID[index]);
ddlStateidElement = "ddlState_" + ido;
$('#' + ddlStateidElement).html(result);
//index = index + 1;
},
error: function (xhr, status, error) {
alert("Enter");
}
});
//loopend
}
Both c# code and ajax always successful still the loop index always points the last index of the array, i don't know why the loop index fails.
output
$.ajax({
type: "POST",
url: "/New/GetOnState",
contentType: "application/json; charset=utf-8",
data: '{"country":"' + countryValue + '"}',
dataType: "html",
async:false,
success: function (result, status, xhr) {
// alert("success");
// alert(arrayID[index]);
ddlStateidElement = "ddlState_" + ido;
$('#' + ddlStateidElement).html(result);
//index = index + 1;
},
error: function (xhr, status, error) {
alert("Enter");
}
});
Related
I am writing a ajax program in which I am reading data from files created in the project folder. I am having trouble when I select Pakistan country then select any province. Firstly cities in selected province come but when I change the Province all the cities in all province files come. I am trying for hours but not able to figure out. Please anyone can help
Here is my jQuery/ajax code:
switch (myProvince) {
case 'Pakistan':
$.ajax({
type:"GET",
url: "file/country/Pakistan.txt",
dataType: "text",
success: function (response) {
var arrayProvince = response.split(',');
for (var i = 0; i < arrayProvince.length; i++) {
$('#province').append('<option>' + arrayProvince[i] + '</option>');
}
}
});
$('#province').change(function () {
var myCity = $('#province option:selected').text();
$("#city").find("option:not(:first)").remove();
switch (myCity) {
case 'KPK':
$.ajax({
type: "GET",
url: "file/Province/KPK.txt",
dataType: "text",
success: function (object) {
var arrayCity = object.split(',');
for (var j = 0; j < arrayCity.length; j++) {
$('#City').append('<option>' + arrayCity[j] + '</option>');
}
}
});
case 'Punjab':
$.ajax({
type: "GET",
url: "file/Province/Punjab.txt",
dataType: "text",
success: function (object) {
var arrayCity = object.split(',');
for (var i = 0; i < arrayCity.length; i++) {
$('#City').append('<option>' + arrayCity[i] + '</option>');
}
}
});
case 'Balochistan':
$.ajax({
type: "GET",
url: "file/Province/Balochistan.txt",
dataType: "text",
success: function (object) {
var arrayCity = object.split(',');
for (var i = 0; i < arrayCity.length; i++) {
$('#City').append('<option>' + arrayCity[i] + '</option>');
}
}
});
case 'Kashmir':
$.ajax({
type: "GET",
url: "file/Province/Kashmir.txt",
dataType: "text",
success: function (object) {
var arrayCity = object.split(',');
for (var i = 0; i < arrayCity.length; i++) {
$('#City').append('<option>' + arrayCity[i] + '</option>');
}
}
});
case 'Sindh':
$.ajax({
type: "GET",
url: "file/Province/Sindh.txt",
dataType: "text",
success: function (object) {
var arrayCity = object.split(',');
for (var i = 0; i < arrayCity.length; i++) {
$('#City').append('<option>' + arrayCity[i] + '</option>');
}
}
});
default:
}
});
Here is my Html code.
<div class="row">
<div class="col-sm-4 form-group">
<select class="country form-control" id="country">
Country
<option disabled selected>Country</option>
<option>Pakistan</option>
<option>America</option>
<option>Russia</option>
<option>China</option>
</select>
</div>
<div class="col-sm-4 form-group">
<select class="country form-control" id="province">
<option id="proDefault" disabled selected>State/Province</option>
</select>
</div>
<div class="col-sm-4 form-group">
<select class="country form-control" id="City">
<option id="city" disabled selected>City</option>
</select>
</div>
</div>
You need a break; at the end of each case block.
See: https://www.w3schools.com/js/js_switch.asp
I removed your switch from province selection. You can do the same for countries, so your code will be significantly shorter with no duplication and much easier to maintain.
Plunker
$(function() {
$('#country').change(function() {
$.ajax({
type: "GET",
url: "Pakistan.txt",
dataType: "text",
success: function(response) {
var arrayProvince = response.split(',');
for (var i = 0; i < arrayProvince.length; i++) {
$('#province').append('<option>' + arrayProvince[i] + '</option>');
}
}
});
});
$('#province').change(function() {
var myCity = $('#province option:selected').text();
$.ajax({
type: "GET",
url: myCity + ".txt",
dataType: "text",
success: function(object) {
$("#city").find("option:not(:first)").remove();
var arrayCity = object.split(',');
for (var j = 0; j < arrayCity.length; j++) {
$('#city').append('<option>' + arrayCity[j] + '</option>');
}
}
});
});
});
I had an ajax function, that needed to be converted to being called with Jquery for wordpress - but now the function doesn't get called?
function getCategories()
{
alert('getCategories test');
var fData = new Object();
fData.val = '';
jQuery(document).ready(
{
type: "POST",
contentType: "application/json; charset=utf-8",
url: "php_scripts/getdeals_php.php",
data: '{"action":"GetCats", "fData":' + JSON.stringify(fData) + '}',
dataType: "json",
success: function (msg)
{
alert('Success');
var offerList = msg;
var Cats = document.getElementById('CategoriesSelect');
document.getElementById("CategoriesSelect").options.length = 0;
var optn = document.createElement('option');
optn.text = "Select Category";
optn.value = "Select Category";
Cats.add(optn);
for(var i=0;i<offerList.length;i++)
{
var optn = document.createElement('option');
optn.text = offerList[i];
optn.value = offerList[i];
Cats.add(optn);
}
},
error: function (xhr, ajaxOptions, thrownError)
{
alert("ERROR:" + xhr.responseText+" - "+thrownError);
}
});
}
I get my 'getCategories test' alert but I don't get the 'success' or the 'error' alert
So I do not think the jquery is running.
Before I started integrating this with wordpress I was using ajax like this
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "php_scripts/getdeals_php.php",
data: '{"action":"GetCats", "fData":' + JSON.stringify(fData) + '}',
dataType: "json",
success: function (msg)
{
$('#loadingmessage').hide();
var offerList = msg;
var Cats = document.getElementById('CategoriesSelect');
document.getElementById("CategoriesSelect").options.length = 0;
var optn = document.createElement('option');
optn.text = "Select Category";
optn.value = "Select Category";
Cats.add(optn);
for(var i=0;i<offerList.length;i++)
{
var optn = document.createElement('option');
optn.text = offerList[i];
optn.value = offerList[i];
Cats.add(optn);
}
},
error: function (xhr, ajaxOptions, thrownError)
{
alert("ERROR:" + xhr.responseText+" - "+thrownError);
}
});
I would get an erorr that ajax was unknown, and it appears I should be using jquery for this instead...?
I get no errors in the console
Well, there are some different method for calling Ajax in WP. For instance, one way would be like
FOR JS Piece
jQuery(document).ready(function($) {
// We'll pass this variable to the PHP function example_ajax_request
var fruit = 'Banana';
// This does the ajax request
$.ajax({
url: ajaxurl,
data: {
'action':'example_ajax_request',
'fruit' : fruit
},
success:function(data) {
// This outputs the result of the ajax request
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
and PHP piece
function example_ajax_request() {
// The $_REQUEST contains all the data sent via ajax
if ( isset($_REQUEST) ) {
$fruit = $_REQUEST['fruit'];
// Let's take the data that was sent and do something with it
if ( $fruit == 'Banana' ) {
$fruit = 'Apple';
}
// Now we'll return it to the javascript function
// Anything outputted will be returned in the response
echo $fruit;
// If you're debugging, it might be useful to see what was sent in the $_REQUEST
// print_r($_REQUEST);
}
// Always die in functions echoing ajax content
die();
}
add_action( 'wp_ajax_example_ajax_request', 'example_ajax_request' );
// If you wanted to also use the function for non-logged in users (in a theme for example)
// add_action( 'wp_ajax_nopriv_example_ajax_request', 'example_ajax_request' );
Thanks to wptheming
In your case, first try to follow template for JS part and secondly always remember in WP to prevent conflict, you must always use
jQuery(document).ready(function($) {
// You JS functions
});
So I tried to modify your code now on the fly, hope it works for you.
jQuery(document).ready(function($) {
var fData = new Object();
fData.val = '';
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "php_scripts/getdeals_php.php",
data: '{"action":"GetCats", "fData":' + JSON.stringify(fData) + '}',
dataType: "json",
success: function (msg)
{
$('#loadingmessage').hide();
var offerList = msg;
var Cats = document.getElementById('CategoriesSelect');
document.getElementById("CategoriesSelect").options.length = 0;
var optn = document.createElement('option');
optn.text = "Select Category";
optn.value = "Select Category";
Cats.add(optn);
for(var i=0;i<offerList.length;i++)
{
var optn = document.createElement('option');
optn.text = offerList[i];
optn.value = offerList[i];
Cats.add(optn);
}
},
error: function (xhr, ajaxOptions, thrownError)
{
alert("ERROR:" + xhr.responseText+" - "+thrownError);
}
});
});
RF: AJAX in Plugins ( WP DOCS )
here is my code, and i would like to only display items which has "assistance" as tag and no the other. I really don't know how can i do that.
function displayall(newid){
$.ajax({
url: "https://cubber.zendesk.com/api/v2/users/"+newid+"/tickets/requested.json",
type: 'GET',
cors: true,
dataType: 'json',
contentType:'application/json',
secure: true,
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(""));
},
success: function (data){
var sortbydate = data.tickets.sort(function(a,b){ return new Date(b.created_at)- new Date(a.created_at); });
for (i = 0; i < data.tickets.length; i++) {
var myticket = data.tickets[i];
var mydate = data.tickets[i].created_at;
var created = moment(mydate).format("MM-DD-YY");
var mytitle = data.tickets[i].subject;
var description = data.tickets[i].description;
var status = data.tickets[i].status;
var ticketid = data.tickets[i].id;
var tag = data.tickets[i].tags[0];
$("#mylist").append('<li class="row col-md-12 listing" id="newlist" value="'+ticketid+'" onclick="ticketcontent('+ticketid+","+newid+')">'+ '<span class="class_'+status+' otherClasses">' + status + '</span>'+'<div class="identifiant fixed col-md-2">'+" #"+ ticketid +'</div>'+'<div class="identifiant col-md-2">'+tag+'</div>'+'<div class="identifiant col-md-4">'+mytitle +'</div>'+'<div class="identifiant datefixed col-md-2">'+created+'</div>'+'</li>');
}
}
})
}
and if i do console.log(data.ticket[i]) this is what i get:
What you're looking for is:
var filteredTickets = data.tickets.filter(function(ticket) {
return ticket.tags.indexOf('assistance') >= 0;
});
Try using data.tickets.filter():
data.tickets = data.tickets.filter(function(ticket){
return ticket.tags[0] === 'assistance';
});
I am working on an java spring application that requires the controller to return json. By receiving that json in jquery success method, I want to make html out of it.
controller returns a json like below:
return "[{\"Id\": \"1\", \"Name\": \"Apples\"}, {\"Id\": \"2\", \"Name\":\"Mangoes\"}]";
jquery used to hit that controller and then receive the json in success method:
var content;
$(document).ready(function(){
$("#submitButton").click(function(e){
var formData = getFormData();
if(formData!=false){
$.ajax({
type: 'POST',
'url': 'http://localhost:8080/Test_ReportingUI/fieldMappingNext.htm',
data: {jsonData: JSON.stringify(formData)},
dataType: 'json',
success: function(response){
for (var x = 0; x < response.length; x++) {
content = response[x].Id;
content += "<br>";
content += response[x].Name;
content += "<br>";
$(content).appendTo("#Fruits");
}
},
timeout: 10000,
error: function(xhr, status, err){
if(response.status=='timeout')
{
alert('Request time has been out','');
}
console.log(status,err);
}
}); }
});
});
below is the HTML div where I want to use above content to append:
<div id="Fruits">
fruits :
</div>
it is reaching to the controller. and also returning json. but I am not able to use that json.
Replace your for loop with
for (var x = 0; x < response.length; x++)
{
content = "<div class='fruit'><div>" + response[x].Id + "</div>";
content += "<div>" + response[x].Name + "</div></div>";
$(content).appendTo("#Fruits");
}
Your error message correctly explained that you were not appending the correct expression into the fruits
try below code
$(document).ready(function() {
$("#submitButton").click(function(e) {
var formData = getFormData();
if (formData != false) {
$.ajax({
type: 'POST',
'url': 'http://localhost:8080/Test_ReportingUI/fieldMappingNext.htm',
data: {
jsonData: JSON.stringify(formData)
},
dataType: 'json',
success: function(response) {
for (var x = 0; x < response.length; x++) {
var fContent = $("<div></div>");
var id = $("<span></span>").text(response[x].Id);
var name = $("<span></span>").text(response[x].Name);
fContent.append(id)
fContent.append(name);
$("#Fruits").append(fContent);
}
},
timeout: 10000,
error: function(xhr, status, err) {
if (response.status == 'timeout') {
alert('Request time has been out', '');
}
console.log(status, err);
}
});
}
});
});
I'm trying to build mutiple select boxes that dymaically populate then next select box based on the option selected.
it seems to be working but the 3rd select box has duplicate results and i can't see why
here is the JS
$(document).ready(function() {
$('.selectchange').one('change', function() {
var x = $(this).children(":selected").attr("value");
console.log(x)
$.ajax({
type: "POST",
data: "id=" + x,
url: "../complaints/index.php/complaint/get_complaint_sub_types",
dataType: "json",
success: function(data) {
var x = $(this).children(":selected").attr("id");
$.each(data, function(id, value) {
var opt = $('<option />');
opt.val(value.id);
opt.text(value.name);
$('.selectchange1').append(opt);
$('.selectchange2').one('click', function(event) {
var y = $(this).children(":selected").attr("value");
$.ajax({
type: "POST",
data: "id=" + y,
url: "../complaints/index.php/complaint/get_complaint_description",
dataType: "json",
success: function(data1) {
if (data1 != " ") {
var z = $(this).children(":selected").attr("id");
console.log(z);
$.each(data1, function(id, value) {
var opt = $('<option />');
opt.val(value.id);
opt.text(value.name);
$('.selectchange2').append(opt);
})
};
}
})
});
});
}
});
});
})
here is the jsfiddle http://jsfiddle.net/7mg3ume5/2/