Ajax Call to Retrieve oData from REST API - ajax

I am trying to use Ajax to get data back from an oData REST API. The Ajax looks like this:
$(document).ready(function () {
$.ajax({
url: "http://localhost:52139/odata/WEB_V_CIVIC_ADDRESS?key=10064450", datatype: 'json',
success: function (oResult)
{
alert("good");
$('.accountNumber').append(data.accountNumber);
$('.civicaddress').append(data.civicaddress);
},
error: function(data)
{
alert('bad');
}
});
});
The URL is called just fine, but then I always get the alert 'bad', so the call is throwing an error. The url is returning:
{"#odata.context":"http://localhost:52139/odata/$metadata#WEB_V_CIVIC_ADDRESS/$entity","#odata.type":"#Values.Classes.Entities.AccountAddress","accountNumber":10064450,"rowNumber":0,"civicaddress":"123 Fake St"}
So how do I get the accountNumber and civicaddress from the ajax call?
Thanks.

If anyone's interested the solution was to add the following in my web.config for the REST service:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
</customHeaders>
</httpProtocol>
</system.webServer>

Related

Cordova $.ajax request wont work

I am having issue with cordova ajax reuest.
$.ajax({
url: syncURL,
data: (changed ? {start: changed + 1} : ''),
dataType: "json",
success: function (data) {
console.log('Ajax success');
callback(data);
},
error: function(model, response) {
console.log('Ajax error');
//app.notify(response.responseText, 'error');
callback(null);
}
});
The program shows Ajax success in console log. I can see the content inside app while watching it on the browser with:
cordova serve
Unfortunately if i want to deploy to ios simulator or on android device, the app wont load the content and get an empty json with no data.
What i am doing wrong. The simulator or android device got network connection.
I dont see nothing in log too.
Also added
cordova plugins add cordova-plugin-whitelist
cordova version is 7.1.0
I bumped into same error starting with phonegap-vue-f7 template and using axios as Ajax library.
For same request to http://my.domain.com/api/request :
returns code 200 with local cordova serve (npm start with phonegap-vue-f7 template)
returns code 404 when I deployed to real device
The phonegap-vue-f7 template furnish a pre-filled config.xml with this:
<access origin="*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />
<allow-intent href="tel:*" />
<allow-intent href="sms:*" />
<allow-intent href="mailto:*" />
<allow-intent href="geo:*" />
at this point I had to install cordova-plugin-whitelist to make it work.
So the cordova-plugin-whitelist plugin correctly configured seem to be the answer.
not sure, but may be the data: value is not correct
data: (changed ? {start: changed + 1} : '')
What if you change to:
data: (changed ? '{start: changed + 1}' : '')

Login with Spring security using Ajax

