Data is not going through the ajax code - javascript

I'm using Facebook login feature & transferring some variables to other page through ajax. This particular ajax code isn't working, data is not going through. However I've other ajax code in other pages that works pretty good.
I'm not able to find the defect in the code.
Here is the code:
Page where ajax is called
<script type='text/javascript'>
window.fbAsyncInit = function() {
FB.init({
appId : 'XXXXX',
status : false,
cookie : true,
xfbml : true
});
}
function Login()
{
FB.login(function(response) {
if (response.authResponse)
{
getUserInfo();
}
else
{
console.log('User cancelled login or did not fully authorize.');
}
},{scope:'email,public_profile'});
}
function getUserInfo() {
FB.api('/me/permissions', function(response) {
var permission_response = JSON.stringify(response);
var permissions = eval('('+permission_response+')');
$.ajax({
type: "POST",
url: "/ajax_save_facebook_data.php",
data: {permissions:permissions},
success: function(option){
alert(option); // Nothing coming here, blank alert
}
});
});
}
AJAX Page
$permissions=$_POST['permissions'];
echo $permissions;
Anybody can help in this? I will really appreciate it.

FB.api is asynchrone function, so your var permissions doesn't exist when you do your ajax call.
Try:
function getUserInfo() {
FB.api('/me/permissions', function(response) {
var permission_response = JSON.stringify(response);
var permissions = eval('('+permission_response+')');
$.ajax({
type: "POST",
url: "/ajax_save_facebook_data.php",
data: {permissions:permissions},
success: function(option){
alert(option); // Nothing coming here, blank alert
}
});
});
}

Related

Laravel 8 and ajax

