I have simple AJAX call.
It looks like this:
myApp.onPageInit('about', function (page) {
search_term = $$("#search_term").val();
const key = "xxxx-xxxx";
const nick = "https://api.xxx.xxx/" + search_term + "?api_key=" + key;
$$.ajax({
url:nick,
type:'GET',
dataType: JSON,
beforeSend: function(){
//myApp.showPreloader('Please wait...');
},
success: function(data) {
//myApp.hidePreloader();
console.log(data);
console.log(data['summonerLevel']);
},
statusCode: {
404: function() {
// myApp.alert('Account does not exist.', 'ERROR');
}
},
error: function(data) {
myApp.alert('Account does not exist.', 'ERROR');
// ak je ovaj error, netko je dirao putanju - fajl
},
});
})
When I'm trying to get properties from data object, every time it says undefined.
Console log: {"id":"xxxx","accountId":"xxxx","puuid":"xxxx","name":"Data","profileIconId":3015,"revisionDate":1546082318000,"summonerLevel":37}
Second console log: undefined
I tried dot notation and bracket notation, but everytime same status(undefined).
Like this:
console.log(data['summonerLevel']);
console.log(data.summonerLevel);
Any suggestion for this problem?
use JSON.Parse() method and try taking the value with object.attributename
$.ajax({
url:nick,
type:'GET',
dataType: JSON,
beforeSend: function(){
},
success: function(data) {
var data=JSON.Parse(data);
console.log(data.summonerLevel);
console.log(data.accountId);
},
statusCode: {
404: function() {
}
},
error: function(data) {
},
});
Related
this is how the javascript looks like
<script type="text/javascript">
$(document).ready(function () {
$('#loginButton').click(function () {
//this.disabled = true;
debugger;
var data = {
"userid": $("#username").val(),
"password": $("#password").val()
};
$.ajax({
url: "/Account/LoginPost",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
},
error: function () {
alert('Login Fail!!!');
}
});
});
});
I am getting the alert('Login fail') also debugger not getting hit.
I am using jquery 1.9.1 and have included unobstrusive
my controller is this as you can i am passing string values not object values
to the controller so stringify is justified here
[HttpPost]
public JsonResult LoginPost(string userid, string password)
{
using (someentities wk = new someentities())
{
var LoginUser = wk.tblUsers.Where(a => a.Username.Equals(userid)&&a.Password.Equals(password)).FirstOrDefault();
if (LoginUser != null)
{
FormsAuthentication.SetAuthCookie(userid,false);
Session["Username"] = LoginUser.Username;
Session["Password"] = LoginUser.Password;
Session["Name"] = LoginUser.Name;
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
else
{
TempData["Login"] = "Please Enter Correct Login Details";
return Json(new { Success = false }, JsonRequestBehavior.AllowGet);
}
}
// If we got this far, something failed, redisplay form
}
when page is loading these error are shown
$(..) live is not a valid function in
(anonymous function) # jquery.unobtrusive-ajax.js:115
(anonymous function) # jquery.unobtrusive-ajax.js:163
take a look to the success function
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
}
you are using multiple ", combine it with the single one ', this is a syntax error, try to check the code on an editor such as Atom, to avoid this kind of errors
Stringify converts an object to a string. Have you tried passing data an object instead of a string? Try replacing JSON.stringify(data), with data?
I am trying to filter the json array received from the server. I'm able to receive the data properly in the success function however I get a "data is undefined error" within the filterdata block. [Uncaught TypeError: Cannot read property 'list' of undefined]
$(function () {
function log(message) {
$("<div>").text(message).prependTo("#log");
$("#log").scrollTop(0);
}
$("#city").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/find?mode=json&type=like",
dataType: "jsonp",
data: {
q: request.term
},
dataFilter: function (data, type) {
console.log(data);
alert(data.list.length);
alert(data.list[0].name + ', ' + data.list[0].sys.country);
jsonObj = [];
for (i = 0; i < data.list.length; i++) {
item = {}
item["city"] = data.list[0].name;
item["country"] = data.list[0].sys.country;
jsonObj.push(item);
}
return jsonObj;
},
success: function (data) {
//alert(data.list.length);
response(data);
}
});
},
minLength: 3,
select: function (event, ui) {
log(ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
});
As dataFilter is a function to be used to handle the raw response data of XMLHttpRequest. Since you are using JSONP request, which is not an XHR request so there is no XHR object and no raw data, which makes the behavior of dataFilter in your case perfectly valid. You should check the response in success callback instead.
How I can get variable value from jsonp response and use it in other script function?
In first function I have one value that I am getting from jsonp response. I am assigning this value to variable ( var userId ) in first function.
How I can get userId value and use it in second script function???
<script>
$(document).on('pageinit', '#login', function () {
$(document).on('click', '#submit', function () {
if ($('#username').val().length > 0 && $('#password').val().length > 0) {
console.log($('#check-user').serialize());
$.ajax({
url: 'http://localhost/check.php',
data: $('#check-user').serialize(),
type: 'POST',
beforeSend: function () {
$.mobile.showPageLoadingMsg(true);
},
complete: function () {
$.mobile.hidePageLoadingMsg();
},
success: function (result, status, err) {
if(result.login){
$.mobile.changePage( "#output", { transition: "slideup", changeHash: false });
var userID = //// HERE I NEED TO GET USER ID FROM jsonp response!!!!
});
}
else{
alert("An error occurred: " + status + "nError: " + err.status);
}
},
error: function (request, error) {
}
});
} else {
alert('Please fill all necessary fields');
}
event.preventDefault();
});
var output = $('#output');
var userid = ////HERE I NEED TO SET USER ID!!!!!!!!!!!!
$.ajax({
url: 'http://localhost/data.php?user='+userid,
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var landmark = '<h1>'+item.name+'</h1>'
+ '<p>'+item.lat+'<br>'
+ item.long+'</p>';
output.append(landmark);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
});
</script>
you can use the global variable assignment feature of js
Declare your variable outside of any function.
<script>
var userId;
function foo(){
//..
}
</script>
OR Use the window object to assign the global variable from inside a function
<script>
function foo() {
window.userID = ...;
}
</script>
more info available here
I'm getting the popup as Undefined and showing the error as below:
Unable to get property 'domain_name' of undefined or null reference.
Can Any body help on this
From View:
#Html.ActionLink("Details", "",
new { id = item.id },
new { onclick = "someFunction(" + item.id + ")",
href = "javascript:void(0)" })
Javascript
function someFunction(id) {
$.ajax({
type: 'POST',
url: '#Url.Content("~/")Contracts/Test/',
data: { 'id': id },
dataType: 'json',
success: function (data) {
alert(data.domain_name);
},
error: function (xhr, status, exception) {
alert("Error: " + exception + ", Status: " + status);
}
});
}
Controller action
enter code here
public JsonResult Test(int id)
{
var result = (from cntrct in db.contracts where cntrct.id == id
select new { cntrct.domain_name, cntrct.id}).ToArray();
return Json(result);
}
Below is the data which I"m getting from db but can't pass to JavaScript back.
Error
SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3.
Contracts
Can you try this in the Json Action method
Action
public JsonResult Test(int id)
{
var result = (from cntrct in db.Contracts where cntrct.ID == id
select new { cntrct.domain_name, cntrct.id, cntrct......}).ToArray();
return Json(result);
}
Script
function someFunction(id) {
$.ajax({
type: 'POST',
url: '#Url.Content("~/")Contracts/Test/',
data: { 'id': id },
dataType: 'json',
success: function (data) {
alert(data.domain_name);
}
});
}
Oohoo!! Finally I got this... Only thing we need to do is alert(data[0].domain_name); :)
in my MVC layout page I have the following:
$("body").ajaxError(
function (e, request) {
if (request.status == 403 || request.status == 500) {
window.location = '#Url.Action("LogOn", "Account", new {area = "", msg = "forbidden", returnUrl = HttpContext.Current.Request.RawUrl})' + window.location.hash;
return;
}
window.location = '#Url.Action("Index", "Error")';
}
);
on another page I'm performing an ajax call like so:
...
$.when(refreshActionLinks(row, machineId, packageId)).done(function(a1) {
row.find("span").text(opStatus).removeClass("pending");
progressbar.progressbar("destroy");
$(row).flash(bg[1], 1000);
});
...
javascript function:
function refreshActionLinks($row, machineId, packageId) {
try {
var json = JSON.stringify({ packageId: packageId, machineId: machineId, tabType: $("#TabType").val() });
console.log("refreshActionLinks => " + json);
$row.find("td.options div.actionLinks").html("<img src='#Url.Content("~/Content/images/ajax-load2.gif")' />"); // pending
return $.ajax({
url: "#Url.Action("GetActionLinks", "Packages")",
data: json,
timeout: 50000,
contentType: 'application/json',
type: 'POST',
success: function (data) {
if ($row.length) {
$row.find("td.options div.actionLinks").html(data);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
} catch(e) {
// hide icons
$row.find("a.action").remove();
}
}
The issue is that while refreshAction function is executing, clicking a menu link causes the ajax call to error out - which in this case is correct. BUT it does take me to /Index/Error page which is NOT correct. I would like "$("body").ajaxError" to handle all ajax errors on the site EXCEPT on the page I'm calling refreshActionLinks. Notice, I already have try/catch surrounding my ajax call. why doesn't that work?
thanks
figured it out:
ajax has a settings:
global: false
now my function looks like this:
function refreshActionLinks($row, machineId, packageId) {
try {
var json = JSON.stringify({ packageId: packageId, machineId: machineId, tabType: $("#TabType").val() });
console.log("refreshActionLinks => " + json);
$row.find("td.options div.actionLinks").html("<img src='#Url.Content("~/Content/images/ajax-load2.gif")' />"); // pending
return $.ajax({
url: "#Url.Action("GetActionLinks", "Packages")",
global: false, // disable error pages on failed ajax calls
data: json,
timeout: 50000,
contentType: 'application/json',
type: 'POST',
success: function (data) {
if ($row.length) {
$row.find("td.options div.actionLinks").html(data);
}
}
});
} catch(e) {
// hide icons
$row.find("a.action").remove();
}
}