Right now I have username and password saved in cookies. My goal is to send that data to my server and then the server will send back response and I will display the response on my webpage. But before I do that I used alert() to see if it is working.
I think something is wrong with the JS:
$(document).ready(function () {
var messageType = "3";
var cookie_name = "username";
var cookie_name2 = "password";
var YouWrote = getName(cookie_name);
var YouWrote2 = getName2(cookie_name2);
var userName = YouWrote;
var password = YouWrote2;
auth(messageType, userName, password);
});
function auth(messageType, userName, password) {
$.ajax({
type: "POST",
//SEND TO SERVER URL
url: "######",
dataType: 'json',
async: false,
data: '{"messageType": "' + messageType + '", "userName": "' + userName + '", "password" : "' + password + '"}',
error: function (xhr, error) {
alert('Error!');
},
success: function (data, textStatus, jqXHR) {
alert(data.details + '\nHello ' + data.clientInfo.firstName + ' ' + data.clientInfo.lastName + '. \nBalance:' + data.clientInfo.balance);
}
})
}
These two functions will help me get the cookie data saved (this works, I have tested it):
function getName() {
if (document.cookie) {
index = document.cookie.indexOf(cookie_name);
if (index != -1) {
namestart = (document.cookie.indexOf("=", index) + 1);
nameend = document.cookie.indexOf(";", index);
if (nameend == -1) {
nameend = document.cookie.length;
}
YouWrote = document.cookie.substring(namestart, nameend);
return YouWrote;
}
}
}
function getName2() {
if (document.cookie) {
index = document.cookie.indexOf(cookie_name2);
if (index != -1) {
namestart = (document.cookie.indexOf("=", index) + 1);
nameend = document.cookie.indexOf(";", index);
if (nameend == -1) {
nameend = document.cookie.length;
}
YouWrote2 = document.cookie.substring(namestart, nameend);
return YouWrote2;
}
}
}
I turned my server off on purpose because I want to see if it will show alert("Error!"). It doesn't which means the functions aren't running properly in the document.ready.
Is there an obvious issue that I'm missing? Any help will be much appreciated.
Your functions will need to have input argument specified:
function getName(cookie_name){ ... };
function getName2(cookie_name2){ ... };
Related
I´m trying to get a list with Ajax when a modal shows up, but for some reason my method always receives a null variable. I´m sure that the issue is on the Ajax call, because if I test my method using 1 as an argument instead of the value from Ajax, it returns the list the way I wanted.
JS:
$("#visualizacao").on('show.bs.modal', function (e) {
var data = $(e.relatedTarget);
var idAviso = data.context.dataset.avisoid;
$.ajax({
type: 'GET',
url: 'ListaVisuAviso/' +idAviso,
success: function (response) {
$('#visu-table tbody').empty();
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.NOME + '</td><td>' + item.DATA_HORA + '</td><td>' + item.DEPARTAMENTO + '</td></tr>';
});
$('#visu-table tbody').append(trHTML);
$('#modal-visu').modal('show');
},
error: function (xhr) {
console.log(xhr);
}
});
$('#modalAviso').modal('show');
});
C#
[HttpGet]
public JsonResult ListaVisuAviso(string avisoId)
{
//var avisoid = 1;
var avisoid = Convert.ToDecimal(avisoId);
var query =
from a in _dataContext.TB_AVISOS_NOTIFICACOES
join b in _dataContext.VW_USUARIOS4 on a.USUARIO_PR equals b.USUARIOID
where a.AVISO_ID == avisoid
select new VisuAviso()
{
NOME = b.NOME,
DATA_HORA = a.DATA_HORA.ToString(),
DEPARTAMENTO = b.DEPARTAMENTO
};
return Json(query, JsonRequestBehavior.AllowGet);
}
I discovered what was causing the "issue". To use this way of sending the parameter, my route config on the backend was expecting it to be a parameter called "id". So I would either change my receiving parameter to "id" instead of "avisoId" like the following:
[HttpGet]
public JsonResult ListaVisuAviso(string id)
{
//var avisoid = 4;
var avisoid = Convert.ToDecimal(id);
var query =
from a in _dataContext.TB_AVISOS_NOTIFICACOES
join b in _dataContext.VW_USUARIOS4 on a.USUARIO_PR equals b.USUARIOID
where a.AVISO_ID == avisoid
select new VisuAviso()
{
NOME = b.NOME,
DATA_HORA = a.DATA_HORA.ToString(),
DEPARTAMENTO = b.DEPARTAMENTO
};
return Json(query, JsonRequestBehavior.AllowGet);
Or, I would have do specify the name of the parameter on the JS, like this "?usuarioId=", this way the route would know that it´s not the id parameter:
$("#visualizacao").on('show.bs.modal', function (e) {
var idAviso = $(e.relatedTarget).attr('data-avisoid');
$.ajax({
type: 'GET',
url: 'ListaVisuAviso/?usuarioId =' + idAviso,
dataType: 'json',
success: function (response) {
$('#visu-table tbody').empty();
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.NOME + '</td><td>' + item.DATA_HORA + '</td><td>' + item.DEPARTAMENTO + '</td></tr>';
});
$('#visu-table tbody').append(trHTML);
$('#modal-visu').modal('show');
},
error: function (xhr) {
console.log(xhr);
}
});
$('#modalAviso').modal('show');
});
I have this "click Listener" that calls and sends a userId parameter to the function-"getModalData" which then returns an array value to the variable-"arrayedUserData".
$('body').on('click', '.openModal', function () {
var userId = $(this).val(),
btnText = $(this).text(),
btnClass = '',
colorCode = '',
arrayedUserData = getModalData(userId);
if (btnText === "Delete") {
btnClass = 'danger';
colorCode = '#d9534f';
} else {
btnClass = 'warning';
colorCode = '#f0ad4e';
}
$('#actionBtn').removeClass().addClass('btn btn-' + btnClass).text(btnText);
$('#modalTitle').text('Confirm ' + btnText);
$('#S-modalbody p').text('Are you sure you want to ' + btnText + ' user: ');
$('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);
});
This is the function-"getModalData". The returned php array from the Ajax's "success" will then be passed to the variable-"UserData" that is then returned by the function.
function getModalData(passedUserId) {
var UserData;
$.ajax(
{
type: "POST",
url: "get/get_modal_data.php",
data: { passedUserId: passedUserId },
dataType: "json",
success: function (data) {
UserData = data;
}
}
);
return UserData;
}
this is the "get_modal_data.php".
<?php
include "../includes/connect.php";
if (isset($_POST['passedUserId'])) {
$UserId = mysqli_real_escape_string($con, $_POST['passedUserId']);
$getUserData = mysqli_query($con, "SELECT * FROM tblUserAccounts WHERE uaUserId = '".$UserId."'");
$uaRow = mysqli_fetch_assoc($getUserData);
$UserDataArr = array("UserId" => $uaRow['uaUserId'],
"EmailAddress" => $uaRow['uaEmailAddress'],
"FirstName" => $uaRow['uaFirstName'],
"LastName" => $uaRow['uaLastName'],
"BirthDate" => $uaRow['uaBirthDate'],
"Address" => $uaRow['uaAddress'],
"Gender" => $uaRow['uaGender'],
"ContactNumber" => $uaRow['uaContactNumber'],
"BloodTypeId" => $uaRow['uaBloodTypeId'],
"AccountStatus" => $uaRow['uaAccountStatus'],
);
echo json_encode($UserDataArr);
exit();
}
?>
this error appears on the console:
Uncaught TypeError: Cannot read property 'LastName' of undefined get_user_accounts.js:66
this is the line 66 of get_user_accounts.js, which is present on the "click listener".
$('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);
but, I am confused because the php array appears on the browser's Network Response:
Successful Connection{"UserId":"1","EmailAddress":"paulanselmendoza#gmail.com","FirstName":"Paul Ansel","LastName":"Mendoza","BirthDate":"1998-12-17","Address":"Phase 1B Block 8 Lot 20 Olivarez Homes South, Sto. Tomas, Binan City, Laguna","Gender":"Male","ContactNumber":"2147483647","BloodTypeId":"0","AccountStatus":"ACTIVE"}
Did you see that you get: Successful Connection before the JSON data? You have to remove that, if not it will be an invalid JSON response. The code you have shared doesn't have the particular stuff.
I believe you have to check your database connection, where on successful connection, it is set to output Successful Connection, which breaks your response. Please remove that bit of code.
include "../includes/connect.php";
It can be something like:
$conn = mysqli_connect() or die("Error");
echo "Successful Connection";
Because getModalData fucntion return the UserData before it asign by ajax(UserData = data;). use a callback function:
using callbacks
function getModalData(passedUserId,callback) {
$.ajax(
{
type: "POST",
url: "get/get_modal_data.php",
data: { passedUserId: passedUserId },
dataType: "json",
success: function (data) {
callback(data);
}
}
);
}
$('body').on('click', '.openModal', function () {
var userId = $(this).val(),
btnText = $(this).text(),
btnClass = '',
colorCode = '';
getModalData(userId, function (arrayedUserData) {
if (btnText === "Delete") {
btnClass = 'danger';
colorCode = '#d9534f';
} else {
btnClass = 'warning';
colorCode = '#f0ad4e';
}
$('#actionBtn').removeClass().addClass('btn btn-' + btnClass).text(btnText);
$('#modalTitle').text('Confirm ' + btnText);
$('#S-modalbody p').text('Are you sure you want to ' + btnText + ' user: ');
$('#S-modalbody h4').css('color', colorCode).text(userId + " - " + arrayedUserData.LastName + ", " + arrayedUserData.FirstName);
});
});
I know this has been asked 1000 times before but I have hit a brick wall with this.^have created a web application that inserts user data and feedback for the user and the code below is basically part of the PhoneGap application. The strange thing is that the code works perfectly in a web browser but not in Phonegap (output iPad via Xcode).
Therefore would someone know why I am getting an undefined error for the following AJAX call, just after the success callback and the alert(data.ResultId). , any help is appreciated.
Thank you!
// POST: /Result/Create
[HttpPost]
public ActionResult Create(Result result)
{
if (ModelState.IsValid)
{
result.ResultDate = DateTime.Now;
repository.InsertResult(result);
repository.Save();
if (Request.IsAjaxRequest())
{
int ResultId = result.ResultId;
try
{ //valid database entry..send back new ResultId
return Json(new { Success = true, ResultId, JsonRequestBehavior.AllowGet });
}
catch
{ // no database entry
return Json(new { Success = false, Message = "Error", JsonRequestBehavior.AllowGet });
}
}
return RedirectToAction("Index");
}
return View(result);
}
Insert QnA
function InsertQnA() {
//hardcoded for testing
Q1 = 10;
Q2 = 10;
Q3 = 10;
Q4 = 10;
Q5 = 10;
Q6 = 10;
Q7 = 10;
Q8 = 10;
Q9 = 10;
Q10 = 10;
localStorage.setItem("Total",100);
localStorage.setItem("CaseStudy", 1);
localStorage.setItem("UserId",1);
Attempts = "1";
////////////////
$.ajax({
url: Domain + '/Result/Create',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{"Q1":"' + Q1 + '","Q2":"' + Q2 + '","Q3":"' + Q3 + '","Q4":"' + Q4 + '","Q5":"' + Q5 + '","Q6":"' + Q6 + '","Q7":"' + Q7 + '","Q8":"' + Q8 + '","Q9":"' + Q9 + '","Q10":"' + Q10 + '","Total":"' + localStorage.getItem("Total") + '","CaseStudy":"' + localStorage.getItem("CaseStudy") + '","UserId":"' + localStorage.getItem("UserId") + '","Attempts":"' + QnANumAttempts + '"}',
// dataType : "json",
success: function (data) {
alert(data.ResultId);
if (data.Success==true) {
}
else if (data.Success==false) {
viewModel.UserId("Your entry has not been saved, please try again.");
}
},
}).fail(
function (xhr, textStatus, err) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});
}
The problem was that I was tying to use the same ActionResult to serve an MVC view as well as an htlm5 cordova iOS app. I got round this by copying the ActionResult but changing the return type to a string, note the code looks a bit different in the action, however the original worked fine too. Many thanks to all who posted
[HttpPost]
public string CreateResult(Result result)
{
result.ResultDate = DateTime.Now;
repository.InsertResult(result);
repository.Save();
if (result == null)
{
// User entity does not exist in db, return 0
return JsonConvert.SerializeObject(0);
}
else
{
// Success return user
return JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
}
}
AJAX
$.ajax({
url: Domain + '/Result/CreateResult',
cache: false,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: '{"Q1":"' + Q1 + '","Q2":"' + Q2 + '","Q3":"' + Q3 + '","Q4":"' + Q4 + '","Q5":"' + Q5 + '","Q6":"' + Q6 + '","Q7":"' + Q7 + '","Q8":"' + Q8 + '","Q9":"' + Q9 + '","Q10":"' + Q10 + '","Total":"' + localStorage.getItem("Total") + '","CaseStudy":"' + localStorage.getItem("CaseStudy") + '","UserId":"' + localStorage.getItem("UserId") + '","Attempts":"' + QnANumAttempts + '"}',
success: function (data) {
try {
if (data != 0) {
//result id used for feedback insertion > update result entity
localStorage.setItem("ResultId", data.ResultId);
viewModel.UserId("You have successfully completed case study " + localStorage.getItem("CaseStudy") + ", please fill out the <a href=evaluation.html target=_self>evaluation.<a/>");
//reset locals
ResetLocalStorage();
//count number of entities for User
CountUserEntitiesInResults();
}
else
{
viewModel.UserId("Your entry has not been saved, please try again.");
}
}catch(error) {
alert("This is the error which might be: "+error.message);
}
},
}).fail(
function (xhr, textStatus, err) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});
In the following script, although the two weather objects are both populated with data in the ajax calls, the updateWeather call shows them both as undefined prior to that line executing. I moved the variable declarations so they would be global but they still both show undefined prior to the updateWeather call. What am I missing? Can I not set up a variable in the ajax success function and then pass it later?
Note: If you want to test this use a different url as this one won't work for you with out my credentials
function getWeatherForecastStationCode() {
var d = new Date();
var parts = d.toString().split(" ");
var dDate = parts[1] + " " + parts[2] + ", " + parts[3];
var ampm;
if (parts[4].split(":")[0] <= 12) {
ampm = "AM";
} else {
ampm = "PM";
}
var dtime = parts[4].split(":")[0] + ":" + parts[4].split(":")[1];
var datetime = dDate + " " + dtime + ampm;
alert(datetime);
var weatherStation = "KPBI"; // get from GetWeatherService.svc
var forecastFields = "&fields=periods.maxTempF%2cperiods.minTempF%2cperiods.vaildTime%2cperiods.weather%2cperiods.icon";
var currentFields = "&fields=ob.tempC%2cob.tempF%2cob.icon%2cplace.name%2cplace.state";
var forecastUrlWeatherStation = 'http://api.aerisapi.com/forecasts/' + weatherStation + '?limit=1&client_id=' + AerisClientId + '&client_secret=' + AerisWeatherApiSecret + forecastFields;
var currentUrlWeatherStation = 'http://api.aerisapi.com/observations/' + weatherStation + '?limit=1&client_id=' + AerisClientId + '&client_secret=' + AerisWeatherApiSecret + currentFields;
$.ajax({
type: "GET",
url: forecastUrlWeatherStation,
dataType: "json",
success: function (json) {
if (json.success === true) {
forecastedWeather = {
weather: json.response[0].periods[0].weather,
maxTemp: json.response[0].periods[0].maxTempF,
minTemp: json.response[0].periods[0].minTempF,
weatherIcon: json.response[0].periods[0].icon,
obsTime: datetime
};
}
else {
alert('An error occurred: ' + json.error.description);
}
}
});
var location;
$.ajax({
type: "GET",
url: currentUrlWeatherStation,
dataType: "json",
success: function (json) {
if (json.success === true) {
var place = json.response.place.name.split(" ");
if (place.length === 1) {
location = place[0].charAt(0).toUpperCase() + place[0].substr(1, place[0].length);
} else {
location = place[0].charAt(0).toUpperCase() + place[0].substr(1, place[0].length) + " " + place[1].charAt(0).toUpperCase() + place[1].substr(1, place[1].length) + ", " + json.response.place.state.toUpperCase();
}
currentWeather = {
location: location,
currentTemp: json.response.ob.tempF
};
} else {
alert('An error occurred: ' + json.error.description);
}
}
});
updateWeather(forecastedWeather,currentWeather);
}
The problem is that AJAX is Asynchronous (Thats the "A" in "AJAX"), so the call to updateWeather is executing before a response is received from your 2 ajax calls.
The way to do this then, is to wait for all ajax calls to complete before calling updateWeather.
Something like the following (untested):
$.when(getForecast(),getCurrent()).done(function(f,c){
updateWeather(forecastedWeather,currentWeather)
});
function getForecast(){
return $.ajax({
type: "GET",
url: forecastUrlWeatherStation,
dataType: "json"
....
});
};
function getCurrent(){
return $.ajax({
type: "GET",
url: currentUrlWeatherStation,
dataType: "json"
....
});
};
I've been trying to get this right for quite some time, I'm trying to append the object from the first ajax call after the second ajax call. But the for loop seems to iterate the changing of the value to the last result before appending the information, having the last post appended every time.
var scribjson =
{
"user_id" : localStorage.viewing,
};
scribjs = JSON.stringify(scribjson);
var scrib = {json:scribjs};
$.ajax({
type: "POST",
url: "getScribbles.php",
data: scrib,
success: function(result)
{
var obj = jQuery.parseJSON(result);
for(var i = 0; i < obj.length; i+=1)
{
var userjson =
{
"user_id" : obj[i].user_id
};
userjs = JSON.stringify(userjson);
var user = {json:userjs};
localStorage.post = obj[i].post;
$.ajax({
type: "POST",
url: "getRequestsInfo.php",
data: user,
success: function(result)
{
var obj2 = jQuery.parseJSON(result);
$('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
$('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
},
error: function()
{
alert('An Error has occured, please try again.');
}
});
}
},
error: function()
{
alert('An Error has occured, please try again.');
}
});
Since ajax calls It looks like the all success functions of the inner ajax call are being called after the loop has ended, so i will always be the last iterated value.
Try this:
(function(i)
{
$.ajax({
type: "POST",
url: "getRequestsInfo.php",
data: user,
success: function(result)
{
var obj2 = jQuery.parseJSON(result);
$('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
$('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
},
error: function()
{
alert('An Error has occured, please try again.');
}
});
})(i);
This will create a closure on i, which will give each ajax call its own copy of the current value.
Use an IIFE:
success: (function(i){return function(result) {
var obj2 = jQuery.parseJSON(result);
$('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
$('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
}})(i),
etc. Currently your loop generated ajax success handlers contain a direct reference to the counter itself, which (by the time they are called) has reached its final value.