Navigation in javascript widget using JSONP - javascript

I am working on javascript widget which can be shown on any site.
see.
Show JS(jQuery) widget on any site, with ASP.NET MVC server side
Embeddable widgets using jQuery and ASP.NET MVC
and for now I faced with issue, when I need to navigate between pages in widgets. See code below. But for now I am confused how to organize navigation (link clicking, ajax updating) in html that comes from server, to make it working as without widget, because I want to debug it as usual page.
<img alt="TEST" onclick="window.zs.LoadStep1('ad507a69-d882-41d4-8300-bd9f7163d419',this);" style="cursor:pointer;"/>
;
(function (window, ZS, undefined) {
var zs = window.zs = ZS || {};
zs.Version = "v1_0";
zs.baseUrl = "http://localhost/w/";
var jQueryScriptOutputted = false;
var containerSelector = '#zaprosWidgetContainer';
function initJQuery() {
if (typeof (jQuery) == 'undefined') {
if (!jQueryScriptOutputted) {
jQueryScriptOutputted = true;
document.write("<scr" + "ipt type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js\"></scr" + "ipt>");
}
setTimeout("initJQuery()", 50);
}
};
function initContainer() {
if ($(containerSelector).length == 0) {
$('<div id="zaprosWidgetContainer" style="width=500px;height:500px;"></div>').appendTo('body');
}
}
zs.LoadStep2 = function (serviceId) {
$.ajax({
url: zs.baseUrl + 'Wizard/Step2JsonP?jsoncallback=?',
data: { serviceId: serviceId },
type: "GET",
dataType: "jsonp",
jsonpCallback: "callBack",
success: function (json) {
$(containerSelector).html(json.Html);
}
});
},
zs.LoadStep1 = function (providerId) {
$(function () {
$.ajax({
url: zs.baseUrl + 'Wizard/Step1JsonP?jsoncallback=?',
data: { providerId: providerId },
type: "GET",
dataType: "jsonp",
jsonpCallback: "callBack",
success: function (json) {
$(containerSelector).html(json.Html);
}
});
});
};
initJQuery();
initContainer();
})(window, window.zs || {});

I understand that you want to navigate to LoadStep1/LoadStep2 without ajax-style?
You could create a master page in ASP.NET that has a link/button to navigate to the next step. That link is generated as part of the previous step.
E.g. on the output html of Step1 add
Next Step
Can you tell us why you have to create a "non-widget mode" for debugging? What's the difference for debugging?
Something else about JsonP that helped me:
You can also extend your JsonP class that wraps the JSON data into a JsonP string to support returning normal JSON when no callback method is supplied - this way you can use the same uri to return the html directly. I use that to allow widgets run in JsonP and Json simultaneously.

Related

Passing parameters between html pages using jquery

I have one html page which contains a jquery function.
<script>
function loadCustomers() {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/cache/getCustomers',
dataType: 'json',
success: function(data) {
var rows = [];
$.each(data,function(id,value) {
rows.push('<tr><td><a href="clientSiteInfo.html?client=">'+id+'</td><td>'+value+'</td></tr>');
});
$('table').append(rows.join(''));
}
});
};
window.onload = loadCustomers;
</script>
I have linked another html page for each row. When each rows populated, the id values has to be passed to the clientSiteInfo.html page.
In the clientSiteInfo.html page i have another jquery function similar to above.
<script>
function loadSites() {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/cache/getSite?clientName='+${param.client},
dataType: 'json',
success: function(data) {
var rows = [];
$.each(data,function(id,value) {
rows.push('<tr><td>'+id+'</td><td>'+value.machine+'</td><td>'+value.state+'</td></tr>');
});
$('table').append(rows.join(''));
}
});
};
window.onload = loadSites;
</script>
in the GET url I try to read client parameter. But it is not passing from my initial page.
What Im doing wrong here? I look for simple solution
jQuery doesn't have a native way to read the url parameters. However, javascript works just fine:
function getParameterByName(name) {
const match = RegExp(`[?&]${name}=([^&]*)`).exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' ') );
}
In your code you would just call it as getParameterByName('client')

jQuery Ajax placing random "jQuery111201xxx" into string

