I am getting this error
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in ["Asharej Branch","Main Branch","Kanad Hospital Branch","Al Muwaiji Branch","Zakher Branch"]
Return this values from controller.
$stores = [];
foreach($t as $k){
$stores[] = $k['store_name'];
}
return $resultJson->setData(json_encode($stores));
Return Values from controller
[
"Asharej Branch",
"Main Branch",
"Kanad Hospital Branch",
"Al Muwaiji Branch",
"Zakher Branch"
]
Using AJAX call i want to access this value and create a dropdown list.
$.ajax({
url:customurl,
type: 'POST',
contentType: "application/json",
async:false,
success:function (data) { alert(data);
valuesCollection = [];
var wert=[];
/*$.each(JSON.parse(data), function (index, thevalue) {
alert(thevalue);
wert=[];
wert["label"]=index;
wert["value"]=thevalue;
valuesCollection.push(wert);
});*/
alert("T1");
for (var i = 0; i < JSON.parse(data.length); ++i) { alert("T2"+i);
console.log(data[i]);
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("There has been an error retrieving the values from the database.");
}
});
I tried .each method and for loop also. But getting the error like above i mentioned. How to fix this?
Related
Can anyone please tell me how to display the validation error in javascript? I am sending the request with ajax and want to display the errors.
blade code
$('input[id^="facility_name"]').map(function() {
return this.value;
}).get();
Laravel Validation
'facility_name.*' => 'required|string|min:3|max:255',
display error from js
$('.facility_name_error').html(data.responseJSON.errors.facility_name);
or
$('.facility_name_error').html(data.responseJSON.errors.facility_name[0]);
I attached the output of validation so how can I display this message to html
If your question is how can you access an object attribute with a dot (.) in the name, you can use the array way
data.responseJSON.errors['facility_name.0'][0]
you can access the error as the following:
in this example i will append the errors to li item you can do what you want
$.ajax({
type: 'POST',
url: 'your-url',
data: {your_data},
success: function (data) {
}
}).fail(function (jqXhr) {
var resp = jqXhr.responseJSON;
if (jqXhr.status === 422) {
var errorsHtml = '<ul>';
$.each(resp.errors, function (key, value) {
errorsHtml += '<li>' + value[0] + '</li>';
});
errorsHtml += '</ul>';
}
}).always(function () {
});
We need to implement type ahead functionality in inbox box ,but when we got response from $http get is invalid JSON so that i cant able do that.
below method i am using for view level
uib-typeahead="name for name in collections ($viewValue)"
Angular:
$scope.collections = function(val) {
return $http.get('/Documents/DocumentsList/', {
params : {
stk : val
}
}).then(
function(response) {
if (response.data.suggestions) {
$("[uib-typeahead-popup].dropdown-menu").css('display','block');
return response.data.suggestions
.map(function(item) {
return item.term;
});
};
});
};
JSON Response:
{} && {
"name": "John",
"age": 31,
"city": "New York"
}
How to modify the invalid JSON to valid JSON and pass the valid response in then.
It would be better to fix the problem at the source but, if you can't do that, implement your own response transformer
return $http.get('/Documents/DocumentsList/', {
params: { stk: val },
transformResponse: function(data) {
return angular.fromJson(data.substring(6));
}
})...
I am relatively new to Angular js and trying to use promises along with services and got reference http://plnkr.co/edit/b4HPbX2olM745EfHVcc6?p=preview. But in my application I am getting response as {"Response":"exception while loading Reports List","error":"Exception getting all records.","status":"failure"}. When I get response like this, I need to show an alert message with the message in "error" (i.e., Exception getting all records) and set $scope.data to [] in my controller.What are the changes I need to make to services and controller to handle this. Any help is much appreciated.
In services :
return $q.when(originalRequest)
.then(function(res) {
data = res.ResultSet.Response;
return data;
});
In Controller,
DashboardsDataService.getNetSpendOverTimeData()
.then(function(data) {
$scope.data = data;
});
The following is my original request to Java action class:
var originalRequest = $.ajax({
async : false,
url : "/dash2/dashd2ajax.do",
type : "POST",
data : {
action : 'getNetSpendOverTime',
customerId : selectedAccTd,
carriersId : selectedCarriers,
fromDate : fromDate,
toDate : toDate,
modes : selectedModes,
services : selectedServices,
dateType : selectedDateType,
lanesList : selectedLaneList
},
dataType : "json"
});
return $q.when(originalRequest)
.then(function(res) {
data = res.ResultSet.Response;
return data;
});
If what you're asking is "how do I turn request success into a failure based on result data", then take a look at the following example:
return $q.when(originalRequest).then(function (res) {
if (res.ResultSet.error) {
return $q.reject(res.ResultSet.error);
} else {
return res.ResultSet.Response;
}
});
Using $q.reject() turned your data into a real "promise failure", so in your controller, you can use the normal promise API:
doSomethingAsynchronous().then(function (data) {
$scope.data = data;
}, function (error) {
$scope.data = [];
alert(error);
});
i'm working on a project like this:
(HTML Forms(AJAX)+ twitter bootstrap)(solo HTML, no JSP,etc..)->Servlets(on Google App Engine-JAVA)->Persistence(Google Cloud SQL).
I'm quite new to jQuery ajax calls, but i understand the process, as i'm used to write the old XHR code.
Below is the function in JS, that does not write to console the expected result..so far most of the times form data is persisted.
My Servlet if fine, and outputs a valid JSON.(calling the URL on a browser always works as expected.)
My answer is why jQuery ajax callbacks(done,fail,always) aren't working properly? They do write to console/display alert().
THANKS, for your time!
$(document).ready(function() {
var myEmail = "";
var myGender = "";
$('#saveButton').click(function() {
$('#myform').submit();
//alert('Handler for .submit() called.');
myEmail = document.getElementById("inputEmail").value;
window.console.log('EMAIL---->' + myEmail);/*ok log!*/
//alert('EMAIL->' + myEmail);
var radioObj = document.forms['myForm'].elements['gender'];
myGender = getCheckedValue(radioObj);
window.console.log('GENDER---->' + myGender);/*ok log!*/
//alert('GENDER->' + myGender);
var jqXHR = $.ajax({
statusCode : {
404 : function() {
alert("404 ERROR - page not found");
}
},
url : "/newuser",
type : "GET",
timeout : 10000,
data : {
email : myEmail,
gender : myGender,
operation : '0'
},
done : function(data, textStatus, jqXHR) {
window.console.log('done -> RESPONSE---->' + data);/*this does not log!*/
alert(data);
},
fail : function(jqXHR, textStatus, errorThrown) {
window.console.log('always -> RESPONSE---->' + data); /*this does not log!*/
alert(data);
},
always : function(data, textStatus, jqXHR) {
window.console.log('always -> RESPONSE---->' + data); /*this does not log!*/
alert(data);
}
});
});
});
done, fail and always are not properties of the settings object passed to $.ajax, they are callbacks on the jqxhr object returned by the call to $.ajax. They should be configured like this instead:
var jqxhr = $.ajax( "example.php" )
.done(function() { alert("success"); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });
Check out the API documentation for further usage guidance.
In Backbone.js, I'm working with an API which wraps the response in a meta and data hash. For example:
# GET /api/posts/1
meta: {
status: 200
},
data: {
id: 1
title: 'Hello World'
}
# GET /api/posts
meta: {
status: 200
},
data: [
{
id: 1
title: 'Hello World'
},
{
id: 2
title: 'Hi everyone!'
}
]
My Backbone.js Collection/Models have the following parse function overwritten:
# App.Models.Post
...
parse: function (response) {
this.meta = response.meta;
return response.data;
}
# App.Collections.Posts
...
parse: function (response) {
this.meta = response.meta;
return response.data;
}
However, when I fetch on the collection posts = new App.Collections.Posts(); posts.fetch(), the post attributes are all empty. I.e. posts.at(0).get('title') = undefined.
Now, this is fixed when the Model parse is changed to:
parse: function (response) {
return response;
}
But this means that post.fetch() is broken.
Any suggestions?
Thanks!
I think the problem is that your model's parse is getting inconsistent data passed into it when done via model fetch vs collection fetch. console.log the argument to model parse to confirm this. This is because the value return by collection's parse is just an array of object data and to convert those to models, the collection just delegates to the model's parse method. This might fix your issue:
//App.Models.Post
parse: function (response) {
if (response.data) {
return response.data;
}
return response;
}
For reference: https://github.com/documentcloud/backbone/pull/773