function getSearchClients() {
console.log('Inside searchClient');
$('#progressbar').show();
var searchClientPhone = document.getElementById('searchClientCellPhoneNo').value;
$.ajax({
type:"POST",
data: "searchClientPhone=" + searchClientPhone,
url: "searchClientCellPhoneNo",
success: function(result){
$("#progressbar").hide();
$("#example td").each( function() {
var thisCell = $(this);
var cellValue = parseInt(thisCell.text());
if (!isNaN(cellValue) && (cellValue >= document.getElementById("selectedClientRewardPoints").value)) {
thisCell.css("background-color","#FF0000");
}
}
);
$("#selectedClientName").show();
$("#selectedClientRewardPoints").show();
window.location.reload(true);
}
});
}
The textboxes do not become visible in the ajax success, though I have verified control goes to the success block.
I think this is because of window.location.reload(true), why do you think to reload the page again!!
As per my understand, when the page is reloaded for a second time, the search input parameter becomes null/empty, so in this snippet var cellValue = parseInt(thisCell.text()); cellValue is null/undefined.
Because of this, the following two lines do not function as expected
$("#selectedClientName").show();
$("#selectedClientRewardPoints").show();
If you want to keep your status like :
$("#progressbar").hide();
$("#selectedClientName").show();
$("#selectedClientRewardPoints").show();
you should store a boolean in the user localstore or a cookie (on ajax success). Then on the page just have a document ready:
$(document).ready({
if(localstorage/cookie) { / check the status of your cookie or localstorage
$("#progressbar").hide();
$("#selectedClientName").show();
$("#selectedClientRewardPoints").show();
// clear the cookie or the localstorage
}
});
I hope this gives you an idea man...
There were a few things wrong. Primarily you were reloading the page, which is probably the main issue.
Also you had a few small issues with your number parsing and validating. I have fixed it below.
function getSearchClients() {
console.log('Inside searchClient');
$('#progressbar').show();
var searchClientPhone = $('#searchClientCellPhoneNo').val();
$.ajax({
type: "POST",
data: "searchClientPhone=" + searchClientPhone,
url: "searchClientCellPhoneNo",
success: function (results) {
$("#progressbar").hide();
$("#example td").each(function () {
var thisCell = $(this);
var cellText = thisCell.text();
// This will update your textbox...
$("#selectedClientName").val(result.clientName);
// And this is an example of updating based on an array of data.
result.transactions.forEach(function(result){
// Create a list item and append it to the list.
$('<li></li>').text(result).appendTo('#resultList');
});
// If the cell text is a number...
if (!isNaN(cellText)) {
// Parse the text to a base 10 integer...
var cellValue = parseInt(thisCell.text(), 10);
if (cellValue >= $("#selectedClientRewardPoints").val()) {
thisCell.css("background-color", "#FF0000");
}
}
});
$("#selectedClientName").show();
$("#selectedClientRewardPoints").show();
// Do not reload the page.
}
});
}
Thanks #JimmyBoh for the pointers, this is how I fixed the issue :
1) Used struts2-json library. In struts.xml, added below:
<package name="json" extends="json-default">
<action name="searchClientCellPhoneNo" class="com.intracircle.action.RedeemAction" method="searchClientCellPhoneNo">
<result type="json">
<param name="root">jsonData</param>
</result>
</action>
</package>
2) In the action class, added a jsonData Map as follows :
private Map<String,Object> jsonData = new HashMap<String,Object>();
Added getters and setters for jsonData
public Map<String,Object> getJsonData() {
return jsonData;
}
public void setJsonData(Map<String,Object> jsonData) {
this.jsonData = jsonData;
}
In the action method, added data to be returned to jsp to the jsonData Map as follows :
public String searchClientCellPhoneNo() {
clientList = userdao.getClientsList(searchClientPhone);
if(clientList != null && clientList.size() > 0) {
selectedClientName = clientList.get(0).getProfileName();
jsonData.put("selectedClientName",selectedClientName);
int storeId = ((Stores)SecurityUtils.getSubject().getSession().getAttribute(SESSION_CONSTANTS.SESSION_STORE)).getStoreId();
selectedClientRewardPoints = redeemDao.getCountRewardPointsForClientForStore(storeId, clientList.get(0).getId());
jsonData.put("selectedClientRewardPoints", selectedClientRewardPoints);
}
viewRedeemScheme();
return SUCCESS;
}
3) In the jsp ajax method, did the following changes : Make sure, you add dataType:'json' and if you want to print the ajax result using alter, stringify it.
$.ajax({
type:"GET",
data: "searchClientPhone=" + searchClientPhone,
url: "searchClientCellPhoneNo",
dataType: 'json',
headers : {
Accept : "application/json; charset=utf-8",
"Content-Type" : "application/json; charset=utf-8"
},
success: function(result){
alert("result: " + JSON.stringify(result));
console.log("Result " + result);
$("#selectedClientName").val(result.selectedClientName);
$("#selectedClientRewardPoints").val(result.selectedClientRewardPoints);
$("#progressbar").hide();
$("#example td").each( function() {
var thisCell = $(this);
var cellValue = parseInt(thisCell.text());
if (!isNaN(cellValue) && (cellValue >= document.getElementById("selectedClientRewardPoints").value)) {
thisCell.css("background-color","#FF0000");
}
}
);
$("#selectedClientName").show();
$("#selectedClientNameLabel").show();
$("#selectedClientRewardPointsLabel").show();
$("#selectedClientRewardPoints").show();
}
});
Thanks everyone for the help, especially #JimmyBoh.
Related
I posted this yesterday but i may not have explained my situation well.
I have 3 grids on a page that are built dynamically through JavaScript.
I then have 3 separate JavaScript methods to set a session when a row is clicked in a certain grid.
Once the session is set i would like it to navigate to the next page.
Here is what i have
OnClick event
$('#clinician-planned').on('click', 'tbody>tr>td:not(:last-child):not(:first-child)', function () {
var ID = $(this).closest("tr").children("td.grid__col--id").find("[name=patient-link]").text().trim();
var Location = '#Url.Action("SetPASession", "Clinician")';
AjaxCall(Location, ID);
});
$('#clinician-recent').on('click', 'tbody>tr>td:not(:last-child):not(:first-child)', function () {
var ID = $(this).closest("tr").children("td.grid__col--id").find("[name=patient-link]").text().trim();
var Location = '#Url.Action("SetRDSession", "Clinician")';
AjaxCall(Location, ID);
});
$('#clinician-theatre').on('click', 'tbody>tr>td:not(:last-child):not(:first-child)', function () {
var ID = $(this).closest("tr").children("td.grid__col--id").find("[name=patient-link]").text().trim();
var Location = '#Url.Action("SetTESession", "Clinician")';
AjaxCall(Location, ID);
});
AJAX Post To Controller
function AjaxCall(Location, ID) {
alert('1');
$.ajax({
type: 'POST',
url: Location,
dataType: 'text',
async: false,
contentType: 'application/json; charset=utf-8',
error: function (response) { alert(JSON.stringify(response)); }
}).done(function (response) {
alert('2');
location.href = "#Url.Action("Summary", "Patient")" + "/" + ID;
});
}
Here are the controller methods
public ActionResult SetPASession()
{
Session.Remove("Clinician");
Session["Clinician"] = "pa";
return Json(null);
}
public ActionResult SetRDSession()
{
Session.Remove("Clinician");
Session["Clinician"] = "rd";
return Json(null);
}
public ActionResult SetTESession()
{
Session.Remove("Clinician");
Session["Clinician"] = "te";
return Json(null);
}
The problem i have is when the row is clicked "alert('1'); shows instantly, however it seems like it takes a while and waits for all grids to be populated before the 2nd alert appears. I have tried putting async: false, but this doesnt seem to work.
Any ideas would be much appreciated.
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.
My ajax call is returning zero even though I wrote die() at the end of my PHP function.
I looked over the other questions here and did not figure it out, please take a look at my code
I make an ajax call using this function:
$('.aramex-pickup').click(function() {
var button = $(this);
var pickupDateDate = $('.pickup_date').val();
var pickupDateHour = $('.pickup_date_hour').val();
var pickupDateMinute = $('.pickup_date_minute').val();
var pickupDate = pickupDateDate + ' ' + pickupDateHour + ':' + pickupDateMinute;
var orderId = button.data('id');
if (pickupDate) {
//show loader img
button.next('.ajax-loader').show();
var data = {
'action': 'aramex_pickup',
'order_id': orderId,
'pickup_date': encodeURIComponent(pickupDate)
};
$.ajax({
url: ajaxurl,
data: data,
type: 'POST',
success: function(msg) {
console.log(msg);
if (msg === 'done') {
location.reload(true);
} else {
var messages = $.parseJSON(msg);
var ul = $("<ul>");
$.each(messages, function(key, value) {
ul.append("<li>" + value + "</li>");
});
$('.pickup_errors').html(ul);
}
}, complete: function() {
//hide loader img
$('.ajax-loader').hide();
}
});
} else {
alert("Add pickup date");
}
return false;
});
in the back-end I wrote this function just to test the ajax is working ok:
public function ajax_pickup_callback() {
echo 'ajax done';
die();
}
I registered the action by:
add_action('wp_ajax_aramex_pickup', array($this, 'ajax_pickup_callback'));
all of this returns 0 instead of "ajax done".
Any help please?
Actually your hook is not get executed. You have to pass the action in the ajax request as you can see here.
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);
I have a connection with my DB and my DB sends me some integer value like "1","2" or something like that.For example if my DB send me "3" I display the third page,it's working but my problem is when it displays the third page it's not hide my current page.I think my code is wrong in somewhere.Please help me
<script>
function show(shown, hidden) {
console.log(shown,hidden)
$("#"+shown).show();
$("#"+hidden).hide();
}
$(".content-form").submit(function(){
var intRowCount = $(this).data('introwcount');
var exec = 'show("Page"+data.result,"Page' + intRowCount + '")';
ajaxSubmit("/post.php", $(this).serialize(), "", exec,"json");
return false;
})
function ajaxSubmit(urlx, datax, loadingAppendToDiv, resultEval, dataTypex, completeEval) {
if (typeof dataTypex == "undefined") {
dataTypex = "html";
}
request = $.ajax({
type: 'POST',
url: urlx,
dataType: dataTypex,
data: datax,
async: true,
beforeSend: function() {
$(".modalOverlay").show();
},
success: function(data, textStatus, jqXHR) {
//$("div#loader2").remove();
loadingAppendToDiv !== "" ? $(loadingAppendToDiv).html(data) : "";
if (typeof resultEval !== "undefined") {
eval(resultEval);
} else {
//do nothing.
}
},
error: function() {
alert('An error occurred. Data does not retrieve.');
},
complete: function() {
if (typeof completeEval !== "undefined") {
eval(completeEval);
} else {
//do nothing.
}
$(".modalOverlay").hide();
}
});
}
</script>
Thanks for your helping my code working fine now.The problem is occured because of the cache. When I clear cache and cookies on Google Chrome it fixed.
The second parameter passed into the show() method is a bit wrong:
"Page' + intRowCount + '"
Perhaps you meant:
'Page' + intRowCount
Edit: wait wait you pass in a string of code to ajaxSubmit? What happens inside it?
If ajaxSubmit can use a callback, try this:
var exec = function(data) {
show('Page' + data.result, 'Page' + intRowCount);
};
Assuming your html is:
<div id='Page1'>..</div>
<div id='Page2'>..</div>
<div id='Page3'>..</div>
add a class to each of these div (use a sensible name, mypage just an example)
<div id='Page1' class='mypage'>..</div>
<div id='Page2' class='mypage'>..</div>
<div id='Page3' class='mypage'>..</div>
pass the page number you want to show and hide all the others, ie:
function showmypage(pageselector) {
$(".mypage").hide();
$(pageselector).show();
}
then change your 'exec' to:
var exec = 'showmypage("#Page"+data.result)';
It would be remiss of my not to recommend you remove the eval, so instead of:
var exec = "..."
use a function:
var onsuccess = function() { showmypage("#Page"+data.result); };
function ajaxSubmit(..., onsuccess, ...)
{
...
success: function(data) {
onsuccess();
}
}
I Have added a Add New Lead button to the Homepage Main form of contacts
This calls a script to open a new form passing Crm Parameter FirstSelectedItemId
So when I have selected a contact I can click create new lead & pass the Id as a parameter to the function:
function openNewLead(SelectedID) {
parameters["customer"] = SelectedID;
Xrm.Utility.openEntityForm("lead", null, parameters);
}
"customer" is a lookup field
Now I can use this and it populates the lookup but im not passing the full name so doesn't work correctly. if I save and refresh its fine!
So I tried:
function openNewLead(SelectedID) {
if (SelectedID != null) {
var parameters = {};
var request = Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc/ContactSet?$select=FullName&$filter=ContactId eq guid'" + SelectedID + "'";
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: request,
async: false,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
if (data.d.results.length > 0) {
var lookupValue = new Array();
lookupValue[0] = new Object();
lookupValue[0].id = SelectedID;
lookupValue[0].name = data.d.results[0].FullName;
lookupValue[0].entityType = "contact";
parameters["customer"] = lookupValue;
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
/*Error Occurred*/
}
});
Xrm.Utility.openEntityForm("lead", null, parameters);
}
else {
Xrm.Utility.openEntityForm("lead");
}
}
This doesn't work from the homepage/main screen as no reference can be added for Json
So the question is how do I reference json from here or is there a better way to write this?
Thank you
Try this change
success: function (data, textStatus, XmlHttpRequest) {
if (data.d.results.length > 0) {
parameters["customerid"] = SelectedID;
parameters["customeridname"] = data.d.results[0].FullName;
parameters["customeridtype"] = "contact";
}
}
Solution:
New lead Button on main/homepage This calls a script to open a new form passing CrmParameter FirstSelectedItemId
function openNewLead(SelectedID) {
if (SelectedID != null) {
var parameters = {};
var contact = {};
contact.Id = SelectedID;
var jsonContact = JSON.stringify(contact);
var PassContactReq = new XMLHttpRequest();
PassContactReq.open("GET", Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc/ContactSet?$select=ContactId, FullName&$filter=ContactId eq guid'" + SelectedID + "'");
PassContactReq.setRequestHeader("Accept", "application/json");
PassContactReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
PassContactReq.onreadystatechange = function () {
PassContact(this);
};
PassContactReq.send(jsonContact);
function PassContact(PassContactReq) {
if (PassContactReq.readyState == 4 /* complete */) {
PassContactReq.onreadystatechange = null; //avoids memory leaks
if (PassContactReq.status == 200) {
//Success
parameters["customer"] = JSON.parse(PassContactReq.responseText).d.results[0].ContactId;
parameters["customername"] = JSON.parse(PassContactReq.responseText).d.results[0].FullName;
Xrm.Utility.openEntityForm("lead", null, parameters);
}
else {
//Failure
Xrm.Utility.openEntityForm("lead");
}
}
};
} else {
Xrm.Utility.openEntityForm("lead");
}
}
Awesome :) thanks #Nicknow for comment!
As this was a custom lookup field the name differs for the parameters too: Ignore the "id" part of the string & no type to set.
Took too long to find this solution so hopefully it will help others :)
try add javascript actions with referenced webresources and some dummy function name. Like "isNaN".
Ribbon Xml will looks like:
<Actions>
<JavaScriptFunction FunctionName="isNaN" Library="new_json2"></JavaScriptFunction>
<JavaScriptFunction FunctionName="isNaN" Library="new_jquery"></JavaScriptFunction>
<JavaScriptFunction FunctionName="someFunctionUsingCoolExternalLibs" Library="new_referencinglibrary"></JavaScriptFunction>
</Actions>
Sorry for my english :)