I have a JSP-servlets application which is deployed on tomcat.Now from my html I need to make web(Ajax) call and call the CQ5 webpage(which is entirely running in CQ instance). When i click on submit button, it goes in the error method of ajax call.
Here is the code
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://crypto-js.googlecode.com/svn/tags/2.5.4/build/crypto/crypto-min.js"></script>
<script src="/resources/scripts/mysamplecode.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#myAjaxRequestForm").submit(function(e){
e.preventDefault();
});
$("#myButton").click(function(e){
//get the form data and then serialize that
dataString = $("#myAjaxRequestForm").serialize();
var username = 'admin';
var password = 'admin';
var url = 'http://localhost:4502/content/geometrixx/en/products/triangle/jcr:content/par/text_0.infinity.json';
$.ajax({
type: 'GET',
url: 'http://localhost:4502/content/geometrixx/en/products/triangle/jcr:content/par/text_0.infinity.json',
dataType : 'json',
'beforeSend': function(xhr) {
var bytes = Crypto.charenc.Binary.stringToBytes('admin' + ":" + 'admin');
var base64 = Crypto.util.bytesToBase64(bytes);
xhr.setRequestHeader("Authorization", "Basic " + base64); //May need to use "Authorization" instead
},
error : function() {
alert('errro');
},
sucess: function(result) {
alert('done');
}
});
});
});
</script>
<div id="allContent">
<div id="myExample">
<form id="myAjaxRequestForm">
<h1> Please enter the Order Information -</h1>
<label for="orderId">Order Id:</label>
<input id="orderId" name="orderId" type="text"><br/>
<br/>
<label for="zipCode">ZIP Code:</label>
<input id="zipCode" name="zipCode" type="text"><br/>
<br/>
<input id="myButton" type="button" value="Submit">
</form>
</div>
<div id="ajaxResponse">
</div>
</div>
</head></html>
Try to change your beforeSend handler a bit and also debug the error:
beforeSend: function (xhr) {
var base64 = btoa(username + ":" + password);
xhr.setRequestHeader("Authorization", "Basic " + base64);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
},
If it doesn't work, please paste the result of those 3 console.log()
I can see the json in the chrome console..but i get the parse error.Jquery17989898 was not called.
This is the code ...
var user = 'admin';
var pw = 'admin';
var url = 'http://localhost:4502/content/geometrixx/en/products/triangle/jcr:content/par/text_0.infinity.json';
alert("i1");
var authToken = null;
$.ajax({
url: 'http://localhost:4502/content/geometrixx/en/products/triangle/jcr:content/par/text_0.infinity.json',
type: "POST",
crossDomain: true,
dataType: "jsonp",
data: JSON.stringify({ "Username" : user, "Password" : pw, "Type" : "SaaSGrid"}),
success: function(data)
{
alert("dsadsadsa");
authToken = data.Token;
},
error: function (jqXHR, textStatus, errorThrown) {
alert("jqXHR : " + jqXHR +
" \n**** text Status : " + textStatus +
" \n**** text Status : " + errorThrown);
}
});
{"textIsRich":"true","jcr:lastModifiedBy":"admin","sling:resourceType":"foundation/components/text","jcr:createdBy":"admin","jcr:created":"Wed Nov 03 2010 00:41:59 GMT-0400","jcr:lastModified":"Fri Nov 05 2010 11:14:54 GMT-0400","jcr:primaryType":"nt:unstructured","text":"The measure of an exterior angle of a triangle is equal to the sum of the measures of the two interior angles that are not adjacent to it; this is the exterior angle theorem. The sum of the measures of the three exterior angles (one for each vertex) of any triangle is 360 degrees.</p>\n</p>\n"}
I think you should explain a bit more your scenario. You are trying to access a page from a CQ5 instance, but authentication for that is probably just needed in an author instance. when accessing a publish instance that page will likely not need any authentication.
Will you always access the author instance? if you will switch to a publish instance later it would be easier to just adjust permissions in CQ5 to make the page public.
from a security perspective, this sounds wrong - you are passing user & password to execute on the client side - exposing your authentication.
Better to open up the permissions on the resource so anonymous can write to it (the POST) then pass credentials out.
Related
I make a request to receive a authentication token. When it's ok, I would navigate to the index.html page (See below "NAVIGATE TO "index.html").
How can I do that?
I tried with: var app = new kendo.mobile.Application() app.navigate("index.html"); but it will not work. I receive the following error:
0x800a139e - Error in JavaScript: Your kendo mobile application element does not contain any direct child elements with data-role="view" attribute set. Make sure that you instantiate the mobile application using the correct container.
Thank you
class LoginViewModel extends kendo.data.ObservableObject {
isVisible = true;
username: string = "";
password: string = "";
errorText: string = "";
clickHandler: any = function (e) {
var self = this;
var data = { grant_type: "password", username: self.get("username"), password: self.get("password") };
$.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded",
url: "/token",
data: data
}).done(function (data, textStatus, jqXHR: JQueryXHR) {
// Cache the access token in session storage.
sessionStorage.setItem("accessToken", data.access_token);
***NAVIGATE TO "index.html"***
}).fail(function (jqXHR: JQueryXHR, textStatus, errorThrown) {
self.set("errorText", jqXHR.status + ': ' + jqXHR.statusText)
});
}
constructor() {
super();
super.init(this);
}
}
Your navigation is ok; you are receiving the error because the application container does not contain a <div> element with data-role="view" as immediate child.
You need to have something like :
<body>
<div data-role="view" ....></div>
</body>
And initialize your app
... = new kendo.mobile.Application(document.body
//or another jquery selector
);
I am trying to register a user via AJAX using FOSUserBundle.
The problem is that the name value in the form is fos_user_registration_form_[username] so it isn't accepted by javascript as array.
<input type="text" id="fos_user_registration_form_username" name="fos_user_registration_form[username]" required="required" />
How can I solve that?
Can I change the name parameter in FOSUserBUndle to fos_user_registration_form_username ?
How can I create an array with fos_user_registration_form_[username] value in Javascript?
$("#registerButton").click( function(){
data = {
fos_user_registration_form_[username]:$("#name").val(), // HERE IS WHERE IT CRASHES, IN THE [username] field.
fos_user_registration_form_[email]:$("#email").val(),
fos_user_registration_form_[plainPassword]:$("#password").val(),
};
$.ajax({
type: "POST",
url: serviceURL,
asyn:false,
data: data,
dataType: "json",
success: function(res) {
alert("success"); // JUST FOR TEST
}
});
I am testing a basic example..
This works (triggers the alert)
<script type="text/javascript">
data = {
fos_user_registration_form_username:"blabla"
};
alert(true);
</script>
This doesn't works: (do not trigger the alert)
<script type="text/javascript">
data = {
fos_user_registration_form_[username]:"blabla"
};
alert(true);
</script>
To fetch the data from your input fields, you need to combine the name_of_the_form_ + the name_of_the_field. For example:
fos_user_registration_form_ + username => fos_user_registration_form_username
data = {
fos_user_registration_form[username]:$("#fos_user_registration_form_username").val(),
fos_user_registration_form[email]:$("#fos_user_registration_form_email").val(),
fos_user_registration_form[plainPassword]:$("#fos_user_registration_form_plainPassword").val(),
};
i have this code but its not working. it says to me ajax post is success but when i look make refresh i saw its not liked.
<?
if ($data->user_has_liked == false)
{
?>
<span class="<?=$data->id;?>">Like</span>
<? } else { echo 'Liked'; } ?>
<script type="text/javascript">
$('a.like').click(function() {
var mediaId = $(this).attr('id');
$.ajax({
url: "https://api.instagram.com/v1/media/" + mediaId + "/likes?callback=?",
dataType: "jsonp",
data: {
access_token: '<?=$access_token;?>',
_method: 'POST'
},
type: "POST",
success: function(data, textStatus, jqXHR) {
$("."+mediaId+"").text('Liked');
},
error: function(jqXHR, textStatus, errorThrown) {
$("."+mediaId+"").text('Error!<br/>' + textStatus + ' - ' + errorThrown);
}
});
});
</script>
I am building something similar and have ran into this problem recently.
Even though your request is sent as a type: POST the request itself is actually sent as GET. This causes your request to return successful without liking anything. Instead it will return all the data for that Media ID.
If you change your datatype to JSON instead of JSONP you request should work as you wish; however, it may require an HTTPS connection requiring an SSL.
I implemented Django ajax comment submission in my app using Nick Carroll's method here. I'd like the user that posted the comment, date of submission and comment to appear on the page using ajax after the server has received and saved it. What's a good way to do this?
Use jquery's post method to post the comment to server and on successful response,display the comment on the page from the success call back function.
Alright this is kind of a hackerish way to go about this, but I think I've figured out a decent solution:
<script type="text/javascript" charset="utf-8">
function bindPostCommentHandler() {
$('#comment_form form input.submit-preview').remove();
$('#comment_form form').submit(function() {
var comment_text = $('#id_comment').val();
$.ajax({
type: "POST",
data: $('#comment_form form').serialize(),
url: "{% comment_form_target %}",
cache: false,
dataType: "html",
success: function(html, textStatus) {
$('#comment_form form').fadeTo(500, 0, function(){
$(this).remove();
});
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} var today = mm+'/'+dd+'/'+yyyy;
var comment = "<div class='comment'><h4>User " + "\"{{ user.username }}\"" + " Rating <small>" + today + "</small></h4>" + comment_text + "</div><hr />";
$(comment).hide().prependTo("#comments_loc").fadeIn(1000);
bindPostCommentHandler();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#comment_form form').replaceWith('Your comment was unable to be posted at this time. We apologize for the inconvenience.');
}
});
return false;
});
}
$(document).ready(function() {
bindPostCommentHandler();
});
</script>
I'm relatively new to javascript so I put this together with what little I know. Feel free to leave some comments if you think this could be cleaned up.
<script type="text/javascript" charset="utf-8">
function bindPostCommentHandler() {
$('#comment_form form input.submit-preview').remove();
$('#comment_form form').submit(function() {
$.ajax({
type: "POST",
data: $('#comment_form form').serialize(),
url: "{% comment_form_target %}",
cache: false,
dataType: "html",
success: function(html, textStatus) {
$('#comment_form form').replaceWith(html);
$('.comt_message').show();
bindPostCommentHandler();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$('#comment_form form').replaceWith('Your comment was unable to be posted at this time. We apologise for the inconvenience.');
}
});
return false;
});
}
$(document).ready(function() {
bindPostCommentHandler();
});
</script>
My Azure web role uses Ajax to call a function (in default.aspx.cs) that delegates work to worker roles. Worker roles may take up to 30-40 minutes depending on input file selected by user. If the worker roles return the result quickly it is received by the webrole and displays correctly on the web page. If it takes long the results are still received by the webrole (tried printing to trace) but nothing gets displayed on the web page.
I feel there is some kind of time out that kills the connection between the ajax code on the page and the webrole.
The code looks like:
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnSubmit").click(function () {
var params = '{ map1 : "' + document.getElementById('<%=ddlMap1.ClientID %>').value + '",' +
'map2 : "' + document.getElementById('<%=ddlMap2.ClientID %>').value + '",' +
'op : "' + document.getElementById('<%=ddlOperator.ClientID %>').value + '"}';
$('#spinner').show();
$('#results').text('');
$.ajax({
type: "POST",
url: "Default.aspx/Overlay",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var dmsg = '';
if (msg == null) {
dmsg = 'null';
} else {
dmsg = msg.d;
}
$('#spinner').hide();
$('#results').text(dmsg);
},
error: function (error) {
$('#results').text('');
}
});
});
});
</script>
The azure load balancer kills any inactive connections after 1 minute. See my answer to this question about how to work around this problem.
I would try to override the default timeout value of jquery to see if it helps:
$.ajaxSetup({
timeout: 3600000 // one hour
});
This issue could be caused by jquery but also be dependent on browser and network settings as stated in this SO question.