I have made a booking system that utilizes FullCalendar; though that part should be irrelevant. My problem is that upon saving an appointment, a 'notes' field I have created very occasionally has this strange string inserted into it, generally at a random point in the string. Here is the latest example:
Has this been changedjQuery1112010047650896012783_1444929292744 with Rich- finishing sleeve off.bringing deposit in on saturday. told him space isnt secure.
As you can see, there is a totally out of place "jQuery1112010047650896012783_1444929292744" placed in the middle of the note. I can't find anything about this online (mainly because I have no idea what terms I'd use to find it). It must be related to jQuery, considering the string.
I am using jQuery v1.11.2 - obviously the string looks like a long version number.
Why is my ajax request seemingly succeeding, but placing this message in the middle of the sent string? I cannot replicate this issue at all, especially this time since it was another user who managed to cause it.
The function that fetches/prepares/sends data looks like this:
function postForm(content, action, update) {
loader('show');
var popup = content.parent();
var children = content.find(".input");
var data = {}
var elements = [];
data['elements'];
$( children ).each(function() {
var child = {};
child['name'] = $(this).attr('data-name');
if ($(this).is(':checkbox')) {
child['value'] = $(this).is(":checked");
} else {
child['value'] = $(this).val();
}
elements.push(child);
});
data.elements = elements;
data.request = action;
dataPost = JSON.stringify(data);
console.log(dataPost);
ajaxRequest = $.ajax({
type: "POST",
url: "/?page=ajax",
data: dataPost,
dataType: 'json',
success: function(response) {
loader('hide');
console.log(response);
if (update) {
$(update.element).load(update.url+" "+update.element+" > *");
checkError = doExtra(response, update.extra);
}
if (checkError == false) {
popup.fadeOut();
}
}
});
return false;
}
The note section is just a textarea with the class 'input' (which is looped through and fetched).
I don't think there will be a solution for the exact problem, however, I'm looking for an explanation for the modification of the string. The application works perfectly, except for this very rare case.
Question marks (??) are replaced with a jQuery time stamp. To fix, I had to add jsonp: false to the parameters. Final ajax:
ajaxRequest = $.ajax({
type: "POST",
url: "/?page=ajax",
data: dataPost,
dataType: 'json',
jsonp: false,
success: function(response) {
loader('hide');
console.log(response);
if (update) {
$(update.element).load(update.url+" "+update.element+" > *");
checkError = doExtra(response, update.extra);
}
if (checkError == false) {
popup.fadeOut();
}
}
});

Dynamic html elements show only when going through debugger