I am trying to work on Ajax based login system using Spring Security and it was working fine, till I got with another requirement where I need to configure authentication-success-handler, so as I can do some post processing once user is authenticated by Spring security.
Earlier I was not using <form-login/> for showing Login page.My Login section is a drop down and part of header section which is common for entire application.
This is how I am trying to configure Spring security
<http pattern="/customer/**" auto-config="true" use-expressions="true" authentication-manager-ref="customerAuthenticationManager">
<!--<http pattern="/customer/**" auto-config="true" use-expressions="true">-->
<intercept-url pattern="/customer/logon.html*" access="permitAll" />
<intercept-url pattern="/customer/denied.html" access="permitAll"/>
<intercept-url pattern="/customer" access="hasRole('AUTH_CUSTOMER')" />
<intercept-url pattern="/customer/" access="hasRole('AUTH_CUSTOMER')" />
<intercept-url pattern="/customer/*.html" access="hasRole('AUTH_CUSTOMER')" />
<intercept-url pattern="/customer/*/*.html" access="hasRole('AUTH_CUSTOMER')" />
<form-login login-processing-url="/customer/logon.html" login-page="/shop/home.html"
authentication-success-handler-ref="webshopAuthenticationSuccessHandler" />
<logout invalidate-session="true"
logout-success-url="/customer/home.html"
logout-url="/customer/j_spring_security_logout" />
<access-denied-handler error-page="/customer/denied.html"/>
</http>
With these configuration, when ever I am clicking on login button with correct credentials, i am getting HTTP 302 error
http://localhost:8080/shop/customer/logon.html 302 found
Not sure what exactly I am doing wrong?
<form id="login" method="post" accept-charset="UTF-8">
<input id="userName" type="text" name="userName" size="30" />
<button type="submit" class="btn">Login</button>
</form>
Ajax Code
var data = $(this).serializeObject();
$.ajax({
'type': 'POST',
'url': "<c:url value="/customer/logon.html"/>",
'contentType': 'application/json',
'data': JSON.stringify(data),
'dataType': 'json',
....
}}:
Login Section
Authentication authenticationToken = new UsernamePasswordAuthenticationToken(customer.getUserName(), customer.getPassword());
try {
Authentication authentication = customerAuthenticationManager.authenticate(authenticationToken);
SecurityContextHolder.getContext().setAuthentication(authentication);
resp.setStatus(AjaxResponse.RESPONSE_STATUS_SUCCESS);
} catch (AuthenticationException ex) {
resp.setStatus(AjaxResponse.RESPONSE_STATUS_FAIURE);
}
Any inputs? With all my efforts, I am still getting 302 and with above configuration, even my logon.html controller is not getting called.
My main issue is when I am enabling Spring security using
<form-login login-processing-url="/customer/logon.html" login-page="/shop/home.html"
authentication-success-handler-ref="webshopAuthenticationSuccessHandler" />
I am getting 302 from logon.html and even logon.html Controller is not being triggered (placed debugger on it)
First you don't need a controller, spring security handles all this for you. So drop the controller.
The current problem is due to your JSON based post. This is handled by the normal filter which handles login, but it doesn't see a j_username and j_password field and as such will redirect (the 302) to the login page (in your case /shop/home.html) asking for those fields.
Basically you are posting the data as JSON whereas it simply should be just an ajaxified form post. This allows you to write a simple AuthenticationSuccessHandler which simply returns a 401 or a 200 status-code (and maybe a body) when things are ok.
Changing your ajax submit to something like this should make things work.
var data = $(this).serializeObject();
$.ajax({
'type': $(this).action,
'url': $(this).target,
'data': data
}):
This should create a ajax form post. Might be that you need a call to preventDefault() in the surrounding method to stop the form from actual posting.
With the login form that is currently posted it cannot work, as a form like this is needed:
<body>
<form action="/j_spring_security_check" method="POST">
<label for="username">User Name:</label>
<input id="username" name="j_username" type="text"/>
<label for="password">Password:</label>
<input id="password" name="j_password" type="password"/>
<input type="submit" value="Log In"/>
</form>
</body>
The post needs to be done j_spring_security_check, and username and password need to be suplied in fields j_username and j_password, otherwise it won't work.
I think you are getting a redirect to a login page.
You can see where the redirect is going with the chrome debugger or firebug if using firefox.
To approach this first get the rest of the config working with the default login page generated by spring security, by removing login-page="/customer/logon.html".
Once this works you can add back the custom login page, but it needs to have the elements above.
Also I believe you are trying to post a JSTL tag via ajax to the server? If it's true it won't work, otherwise can you edit the question.
Try it step by step by first using the default login page, then with an ajax request with hardcoded values just for testing and then when this works with a custom login page.
response code 302 is not an error indication. It's a way of performing a redirection.
as you have not shared your webshopAuthenticationSuccessHandler code.
But i am pretty much sure you are redirecting the request to some specified resource after processing some certain condition. so just check your header and get the URL of redirection.
and then redirect with javascript code.
An HTTP response with this status code will additionally provide a URL in the Location header field.
For an example -
Client request:
GET /index.html HTTP/1.1
Host: www.example.com
Server response:
HTTP/1.1 302 Found
Location: http://www.iana.org/domains/example/
so along with this error code you are getting http://www.iana.org/domains/example/ url where your authenticationSuccessHandler want you to redirect so redirect it through javascript code.

ajax call to do action when onclick checkbox in ofbiz

