How to use framework7 preloader inside a function - phonegap

I have this simple login function and I want to add a preloader, after trying what's in their doc I can't make the preloader show any tips why? http://v2.framework7.io/docs/preloader.html source.
$$('.button-login').on('click', function (e) {
app.preloader.show();
var username = $("#username").val();
var password = $("#password").val();
if(username != '' && password !='' ){
app.request({
url: 'https://server/login',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
'username': username,
'password': password
}),
type: "POST",
dataType: "json",
crossDomain: true,
headers: {'Authorization' : 'Basic ' + btoa(username + ':' + password)},
error: function (data) {
app.preloader.hide();
app.dialog.alert('Invalid username or password!', 'Login Error');
},
success: function (data) {
app.dialog.alert('Welcome ' + username, 'Login Success');
localStorage.setItem('token', data.token);
localStorage.setItem('authorization', 'Basic' + btoa(username + ':' +password));
localStorage.setItem('username', username);
app.preloader.hide();
app.loginScreen.close();

Did you used var app = new Framework7(); to define app?
Is there some errors in console?
I made jsfiddle for you. Check it here.
If you want to hide preloader overlay after ajax call use dom7: $$('.preloader').hide();

Related

Making AJAX call to MVC API

I am trying to make an API call with ajax:
svc.authenticateAdmin = function (id, code) {
$.ajax({
url: 'api/event/authenticate',
data: { 'id': id, 'code': code },
datatype: 'json',
contentType: 'application/json',
type: 'GET',
success: function (data) {
App.eventBus.publish('authenticationComplete', data);
}
});
};
The method in the API Controller:
[ActionName("All")]
public bool Authenticate(int id, string code)
{
var repo = new MongoRepository<Event>(_connectionString);
var entry = repo.FirstOrDefault(e => e.Id == id);
return entry.AdminPassword == code;
}
But I am getting a 404 error: urlstuff/api/event/authenticate?id=123&code=abc 404 (Not Found)
I have copied the implementation from a number of known working calls (that I did not write). That look like:
svc.getEventFromCode = function (code) {
$.ajax({
url: '/api/event/',
data: { 'code': code },
dataType: 'json',
type: 'GET',
success: function (data) {
App.eventBus.publish('loadedEvent', data);
App.eventBus.publish('errorEventCodeExists');
},
error: function () {
App.eventBus.publish('eventNotFound', code);
}
});
};
and
svc.getEventPage = function (pageNumber) {
$.ajax({
url: '/api/event/page/',
data: { 'pageNumber': pageNumber },
dataType: "json",
contentType: "application/json",
type: 'GET',
success: function (data) {
App.eventBus.publish('loadedNextEventsPage', data);
}
});
};
But neither has to pass in 2 parameters to the API. I'm guessing it's something really minor :/
Your action name is called "Authenticate", but you have included the following which will rename the action:
[ActionName("All")]
This makes the URL
/api/event/all
The problem lies in your url.
Apparently, ajax interpret / at the start of the url to be root
When the application is deployed on serverserver, its URL is something like http://localhost:8080/AppName/
with api/event/page/, ajax resolve the URL to http://localhost:8080/AppName/api/event/page/ or an url relative to your current directory.
However, with /api/event/page/, the URL is resolved to http://localhost:8080/api/event/page/
Hope it helped.

How to format response to jQuery AutoComplete

Im trying to use jQuery AutoComplete but all i get is a single item with all results all in it.
I have this ASP.Net WebMethod:
[WebMethod]
public static string FetchCompletionList(string term)
{
var json = JsonConvert.SerializeObject(CustomerProvider.FetchKeys(term, 8));
return json;
}
being called by this script:
$("[id$='txtLKey']").autocomplete({
minlength: 2,
source: function(request, response) {
$.ajax({
type: "POST",
url: "/Views/Crm/Json/Json.aspx/FetchCompletionList",
data: '{term: "' + $("[id$='txtLKey']") .val() + '", count: "8"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
response(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseText);
alert(textStatus);
alert(errorThrown.toString());
}
});
}
});
And the result is this:
When what I actually want is a list of options the user can select i.e. each NZ should be an item in a list.
There are two problems here,
you need to pass data.d to response like response(data.d).
your value string is invalid it should be {"d":["NZ0008","NZ0015","NZ0017","NZ0018","NZ0026","NZ0027","NZ003??1","NZ0035"‌​]}

values are not saved in session array

In my controller action i initialize a session of array and inserting values. These values are coming from the client side through ajax, so the page is not refreshed while inserting these values to an array.But suprisingly every time it iniatialize a new session instead of inserting to the same defined session. Here is my code
controller
def receive_tags
parser = Yajl::Parser.new
#hash = parser.parse(request.body.read)
log=Logger.new(STDOUT)
log.error(#hash)
session[:tags]||=[]
session[:tags] << #hash["tag"]
unless session[:tags].empty?
log.error(session[:tags] ) #this keeps printing the current value i was expecting it to print a list of values including the previous
end
render :nothing=>true
end
Ajax
var myobj={tag:"mytag"};
$.ajax({
url: 'ips/receive_tags',
type: 'post',
contentType: 'application/json; charset=UTF-8',
accept: 'application/json',
dataType: 'json',
data:JSON.stringify(myobj),
success: function(res) {
if (res.ImportResponse !== void 0) {
console.log('Success: ' + res);
} else if (res.Fault !== void 0) {
console.log('Fault: ' + res);
}
},
error: function() {
console.error('error!!!!');
}
});
This sounds like the browser isn't saving cookies, which would explain the behavior you are seeing where the session is reinitialized every time. To confirm this, you can do
print "Session ID: #{request.session_options[:id]}"
in your action and see if the session id changes for each request. If it does, check your browser privacy settings and see if it is saving any cookies.
Finally i figured it out, The problem is i wasn't setting the request header for the token before sending ajax call so Rails was receiving data without the token, thus kept assuming it is a new object for every request.You can read more here.To set the request header add
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
}
Below is my ajax function that works
var myobj={tag:"mytag"};
$.ajax({
url: 'ips/receive_tags',
type: 'post',
contentType: 'application/json; charset=UTF-8',
accept: 'application/json',
dataType: 'json',
data:JSON.stringify(myobj),
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
}
success: function(res) {
if (res.ImportResponse !== void 0) {
console.log('Success: ' + res);
} else if (res.Fault !== void 0) {
console.log('Fault: ' + res);
}
},
error: function() {
console.error('error!!!!');
}
});

Jquery Mobile asp.net webservice parameter

$.ajax({
type: "POST",
url: "ContactList.asmx/GetContacts",
data: "{'start':" + 1 + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$.mobile.showPageLoadingMsg();
console.log(msg.d);
},
error: function () {
$('[data-url="' + tempdataurl + '"] div[data-role="content"]').html("Error loading article. Please try web version.");
}
});
how can I send Muttiple paramater? I have 2 parameter start and count . please help.
Please try this code
data: {start: 1 ,count:5}

How do I pass a textbox value to jQuery .ajax method?

Here's my jquery method:
$.ajax({
type: "GET",
url: "Home/GetSocialMentionBlogs/"
dataType: "json",
success: function (data) {
var obj = JSON.parse(data);
$.each(obj.items, function (i, item) {
$("<strong><p>" + item.title + "</strong></p>").appendTo("#blogs");
if (i == 5) return false;
});
}
});
What I want to do is when a user clicks a button, callt his method, and pass in the value of a textbox so that the URL will now be:
url: Home/GetSocialMentionBlogs/value from text box
Of course I'll need to URL encode that, but as of now, I don't know how to pass in values to this .ajax function.
I'm completely new to jQuery and MVC so pardon my ignorrance ont he subject so far.
Well if the input field has an "id" value you'd just do
url: "Home/GetSocialMentionBlogs/" + $('#inputFieldId').val(),
If all you've got is the name, then you could do:
url: "Home/GetSocialMentionBlogs/" + $('input[name=inputFieldName]').val(),
Is that all you need to do or am I missing some detail?
Oh and to URL encode just use the Javascript encodeURIComponent() function.
$.ajax({
type: "GET",
url: "Home/GetSocialMentionBlogs/" + $('#textBoxID').val(),
dataType: "json",
success: function (data) {
var obj = JSON.parse(data);
$.each(obj.items, function (i, item) {
$("<strong><p>" + item.title + "</strong></p>").appendTo("#blogs");
if (i == 5) return false;
});
}
});

Resources