Never used ajax before and I'm quite new to Laravel as well.
I'm running a function where it gets the information from the form and i have no idea how to do the request with the information that I need.
function myFunction() {
var x = document.getElementById("frm1");
//console.log(x.elements.personSearch.value);
var details = x.elements.personSearch.value;
document.getElementById("personValidation").innerHTML = "";
if (
!details.match(
/\b[a-zA-Z ]*\\[a-zA-Z ]*\\[0-3][0-9][0-1][0-9][0-9]{4}\b/g
)
) {
document.getElementById("personValidation").innerHTML =
"Your search does not match the required format";
return;
}
$.ajax({
url: "/api/pnc/person",
type: "POST",
dataType: "json",
success:function(amount) {
console.log(amount);
}
});
``` Javascript
public function person(Request $request)
{
$request->validate([
'search' => 'required'
]);
return "test";
}
You need to Follow 3 steps for Ajax Request-
1. Setup Ajax Header bottom of your code. I mean before </html> add below code.
<script>
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
2. If you don't use Header Then you can use.
<script>
$(document).ready(function () {
$("#your_form_id").submit(function(e) {
var details = $('#details_input_id').val();
if(your_condition){
$.ajax({
url: "api/url",
type: "post",
data: {"_token": "{{csrf_token()}}", 'details':details},
success:function(data){
//Your response
if(data){
consol.log("Print what you want to print");
}
}
});
}else{
alert("Your search does not match the required format")
}
});
});
</script>
3. Your Route will be like ajax url
Route::post('api/url', [YourController::class, 'functionName'])->name('functionName');

using ajax with javascript to put in database

I'm trying to put the infos into my database, for that, this code is in the connexion.jsp which is a page that ask to log with facebook.
the code is supposed to be called into the Controller which is a file in java, and go into the databse.
So my problem is the fact that the code $.ajax doesn't seems to work. It doesn't give a success or error window.alert with or without function(){}.
I might have missed some information about ajax, but i can't find more info about my error.
function fbLogin() {
FB.login(function (response) {
if (response.authResponse) {
// Get and display the user profile data
getFbUserData();
$.ajax({
method: 'post',
url: '/hello/facebookconnection',
first_name: response.first_name,
last_name: response.last_name,
email: response.email,
success:
//success: function(){
window.alert('Sent User data!')//;}
,
error:
window.alert('Error in sending ajax data')
});
else {
document.getElementById('status').innerHTML = 'User cancelled';
}
}, {scope: 'email'});
}
function fbLogin() {
FB.login(function (response) {
if (response.authResponse) {
// Get and display the user profile data
getFbUserData();
$.ajax({
method: 'post',
url: '/hello/facebookconnection',
first_name: response.first_name,
last_name: response.last_name,
email: response.email,
success:
//success: function(){
window.alert('Sent User data!')//;}
,
error:
window.alert('Error in sending ajax data')
});
} else {
document.getElementById('status').innerHTML = 'User cancelled';
}
}, {scope: 'email'});
}
You have a syntax error in front of your else.

not going through the django view through ajax post data

I am doing the login throgh ajax. jquery function is working fine but its not going to the ajax url. So django view is not getting executed.
Ajax.html
$(function()
{
localStorage['domain'] = "http://122.172.64.142";
var domain = localStorage['domain'];
$('#fac1').on('click', function () {
var username = $("#username").val();
var password = $("#pwd").val();
data = {
name: username,
password: password
};
alert(domain);
$.ajax({
url: domain + "/login/login_android_here/",
type: "POST",
data: data,
success: function (response) {
alert("success");
window.location = 'file:///android_asset/www/posts.html';
},
error: function () {
alert('some error in login');
}
});
return false;
});
});
My django views.py
#csrf_exempt
def login_android(request):
print "i am in view"
if request.method == "POST":
print "you are in method"
username = request.POST['name']
password = request.POST['password']
login_api(request,username,password)
#return HttpResponseRedirect('/home/')
messages.success(request, 'You Loged In Successfully')
response = json.dumps(username)
return HttpResponse(response, mimetype="application/json")
When i click on login button i am getting alert but its not getting entered to view. Url is correct.
I would first recommend using Chrome with the developer tools console open.
You could change you alerts for console.log().
When your trying window.location = 'file:///android_asset/www/posts.html';
You are trying to access a local resource. If I post that in my Chrome developer tools I get back
Not allowed to load local resource: file:///android_asset/www/posts.html
If you would use window.location.replace("a url to your view"); this will work like a HTTP redirect.
for more information redirect page
and you should be able to see your view.
I was made a silly mistake. I provided a wrong domain address on this page. Now it worked.
localStorage['domain'] = "http://122.172.64.142";
This address was wrong. Thats why it was not able to enter in to the view.
You forgot dataType ajax param
$.ajax({
url: domain + "/login/login_android_here/",
type: "POST",
data: data,
dataType : 'json', //dataType param IS MISSING
success: function (response) {
alert("success");
window.location = 'file:///android_asset/www/posts.html';
},
error: function () {
alert('some error in login');
}
});

Cakephp Ajax Login is loggin in even with wrong data

I have a simple html form to login outside my cake structure, I send the login data via jquery to my login function:
public function login() {
if ($this->request->is('ajax')) {
$this->request->data['Appuser']['password'] = Security::hash($this->request->data['password']);
$this->request->data['Appuser']['name'] = $this->request->data['name'];
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl(array('action' => 'returnUserData')));
}else{
$this->response->body(json_encode('Login failed!'));
}
}elseif($this->request->is('post')){
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirectUrl());
}else{
$this->Session->setFlash(__('Invalid username or password, try again'));
}
}
}
The very strange thing is:
the login via post from /view/users/login.ctp form works perfectly!
When I try to login from "outside" via ajax, I am always logged in even with wrong access details and get the data from function 'returnUserData'
$('#login').click(function() {
$.ajax({
type: "POST",
url: '/api/login',
data: {
name: $("#username").val(),
password: $("#password").val()
},
success: function(data)
{
alert(data);
}
});
});
When I set a debug(); after if ($this->request->is('ajax')) I can see it, so the script seems to go into the right if section. But I don't get it, why the $this->Auth->login always return true...?

linkedin logout function(javascript API) is not working in some conditions

In my website, I have provided a facility to login via linkedin. I have used javascript API for that.
I have written below code for login.
function onLinkedInAuth() {
var isLoggedIn = document.getElementById('<%=hdnIsLoggedin.ClientID %>').value;
// Check for the session on the site
if (isLoggedIn == false || isLoggedIn == 'false') {
IN.API.Profile("me")
.fields("id", "firstName", "lastName", "industry", "emailAddress")
.result(function (me) {
//debugger;
var id = me.values[0].id;
var fname = me.values[0].firstName;
var lname = me.values[0].lastName;
var industry = me.values[0].industry;
var email = me.values[0].emailAddress;
// AJAX call to register/login this user
jQuery.ajax({
type: "POST",
url: "UserRegisterAsSeeker.aspx/LinkedinLoginOrRegister",
data: "{id:'" + id + "',fname:'" + fname + "',lname:'" + lname + "',email:'" + email + "'}",
contentType: "application/json; Characterset=utf-8",
dataType: "json",
async: true,
success: function (data) {
closeLoginWindow();
__doPostBack('<%=lnkRefreshPage.UniqueID%>', '');
},
error: function (request, status, error) {
alert('Unable to process the request at this moment! Please try again later.');
},
complete: function () {
}
});
});
}
}
Above code works fine.
And for logout i have used below function provided by linkedin
function logout() {
IN.User.logout(function () {
window.location.href = '/logout.aspx';
});
}
Problem is in logout. When we login to the site and immediately logout, it works fine but when we leave the site ideal for some time it does not logout from linkedin. We have to click 3-4 times then it works.
I don't know why it's happening. Please help if you can.

Categories

Resources