I want to use checkboxes with options say id1,id2.when i choose id1 a ajax will run through javascript and call the appropriate action and return the response.i dont want to reload the page.please post some freemarker, controller.xml, java codes to do this.
Based on my understanding of the question, the following script might be helpful you:
in ftl file itself/ in seperate js file you add the following script:
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#id1").click(function(){
if(jQuery(this).is(":checked")) {
var reqUrl= "checkbox1_Url";
sendAjaxRequest(reqUrl);
}
});
jQuery("#id2").click(function(){
if(jQuery(this).is(":checked")) {
var reqUrl= "checkbox2_Url";
sendAjaxRequest(reqUrl);
}
});
});
function sendAjaxRequest(reqUrl){
jQuery.ajax({
url : reqUrl,
type : 'POST',
data : {'var1': 'val1', 'var2' : 'val2'}, //here you can pass the parameters to
//the request if any.
success : function(data){
//You handle the response here like displaying in required div etc.
},
error : function(errorData){
alert("Some error occurred while processing the request");
}
});
}
</script>
In freemarker,
<input type="checkbox" id="id1" name="checkbox1" />
<input type="checkbox" id="id2" name="checkbox2" />
In controller.xml:
<request uri="checkbox1_Url">
<!-- fire if any events are here -->
<response name="success" type="view" value="ViewName1" />
<response name="error" type="view" value="errorViewName" />
</request>
<request uri="checkbox2_Url">
<!-- fire if any events are here -->
<response name="success" type="view" value="ViewName2" />
<response name="error" type="view" value="errorViewName" />
</request>
<view-map name="ViewName1" type="screen" page="component://.../widget/screensFileName#screenName"/>
<view-map name="ViewName2" type="screen" page="component://.../widget/screensFileName#screenName"/>
You define two screens in widgets as specified in the above path(page="...." attribute of view-map tag).
jQuery(function() {
jQuery('input[type = checkbox]').bind('click',function() {
var categoryId ="";
if(jQuery(this).is(':checked')) {
categoryId = jQuery(this).val();
}
var reqUrl= "categoryurl";
sendAjaxRequest(reqUrl, categoryId);
});
});
function sendAjaxRequest(reqUrl, categoryId){
jQuery.ajax({
url : reqUrl, // Here the Url will have to return the all products related to
//passed category
type : 'POST',
data : {'categoryId': categoryId}, //here you can pass the parameters to
//the request if any.
success : function(data){
//You handle the response here display all products in a div etc.
},
error : function(errorData){
alert("Some error occurred while processing the request");
}
});
}
<input type="checkbox" id="id1" name="checkbox1" value="yandamuri_cat"/><label for="id1">YandaMuri</label>
<input type="checkbox" id="id2" name="checkbox2" value="chetanBhagat_cat"/><label for="id2">Chetan Bhagath</label>
In Controller.xml:
<request uri="categoryurl">
<!-- fire if any events are here -->
<response name="success" type="view" value="ViewName" />
<response name="error" type="view" value="errorViewName" />
</request>
<view-map name="ViewName" type="screen" page="component://.../widget/screensFileName#screenName"/>
Define a screen in appropriate location/path specified in above page attribute of viw-map tag.
Here, the screen may be without decorator, so that the response will come without decorator and so you can display them in the current page, without reloading. Entire page.
I guess this might help you.

JQuery return code

Got a problem with jquery. I cant get a .xml file from the server, using the ajax function in jquery. I tried to call an alert upon succes and upon error, but nothing triggers. I did it this way:
$.ajax({
type: "GET",
url: "Levels.xml",
dataType: "xml",
error: function(){
alert("Ajax failed!");
},
success: function(xml){
alert(xml);
}
});
That did not work.
Edit: I have this code in my xml file:
<?xmlversion="1.0" encoding="ISO-8859-1"?>
<Level id="TestLevel" theme="woods">
<Wall>
<Row>111111111111111111111</Row>
<Row>100000000000000000001</Row>
<Row>100000000000000000001</Row>
<Row>100000000000000000001</Row>
<Row>100000000000000000001</Row>
<Row>100000000000000000001</Row>
<Row>100000000000000000001</Row>
<Row>100000000000000000001</Row>
<Row>100000000000000000001</Row>
<Row>100000000000000000001</Row>
<Row>100000000000000000001</Row>
<Row>111111111111111111111</Row>
</Wall>
</Level>
Renaming the XML File to something else like "sites.xml" fixes this on my server.
Appears that "levels" is somehow related to the xml request by ajax.
cheers
PrimuS

MVC 3.0 : why no client-side validation messages?

I have a model like this
public class SampleModel{
public int No{get;set;}
}
and in view I have a custom ValidationFor which shows a star near the inputbox for this field :
#Html.EditorFor(model => model.No)
#Html.ValidationMessageWithStarFor(model => model.No)
So in rendering I have a "*" nears the inputbox which tells the field is required. It works in server-side properly but it doesn't work in client-side.
In spite of Enabling ClientValidation in web.confing through these lines :
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="false" />
...how can I enable it?
You probably forgot to reference the following scripts in your page in addition to jQuery:
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
the problem was because of the following code :
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
which prevents dataannotation to validate not nullable types.

Resources