Dynamic html elements show only when going through debugger - javascript

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!

Related

error with sending javascript parametre to action asp net boilerplate

Im doing the biggest project of my life and im stocked with error,
there is the story:
I made a dropdownlist of countries, when you choose the country from the select list i use javascript to send countries ID to state function:
$("#Country").change(function () {
var Index = $(this).val();
$.ajax({
url: '/Company/State',
type: "POST",
dataType: 'html',
data: { CountryId: Index },
success: function (data) {
$('#State').empty();
$('#State').append($('<option>').attr("value", "").text("Select state"));
var state = JSON.parse(data)["state"];
for (var i = 0; i < state.length; i++) {
$('#State').append($('<option>').attr("value", state[i].id).text(state[i].name));
}
}
});
and then my droplist doesnt work and i get the following error and my drop list doesn't show anything:
"Failed to load resource: the server responded with a status of 400 (Empty or invalid anti forgery header token.)"
and when i disable the antiforgerytoken everything works perfectly
[HttpPost]
[DisableAbpAntiForgeryTokenValidation]
public string State(GetStateInput input)
there is my question:
We need the antiforgerytoken and we can not disable it, so how i overcome the error without disabling the antiforgerytoken?
Preferably, add this in your _Layout.cshtml or view:
#{
SetAntiForgeryCookie();
}
Alternatively, intercept XMLHttpRequest:
(function (send) {
XMLHttpRequest.prototype.send = function (data) {
this.setRequestHeader(abp.security.antiForgery.tokenHeaderName, abp.security.antiForgery.getToken());
return send.call(this, data);
};
})(XMLHttpRequest.prototype.send);

How to create a secure token for an app?

Im working on a simple app, that allow the user to login. Im using an ajax function pass the values to a PHP file(on a different domain). If the user and the password are correct the page display echo"success" and im using that word to validate and create a random key to allow the user access to a private page.
I was reading that you can also add a header token, it is possible to add that to my current code..
Iam new in developing "app", hope some one can point in the right direction on what is the best way to do this.
var username = $("#username").val();
var password = $("#pass").val();
var dataString = "username="+username+"&pass="+password+"&insert=";
$.ajax({
type: "POST",
url: "url",
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function() {$('#loginButton').val('Connecting...');},
success: function(data)
{
if(data == " success")
{
alert("Success");
returnHash();
}
if(data == " Login failed")
{
alert("There's a problem with username/password!");
$('#loginButton').val('Submit');
}
}
});
function returnHash()
{
letters = "abcdefghijklmnopqrstuvwxyz1234567890".split("");
window.token="";
for(i=0;i<64;i++){
window.token += letters[Math.floor(Math.random()*letters.length)];
}
success();
}
To create a real unique hash, use the current time with an random generated number like in the code below:
var dateForHash = (new Date()).valueOf().toString();
var createRandomNum = Math.random().toString();
crypto.createHash('sha1').update(dateForHash + createRandomNum).digest('hex');
You can also use crypto.randomBytes()- this hash is practical unique but not theoretical.
var hash = crypto.randomBytes(20).toString('hex');
I would recommend the second way for this type of use.

Progress bar to download data SQLITE javascript

I have a scenario where I have to show a progress bar to load data to sqlite from online server.I am loading a few master tables and transaction tables. I have created the sqlite tables and then called ajax to get data and have loaded in sqlite:
insert_sur_category(function(ret_insSur)
{
//calls ajax gets data from php and then inserts into sqlite using foreach loop and insert command
if(ret_insSur=="success")
{
insert_districts(function(ret_dis)
{
}
}
}
sample ajax code
function insert_sur_category(callBack){
//alert("ding here");
var i;
var separator='surveymaster';
//alert(sessionStorage.url+"load_masters.php?separator="+separator);
$.ajax({
type: "POST",
url: sessionStorage.url+"load_masters.php?separator="+separator,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){
obj = JSON.stringify(data);
obj1 = JSON.parse(obj);
if(obj1!=0)
{
var i=0;
$.each(data, function(i, item) {
myDB.transaction(sur_category);
function sur_category(tx){
tx.executeSql('INSERT INTO survey_category (sur_category_id, sur_category_name,last_updated) VALUES("'+obj1[i].id+'","'+obj1[i].name+'",datetime())');
}
// sur1();
//callBack("success");
});
sur1();
callBack("success");
}
else
{
//alert("sdfdsf");
callBack("failed");
}
},
complete: function(){
}
});
}
After all callbacks are success I have given a alert to say data loaded successfully.However the alert comes long before the data is loaded.I am checking using google chrome.Any help Please
transaction is an asynchronous call. To make synchronous call, you can check this link and follow it's answer.
It will surely help you.

JQuery $.ajax not posting multiple vars

Hi Guys I have the following function that is called on a link:onclick(), but for some reason the $.ajax does nothing at all - have even stripped my php code to only dump the $_POST var but I still get no feedback from the function - all i get is the alert msg - which is also just there for test purposes...
called there:
Save
function saveMyGame(){
var usern = $('#usern').attr('value');
var usrPoints = $('#userPoints').attr('value');
var usrLevel = $('#userlevel').attr('value');
var saveState = this.imgPath;
alert('Saving your game: '+usern+' Points: '+usrPoints+' Level: '+usrLevel+' state phase: '+saveState);
e.preventDefault();
var svGame = {act:'saveGame',user:usern, Points:usrPoints, Level:usrLevel, saveGState:saveState} ;
$.ajax({
url: "game/lib/updateGame.php",
type: "POST",
cache: false,
data: svGame,
dataType: "html",
success: function(svGame) {
$(".traget").html(svGame).fadeIn('slow');
}
});
}
the PHP code is suppose to check act, then verify that all required info is passed, than process the request or display an error msg...
<?php
if(isset($_POST['act']) && $_POST['act'] == 'saveGame') {
//Process save game request
/*if(isset($_POST['user']) && isset($_POST['userPoints']) && isset($_POST['userLevel']) && isset($_POST['saveGState']) ) {
$Game->saveGame();
echo'<br>....'.$_POST['user'];
} else {
echo 'Please provide correct information for saving...';
}
*/
echo var_dump($_POST);
}
Url in your ajax request has relative path url: "game/lib/updateGame.php", without slash in the beginning of the url like url: "/game/lib/updateGame.php",.
So maybe if your page adress differ from root (for example http://yourdomain.com/games/), full path will be http://yourdomain.com/games/game/lib/updateGame.php and therefore the server method is not performed.

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.

Categories