I need to get response['cloudUrl'] from my AJAX to my fb share dialog, all happening at the same time as user clicks on #sharebutton.
I can't put my code in AJAX success, if I wrap it in something else other than user click event, browser will most likely to block my fb share popup.
To make things clearer, I can get response['cloudUrl'] in the AJAX success callback.
function submitDataToFbShare(){
$.ajax(
{
url : 'www.testing.com/fb-data")',
type : 'POST',
data :
{
name: $('.nameField').val(),
personality_index: $('.nameField').val(),
country: $( "#countryList select:first-child option:selected").attr("value"),
},
dataType:'json',
success : function(response)
{
console.log("Successfully saved!");
console.log("response " + response['cloudUrl']);
},
error : function(request,error)
{
console.log("Error saving data!");
}
});
}
$('#sharebutton').click(function(e){
submitDataToFbShare();
e.preventDefault();
FB.ui({
method: 'feed',
link: "www.test.com",
name: "test",
description: "testing description",
picture: response['cloudUrl'],
}, function(response)
{
if (response != null || response != undefined)
{
console.log("success");
}
else
{
console.log("failed");
}
});
});
Related
I have the following code snippet here. I am trying to refresh the page with /Events/Index page when the Ajax request is successful. However, inside the success method, I see that the response variable is available in else if case, but it is not available in the if case. Inside if case, I get an error: The name response does not exist in the current context.
The Ajax call from the View is as follows:
$.ajax({ url: "/Events/DeleteEvent", data:data, async: true }).success(function (response) {
if (response != "" || response != "Event not found!") {
swal("Deleted!", "The event has been deleted.", "success");
window.location.href = '#Url.Action("Index", "Events", new { EventId = response })';
}
else if (response == "Event not found")
swal("Cancelled!!!", "Error : " + response, "error");
});
This is how I am sending the response to the success part of the Ajax call from the Controller:
if (eventid > 0)
{
...
return Json(id);
}
else
return Json("Event not found");
// id is an integer value that I want to send to success in Ajax.
Am I going wrong anywhere?
The response is a client-side variable which contains AJAX response, hence you cannot use it as routeValues parameter value inside #Url.Action() helper which contains server-side code because the script doesn't executed yet while action URL is generated, and response variable doesn't declared yet in server-side code.
To fix the issue, try using plain query string to insert EventId parameter:
$.ajax({
url: "/Events/DeleteEvent",
data: data,
async: true,
success: function (response) {
if (response !== "" || response != "Event not found!") {
swal("Deleted!", "The event has been deleted.", "success");
// use query string because Url.Action helper runs server-side
window.location.href = '#Url.Action("Index", "Events")' + '?EventId=' + response;
} else if (response == "Event not found") {
swal("Cancelled!!!", "Error : " + response, "error");
}
}
});
Or use a placeholder from server-side and then change parameter value to response with replace():
$.ajax({
url: "/Events/DeleteEvent",
data: data,
async: true,
success: function (response) {
if (response !== "" || response != "Event not found!") {
swal("Deleted!", "The event has been deleted.", "success");
// the URL generated server-side with placeholder
var targetUrl = '#Url.Action("Index", "Events", new { EventId = "xxx" })';
// replace placeholder with event ID
window.location.href = targetUrl.replace("xxx", response);
} else if (response == "Event not found") {
swal("Cancelled!!!", "Error : " + response, "error");
}
}
});
Additional note:
Better to use client-side property in the response to differentiate between success and error conditions, as provided in example below:
if (eventid > 0)
{
...
return Json(new { id = id });
}
else
return Json(new { message = "Event not found" });
AJAX call
$.ajax({
url: '#Url.Action("DeleteEvent", "Events")',
data: data,
async: true,
success: function (response) {
if (typeof response.id !== 'undefined' && response.id != null) {
swal("Deleted!", "The event has been deleted.", "success");
// use query string because Url.Action helper runs server-side
window.location.href = '#Url.Action("Index", "Events")' + '?EventId=' + response.id;
} else if (typeof response.message !== 'undefined' && response.message != null) {
swal("Cancelled!!!", "Error : " + response.message, "error");
}
}
});
Try this:
$.ajax({
url: "/Events/DeleteEvent",
data: data,
async: true,
success: function (response) {
if (response !== "" || response != "Event not found!") {
swal("Deleted!", "The event has been deleted.", "success");
window.location.href = '#Url.Action("Index", "Events", new { EventId = "' + response + '" })';
} else if (response == "Event not found") {
swal("Cancelled!!!", "Error : " + response, "error");
}
}
});
You have some errors in your syntax. Look at the code and you'll see the difference in the syntax.
Let me know how this goes.
Pass response value instead of its name
'#Url.Action("Index", "Events", new { EventId = "' + response + '" })'
Hello I am not good with ajax.I want to check my login info and return either 'success' or 'fail'.Buy my ajax seems to have an error.
var user = $('.username').value();
var pass = $('.password').value();
$.ajax({
type : 'POST',
url : 'login_check.php',
data : {
'username': user,
'password': pass
},
beforeSend: function() {
$("#Loading").show();
},
success : function(response) {
if(response=="success" && response!=="fail") {
$('.status').html("Success! Now logging in ......");
setTimeout(' window.location.href = "index.php"; ',4000);
} else {
$('#Loading i').hide();
$('.status').html("Login fail! Please use correct credentials....");
setTimeout(' window.location.href = "login.php"; ',4000);
}
}
});
Can anyone points me out?
The reason you are getting error is because your javascript is getting break(giving error) at $('.username').value(); as there is no value() function. If you open console you get this error. So because of this rest of script is not working. So change $('.username').value(); to this $('.username').val(); and same for the var pass = $('.password').value(); change to var pass = $('.password').val(); and also you don't need if condition as mention in comment. Your final code will be something like this.
var user = $('.username').val();
var pass = $('.password').val();
$.ajax({
type: 'POST',
url: //some url
data: {
'username': user,
'password': pass,
},
beforeSend: function() {
//some code
},
success: function(response) {
// some code which you want to excute on success of api
},
error: function(xhr, status, error) {
// some code which you want to excute on failure of api
}
});
I dont have the whole code for your app but when it come to your ajax request your code should look like this , for a more accurate answer please show the error that you are getting
var user = $('.username').val();
var pass = $('.password').val();
$.ajax({
type : 'POST',
url : 'login_check.php',
data : {
'username':user,
'password':pass,
},
beforeSend: function()
{
$("#Loading").show();
},
success : function(response)
{
$('.status').html("Success! Now logging in ......");
setTimeout(()=>{ window.location.href = "index.php"; },4000);
},
error: function(xhr, status, error) {
$('#Loading i').hide();
$('.status').html("Login fail! Please use correct credentials....");
setTimeout(()=>{ window.location.href = "login.php"},4000);
}
});
Your response needs to be a PHP echo that returns a string with a value of either ”success” or ”fail”.
Your PHP response after successful login:
echo(‘success’);
Your PHP response after failed login:
echo(‘fail’);
I am trying simple login form with username, password fields in jquery mobile. Username and password should validate from ajax page. In my system i am able to get response perfectly. When convert my code to .apk uging phonegap, my mobile unable to receive response from ajax page. Any code inside success function is not working, Directly it goes to error function. What am i doing wrong?
$(document).on('pagebeforeshow', '#login', function(){
$(document).on('click', '#submit', function() {
if($('#username').val().length > 0 && $('#password').val().length > 0){
$.ajax({
url : 'liveurl/check.php',
data: {action : 'login', formData : $('#check-user').serialize()},
type: 'post',
beforeSend: function() {
$.mobile.loading(true); },
complete: function() {
$.mobile.loading(false);
},
success: function (result) {
if(result.status == "success"){
resultObject.formSubmitionResult = result.uname;
localStorage["login_details"] = window.JSON.stringify(result);
$.mobile.changePage("#second");
}else{
$.mobile.changePage("#login");
alert("incorrect login");
}
},
error: function (request,error) {
alert(error);
}
});
} else {
alert('Fill all nececery fields');
}
return false;
});
});
Two points:
Your APK is not running on your server. That means, that your url is wrong it needs to be something like:
url: "http://www.your_server.com/liveurl/check.php"
You have to whitelisten every external url, please read the docs for that:
http://cordova.apache.org/docs/en/dev/guide/appdev/whitelist/index.html
I am trying to use Facebook Graph API to get information about users who logged in via Facebook.
At the beginning, I was using only one function and no errors occurred; But then, I added another function that uses Facebook API. From that moment, none of the functions works. Only when I remove the new function, the old one works again...
I guess the code will be much understandable than what I described above:
function fb_login(){
FB.login(function(response) {
if (response.authResponse) {
access_token = response.authResponse.accessToken; //get access token
user_id = response.authResponse.userID; //get FB UID
FB.api('/me', function(response) {
user_email = response.email; //get user email
$.ajax({
type: "POST",
url: "http://*******/ajax.php",
data: { action: "login", id: user_id, email: user_email, first_name: response.first_name, last_name: response.last_name }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
} else {
//user hit cancel button
console.log('User cancelled login or did not fully authorize.');
}
}, {
scope: 'publish_actions,email,read_stream,publish_stream'
});
}
The function above will work unless the function below exists.
function update_autopost(form)
{
FB.api('/me', function(response) {
var autopost_value = form.autopost.checked;
if(autopost_value == false)
{
autopost_value = "off";
}
else{
autopost_value = "on";
}
$.ajax({
type: "POST",
url: "http://*********/ajax.php",
data: { action: "update", id: response.authResponse.userID, autopost: autopost_value }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
}
To be more detailed, after adding the second function, two things happens:
The first function stops working.
The second function is not able to get information from Facebook Graph API (for instance, response.authResponse.userID doesn't work).
I am using the JavaScript SDK, and the documentation says that I can call a method that will create a dialog allowing the user to select and invite multiple friends to my app. Here is the code I am using:
FB.ui(
{
method: 'apprequests',
message: 'Invite your friends to use this app'
}, function(response)
{
alert(response);
});
This code does not work. An error is produced when it is run: "Error: c is null" on line 18 of http://connect.facebook.net/en_US/all.js. What am I doing wrong?
This is what I use. It has all of the error processing in it too:
FB.ui
(
{
method : 'apprequests',
data: '',
display: 'dialog',
title : 'Invite a Friend',
message: 'I just sent you an invitation to play My Game.',
filters: ['app_non_users']
}, function(response)
{
if (response && response.request_ids)
{
jQuery.ajax
(
{
url: 'Invite_Request.php',
type: 'GET',
data:
{
'request_id': response.request_ids, 'signed_request': "<?php echo $_SESSION["SR"] ?>"
},
success: function(data)
{
if (data.error)
{
//jQuery("#inviteMessages").html('successful call, but error! ' + data.message);
}
else
{
jQuery("#inviteMessages").html('successful request! ' + data.message);
}
},
error: function(xhr, status, msg)
{
//jQuery("#inviteMessages").html('unsuccessful call, error! ' + status + ' ' + msg);
}
}
);
//jQuery("#inviteMessages").html('Successful request! Request ID = ' + response.request_ids);
}
else
{
//jQuery("#inviteMessages").html('Request failed!');
}
}
);