Filtering Selection from AJAX Call - javascript

What I want to do is, I want to display the selection that registered under accType=Acc1 in Selection. The AccInfo function is my ajax call. I would like to pass the parameter in data. The Acc_response function is a function to operate the option value. I would like to show the branchCode,accType,Code, that is registered under Acc1. How can I do that?
function AccInfo(Acc1){
$.ajax({
type:"POST",
datatype:"json",
async:true,
data:{A:Acc1},
url:AccInfo_url,
success: function(data){
Acc_response(data);
},
error: function(jqXHR, textStatus){
errorHandling(textStatus);
}
})
}
function Acc_response(data){
console.log(data);
for (var i=0;i<data.ClientInfo.length;i++)
{
var $option=$('<option />');
$option.attr('value', data.ClientInfo[i].branchCode+"|"+data.ClientInfo[i].Code+"|"+data.ClientInfo[i].accType);
$option.text(data.ClientInfo[i].accType+" (" + data.ClientInfo[i].Code+"-"+data.ClientInfo[i].branchCode+") ";
$('#Selection').append($option);
}
}

This is more usefull;
var selectedAccType = 'your account type';
//you can set this at post action to
function Acc_response(data){
data.ClientInfo.forEach(function(client) {
if(client.accType==selectedAccType){
var optionValue = client.branchCode+'|'+client.Code+'|'+client.accType;
var optionText = client.accType+'('client.Code+'-'+client.branchCode+')';
var option = '<option value="'+optionValue+'">'+optionText+'</option>';
$('#Selection').append(option);
}
});
}
This works for if you have one <select>. If you have more selects send us your html code.

Related

How do I prevent reset the select box after ajax post action?

I want to make the option I selected fix to after AJAX POST.
Currently I am doing the work manually.
I put the value at OnChange in the HiddenField,
and after doing AJAX POST, re-insert the value selected in "ddlUserCont".
<select id="ddlUserCont" onchange="ddlUserCont_Onchange(this);"></select>
function ddlUserCont_Onchange(obj) {
document.getElementById("<%=hidSelddlUserCont.ClientID %>").value = obj.value;
}
-> After AJAX POST action..
function btnTest_Click() {
// ... Some logic
$.ajax({
type: "POST",
cache: false,
url: "../../WebServices/WebService.asmx/GetTest",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
OnSuccess_GetTest(data, sTestVal);
},
error: function (request, status, error) {
console.log("code:" + request.status + "\n" + "message:" + request.responseText + "\n" + "error:" + error);
}
});
}
function OnSuccess_GetTest(response, sTestVal) {
var items = response.d;
// ... Some logic
var sSelPageName = document.getElementById("<%=hidSelddlUserCont.ClientID %>").value;
document.getElementById("ddlUserCont_" + sSelPageName).selected = "true";
}
Do I use UpdatePanel ?
Why is it getting reset? is the page reloading? or is some other script resetting it?
function OnSuccess_GetTest(response, sTestVal) {
var items = response.d;
// ... Some logic
var sSelPageName = document.getElementById("<%=hidSelddlUserCont.ClientID %>").value; // get the value from the hidden field
document.getElementById("ddlUserCont).value = sSelPageName; // set it on the select options element
}
Just make sure that select has an option child element with value=<sSelPageName> at the time.

how to empty the function parameter once it passes to the function?

I am trying to send the parameter in a function but its in a loop so when i select the same function next time it first send me the previous value then send me the value that i want which causes the function to be empty and not take any value let me show you my code.
$(window).load(function(e) {
loadmore();
select_likes();
select_share();
// get_recieve_friend_requests();
// get_sent_friend_requests();
});
function loadmore() {
var lastID = $('.load-more').attr('lastID');
// alert(lastID);
jQuery.ajax({
type: 'POST',
url: '<?php echo base_url("user/get_all_post"); ?>',
data: {
id: lastID
},
dataType: 'json',
beforeSend: function(data) {
$('.load-more').show();
},
success: function(data) {
var ParsedObject = JSON.stringify(data);
var json = $.parseJSON(ParsedObject);
if (json == "") {
$("#bottom").append('<div class="btn btn-default col-md-6" >' + 'No More Results' + '</div>');
$("#Load_more_data").hide();
} else {
$postID = json[json.length - 1].id;
$('.load-more').attr('lastID', $postID);
$.each(json, function(key, data) {
var post_id = data.id;
var post_status = data.status;
var status_image = data.status_image;
var multimage = data.multimage;
if (!post_status == "" && !status_image == "") {
alert(post_id);
$("#status_data").append('<div class="media-body"><div class="input-group"><form action="" id="form_content_multimage"><textarea name="textdata" id="content_comment_multimage" cols="25" rows="1" class="form-control message" placeholder="Whats on your mind ?"></textarea><button type="submit" id="comment_button_multimage" onclick="comment_here_multimage(' + post_id + ');" >Comment</button><?php echo form_close();?></div></div></li></ul></div></div>');
}
});
}
}
});
}
function comment_here_multimage(post_id) {
$(document).on('click', '#comment_button_multimage', function(e) {
// this will prevent form and reload page on submit.
e.preventDefault();
var post_id_multimage = $('#post_id_multimage').val();
// here you will get Post ID
alert(post_id_multimage);
var Post_id = post_id;
alert(post_id);
if (post_id == post_id_multimage) {
var User_id = $('.id_data').attr('value');
var textdata = $('#content_comment_multimage').val();
alert(textdata);
alert(Post_id);
$.ajax({
type: 'POST',
url: '<?php echo base_url("user/post_comment"); ?>',
data: {
Post_id: Post_id,
User_id: User_id,
textdata: textdata
},
dataType: 'json',
success: function(data) {
console.log(data);
alert('you have like this');
jQuery('#form_content_multimage')[0].reset();
Post_id = "";
}
});
} else {
return false;
}
});
}
The post_id is being passed onclick event of the comment_here_multimage but whenver i click on it after first time same id is being passed again first then the next id passes. what can i fo to empty the post_id value once it completes.
look at these images and tell me if there is something you dont understand.
[![first time comment][1]][1]
[![second time comment][2]][2]
[![second time comment][3]][3]
[1]: https://i.stack.imgur.com/b36o4.png
[2]: https://i.stack.imgur.com/ahg3W.png
[3]: https://i.stack.imgur.com/taHAS.png
Your problem is not isolated in code. However according to my understanding.
You are binding "comment_here_multimage" function on click event of button when creating dynamic html.
Once context is loaded and user clicks that button you again binds another function on same button, which is ultimately added to the event stack.
If user clicks the button first time nothing will happen, there is no action on it. On first time it will register a handler with it.
If user click second time it will fire the handler attached on first click resulting in old postid supplied to it.
I think your problem is with passing parameter. You can set it in a custom parameter and get it later in click handler. Or you can change your handler like below.
You can change your code like this
onclick="comment_here_multimage(this,' + post_id + ');"
function comment_here_multimage(e,post_id) {
// this will prevent form and reload page on submit.
e.preventDefault();
var post_id_multimage = $('#post_id_multimage').val();
// here you will get Post ID
alert(post_id_multimage);
var Post_id = post_id;
alert(post_id);
if (post_id == post_id_multimage) {
var User_id = $('.id_data').attr('value');
var textdata = $('#content_comment_multimage').val();
alert(textdata);
alert(Post_id);
$.ajax({
type: 'POST',
url: '<?php echo base_url("user/post_comment"); ?>',
data: {
Post_id: Post_id,
User_id: User_id,
textdata: textdata
},
dataType: 'json',
success: function(data) {
console.log(data);
alert('you have like this');
jQuery('#form_content_multimage')[0].reset();
Post_id = "";
}
});
} else {
return false;
}
;
}

jQuery How to make a variable that shows just the value of a form array

So right now I have a form that is saved in AJAX when submitted.
$(document).ready(function () {
$("#dispatchForm").on("submit", function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr("action") || window.location.pathname,
type: "POST",
data: $(this).serialize(),
success: function (data) {
$("#form_output").html(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
I then have it where the result is shown in a variable and put into a textbox on the page when the submit button is clicked, via this code.
$(function () {
$("#dispatchSumbit").on("click", function () {
var text = $("#textarea");
var local = $("#dispatchForm").serialize();
text.val(text.val() + time +" - Dispatched to \n" + local);
});
});
However it shows the whole array which is like this:
I want it to just say "[Time] - Dispatched to Test"
Thanks for the help in advance!
$("#dispatchForm").serialize() is for creating a name=value&name=value&... string for all the inputs in the form, which can be used as the data in an AJAX request. If you just want a single value, use
var local = $("#dispatchForm [name=dispatchLocal]").val();

Creating html table using javascript ajax calls in sequential order?

I am new to JavaScript. I am creating one table dynamically; I am facing a problem with the order of execution. I know JavaScript code won't execute sequentially, but what will be the work around?
First I will brief what I am trying to do.
1) loadList () -> I will call this method on click of load data button
here I will fire AJAX request to get data
2) using the result of above AJAX request, I am trying to create table rows
3) few table rows td having combo box, whose value to be filled using another AJAX call, passing the rowObject value
Below is my code:
var loadList = function(){
//ajax call
$.ajax({
url:"tworows.json",
type: "GET",
dataType : "json"
})
.done(function(data, textStatus, jqXHR){
generateTable(data);
});
};
function generateTable(data){
$("#gridTable").empty();
//create table header
var headertr = $("<tr><th>col1 </th><th>col 2</th><th>col 3</th><th>col 4</th><th>col 5</th><th>col 6</th><th>col 7</th></tr>");
//get table id from jquery
var tableelement = $("#gridTable");
//add header row to table
tableelement.append(headertr);
for(var i=0; i< data.links.id.length; i++){
tableelement.append(createRow(data.links.id[i]));
}
}
function createRow(rowObject){
//used to create combo box 1 based row 1 value
var combo1 = createCombo1(rowObject);
//used to create combo box 2 based row 1 value
var combo2 = createCombo2(rowObject);
var trElement = "<tr>"+
"<td><input type='text' name='col1name' value='"+rowObject.Number+"' onblur='handleInput(this)'/></td>"+
"<td><input type='text' name='col3name' value='"+rowObject.name+"'/></td>"+
"<td><input type='text' name='col3name' value='"+rowObject.quantity+"'/></td>"+
"<td>"+combo1+"</td>"+
"<td>"+combo2+"</td>"+
"<td><button>Del</button></td>" +
"<td><button>Add</button></td></tr>";
return trElement;
}
function createCombo1(rowObject){
var comboList = [];
//call ajax to get combo value
$.ajax({
url:"combo1data.json",
type: "GET",
dataType : "json",
async : false
})
.done(function(data, textStatus, jqXHR){
comboList = data.links.id;
});
var cmb1 = "<select name='cmb1' onchange='handlecmb1Change(this)'>";
for(var i=0;i < comboList.length; i++){
cmb1 +="<option value='"+comboList[i].id+"'>"+comboList[i].name+"</option>";
}
cmb1 += "</select>";
return cmb1;
}
function createCombo2(rowObject){
var comboList = [];
//call ajax to get combo value
$.ajax({
url:"combo2data.json",
type: "GET",
dataType : "json",
async : false
})
.done(function(data, textStatus, jqXHR){
comboList = data.links.id;
});
var cmb2 = "<select onchange='handlecmb2Change(this)'>";
for(var i=0;i < comboList.length; i++){
cmb2 +="<option value='"+comboList[i].id+"'>"+comboList[i].name+" </option>";
}
cmb2 += "</select>";
return cmb2;
}
Here row is creating first, after that control is going to createCombo methods. Because of this I am not getting combo boxes in td.
I want to create combobox based on first result of AJAX call; using the first result I need to call other 2 AJAX calls and populate them in the td combobox.
Please use below code block, this might be solve your problem. Your requirement need synchronous execution of methods, for this you need to use callback structure.
below is the code :
var loadList = function(){
//ajax call
$.ajax({
url:"tworows.json",
type: "GET",
dataType : "json"
})
.done(function(data, textStatus, jqXHR){
generateTable(data);
});
};
function generateTable(data){
$("#gridTable").empty();
//create table header
var headertr = $("<tr><th>col1 </th><th>col 2</th><th>col 3</th><th>col 4</th><th>col 5</th><th>col 6</th><th>col 7</th></tr>");
//get table id from jquery
var tableelement = $("#gridTable");
//add header row to table
tableelement.append(headertr);
for(var i=0; i< data.links.id.length; i++){
tableelement.append(createRow(data.links.id[i]));
}
}
function createRow(rowObject){
var trElement = "<tr>";
//used to create combo box 1 based row 1 value
var combo1 = createCombo1(rowObject,function(response){
//used to create combo box 2 based row 1 value
var combo2 = createCombo2(rowObject,function(result){
trElement+= "<td><input type='text' name='col1name' value='"+rowObject.Number+"' onblur='handleInput(this)'/></td>";
trElement+="<td><input type='text' name='col3name' value='"+rowObject.name+"'/></td>";
trElement+="<td><input type='text' name='col3name' value='"+rowObject.quantity+"'/></td>";
trElement+="<td>"+response+"</td>";
trElement+="<td>"+result+"</td>";
trElement+="<td><button>Del</button></td>";
trElement+="<td><button>Add</button></td></tr>";
});
});
return trElement;
}
function createCombo1(rowObject,callback){
var comboList = [];
//call ajax to get combo value
$.ajax({
url:"combo1data.json",
type: "GET",
dataType : "json"
})
.done(function(data, textStatus, jqXHR){
comboList = data.links.id;
var cmb1 = "<select name='cmb1' onchange='handlecmb1Change(this)'>";
for(var i=0;i < comboList.length; i++){
cmb1 +="<option value='"+comboList.id+"'>"+comboList.val+"</option>";
}
cmb1 += "</select>";
return callback(cmb1);
});
}
function createCombo2(rowObject,callback){
var comboList = [];
//call ajax to get combo value
$.ajax({
url:"combo2data.json",
type: "GET",
dataType : "json"
})
.done(function(data, textStatus, jqXHR){
comboList = data.links.id;
var cmb2 = "<select name='cmb1' onchange='handlecmb1Change(this)'>";
for(var i=0;i < comboList.length; i++){
cmb1 +="<option value='"+comboList.id+"'>"+comboList.val+"</option>";
}
cmb2 += "</select>";
return callback(cmb2);
});
}
thanks
There are several problems that need to be addressed.
First, the return value from an ajax callback won't go anywhere.
This line
var combo1 = createCombo1(rowObject);
Will set combo1 to undefined every single time. Because createCombo1() doesn't return anything. The anonymous function inside of createCombo1() is what returns the value your looking for, but in this case you can't use that return value.
What I recommend for createCombo1() and createCombo2() is to save the return value to a global variable or maybe even an array, so you can access them when they are done.
Which brings me to the next problem...how do you know when they are done?
jQuery has something called a deferred object. Which allows you to chain multiple callbacks to one function. There is a similar SO question that addresses how to use this using When().
Here is the question
There is still a lot to do on your end, but hopefully this will point you in the right direction.

Update data from a new JSON after delay of 5 seconds and again from a new JSon after another 5 delays sec

my updated full script:
$(document).ready(function() {
$.getJSON('table.json',function(data){
$('#mytable').empty();
var html = '';
html += '<tr class="tableheader"><th>Name</th><th>Code</th><th>Value</th><th>Bid</th><th>Offer</th></tr>';
for (var i=0, size=data.length; i<size;i++) {
html += '<tr class="tablecontent"><td>'+ data[i].name+ '</td><td>'+ data[i].code+ '</td><td>'
+ data[i].value+ '</td><td>'
+data[i].bid+'</td><td>'+data[i].offer+'</td></tr>';
}
$('#mytable').append(html);
tablerows('mytable');
setTimeout(poll,5000);
});
});
var poll = setInterval(function(){
$.ajax({
type:"GET",
url: "dummy.json",
success: function(data){
//HANDLE DATA
setTimeout(poll,5000);
}
});
},5000);
Please help me in this. i have 3 JSONs. 1st Json will load initially. That is done.
2nd json needs to be parsed (which has 2 field changes) and show the initial json + changed fields and then again from 3rd JSON.
I have written below script:
var poll = setInterval(function(){
$.ajax({
type:"GET",
url: "dummy.json",
success: function(data){
//HANDLE DATA
JSON.parse(data);
}
});
},5000)
dummy.json is my second changed JSON. Is this the correct way?how should i call this function function in my $(document).ready?
Set it as a regular function and then call it from itself within the success handler so then you are never getting ahead of yourself. Then you can also just call it once from your $(document).ready.
var poll = function(){
$.ajax({
type:"GET",
url: "dummy.json",
success: function(data){
//HANDLE DATA
setTimeout(poll,5000);
}
});
}

Categories