I'm working on project that simulates Twitter and I'm using HTML + JS on client and WCF services on server side (ajax calls), and Neo4J as database.
For example:
in $(document).ready(function ()
there is DisplayTweets service call -> DisplayTweets(username)
function DisplayTweets(userName) {
$.ajax(
{
type: "GET", //GET or POST or PUT or DELETE verb
url: "Service.svc/DisplayTweets", // Location of the service
data: { userName: userName },
contentType: "application/json; charset=utf-8", // content type sent to server
dataType: "json",
processdata: true, //True or False
success: function (msg) //On Successfull service call
{
DisplayTweetsSucceeded(msg);
},
error: function () // When Service call fails
{
alert("DISPLAY TWEETS ERROR");
}
}
);
}
and then DisplayTweetsSucceeded(msg) where msg would be json array of users tweets
function DisplayTweetsSucceeded(result)
{
for (var i = 0; i < result.length; i++)
{
var tweet = JSON.parse(result[i]);
var id_tweet = tweet.id;
var content_tweet = tweet.content;
var r_count_tweet = tweet.r_count;
NewTweet(null, id_tweet, content_tweet, r_count_tweet);
}
}
Function NewTweet is used for dynamic generating of tweets.
Problem is when I first load html page, nothing shows up, neither when I load it multiple times again. It only shows when I go through Firebug, line by line.
I'm presuming that maybe getting data from database is slower, but I'm not sure and also have no idea how to solve this. Any help will be very much appreciated, thank you in advance!

JQuery AutoComplete From XML (Dynamic Results)

Perhaps I'm not understanding this concept (I'm an AJAX/javascript/Web newbie). I'm using the JQuery autocomplete feature and if I specify a small, limited items flat file (suggestions.xml) the function works fine, but when I use an actual production data file (3 MB) of suggestions the script doesn't work at all.
So I created a web service that generates XML based on the characters in the textbox but it appears this JQuery doesn't run on each keypress, rather only when the page first loads. Obviously, for this function to be of any use it needs to fetch results dynamically as the user types into the input field.
$(document).ready(function () {
var myArr = [];
$.ajax({
type: "GET",
// this line always sends the default text; not what the user is typing
url: "Suggestions.aspx?searchString=" + $("input#txtSearch").val(),
dataType: "xml",
success: parseXml,
complete: setupAC,
failure: function (data) {
alert("XML File could not be found");
}
});
function parseXml(xml) {
//find every query value
$(xml).find("result").each(function () {
myArr.push({ url: $(this).attr("url"), label: $(this).attr("name") + ' (' + $(this).attr("type").toLowerCase() + ')' });
});
}
function setupAC() {
$("input#txtSearch").autocomplete({
source: myArr,
minLength: 3,
select: function (event, ui) {
$("input#txtSearch").val(ui.item.label);
window.location.href = ui.item.url;
//alert(ui.item.url + " - " + ui.item.label);
}
});
}
});
On the server I expected to see a few requests corresponding to the characters the user is typing into the search box but instead I get a single message:
2013-10-18 22:02:04,588 [11] DEBUG baileysoft.mp3cms.Site - QueryString params: [searchString]:'Search'
My flat file of suggestions appears to be way to large for JQuery to handle and my web service script is never called, except when the page is first loaded.
How do I generate suggestions dynamically as the user is typing in the search box if I can't run back to the database (via my web service) to fetch suggestions as the user is typing?
Ok, I got it all worked out.
On the ASPNET side; I created a form to receive and respond to the AJAX:
Response.ContentType = "application/json";
var term = Request.Form["term"];
var suggestions = GetSuggestions(term); // Database results
if (suggestions.Count < 1)
return;
var serializer = new JavaScriptSerializer();
Response.Write(serializer.Serialize(suggestions);
On the AJAX side I modified the js function:
$("input#txtSearch").autocomplete({
minLength: 3,
source: function (request, response) {
$.ajax({
url: "Suggestions.aspx",
data: { term: $("input#txtSearch").val() },
dataType: "json",
type: "POST",
success: function (data) {
response($.map(data, function (obj) {
return {
label: obj.Name,
value: obj.Url
};
}));
}
});
},
select: function (event, ui) {
$("input#txtSearch").val(ui.item.label);
window.location.href = ui.item.value;
}
});
Everything is working as expected now.
Hope this helps someone else who might get stuck trying to figure out JQuery stuff for ASPNET.

How to bind a controls data using jQuery and Static Page Method?

Goal: Call a server side method asynchronously from changing a dropdown to get data and populate a separate listbox not using UpdatePanels.
Currently I'm using a static ASP.NET page method asynchronously using jQuery and an ajax call as shown in this post (How to wire up a DropDownList to make AJAX calls to the server?) and it is working well.
The whole purpose was to prevent using the UpdatePanel tangled mess that I had been in previous years and this seems to be a good alternative. What I didn't realize is that the page method has to be static and you can not access any of the page's controls or context. So trying to make this call from a dropdown selection to populate another control's data is not possible. I can't see the other controls.
So what I'd like to do before I give up and go back to updatepanels is try to do 1 of the following:
Have my static page method return a json string with my collection data that I then use in the original jQuery method wired up to the change method of the dropdown to populate the separate listbox.
Same as above but return a .NET IList<> or comparable if returning json is not a good idea.
Point is I want that static method to return the needed data to bind to my listbox control. However I don't know how to do this. Here is my current jQuery method:
<script type="text/javascript">
$(document).ready(function () {
// Add the page method call as an onclick handler for the control.
$("<%= MyDDL.ClientID %>").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/MyDDL_SelectedIndexChanged",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
});
});
</script>
Here is the original dropdown:
<asp:DropDownList ID="MyDDL" runat="server" Width="340px" />
Here is the control that needs populated based on the selection of the dropdown after calling the static method named MyDDL_SelectedIndexChanged:
<asp:ListBox ID="ListBox2" runat="server" Width="340px" SelectionMode="Multiple" />
Here is my current static page method:
[WebMethod]
public static string MyDDL_SelectedIndexChanged()
{
var myClass = new MyClass()
var data = myClass.GetDataCollection()
JavaScriptSerializer serializer = new JavaScriptSerializer();
string jsonString = serializer.Serialize(data);
}
Is there a way to take this returned data and bind it in the jQuery method above? My bailout is to go back to using an UpdatePanel where my server-side method can access other controls, but I really do not want to do this.
There is a javascript project called jsRender that may be what you need:
http://weblogs.asp.net/stevewellens/archive/2011/12/01/goodby-jquery-templates-hello-jsrender.aspx
I actually was looking for a more complete exaample and have the solution working with the code below:
$(document).ready(function () {
MyDDL_OnChangeHandler();
});
function MyDDL_OnChangeHandler() {
// Add the page method call as an change handler for the MyDDL DropDownList.
// This will call the static page method, and use the returned results to populate the 'MyListBox' listbox control.
$('#<%=MyDDL.ClientID %>').change(function () {
var val = $(this).val();
var text = $(this).children("option:selected").text();
var $lbxCtrl = $('#<%=MyListBox.ClientID %>');
$lbxCtrl.attr('disabled', 'disabled');
$lbxCtrl.empty();
$lbxCtrl.append('<option value="0">< Loading Please Wait... ></option>');
$.ajax({
type: "POST",
url: "Default.aspx/MyDDL_SelectedIndexChanged",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{'ID':'" + val + "', 'Name':'" + text + "'}",
success: function (data) {
$lbxCtrl.removeAttr('disabled');
$lbxCtrl.empty();
if (data.d == null) {
return;
}
$.each(data.d, function (i, data) {
$users.append('<option value="' + data.Value + '">' + data.FullName + ' (' + adUser.data+ ')' +'</option>');
});
},
error: function () {
$lbxCtrl.empty();
$lbxCtrl.append('<option value="0">< Error Loading Data ></option>');
alert('Failed to retrieve data.');
}
});
});
As Michael B mentioned in the comments, you can handle any data returned from the ajax call by using success:
<script type="text/javascript">
$(document).ready(function () {
// Add the page method call as an onclick handler for the control.
$("#<%= MyDDL.ClientID %>").click(function () {
$.ajax({
type: "POST",
url: "Default.aspx/MyDDL_SelectedIndexChanged",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
// do stuff with the "data" that is returned
},
error: function(data) {
// handle any errors here
}
});
});
});
</script>

Categories