Codeigniter Post not accepting string URL - ajax

I try to send an ajax post with URLs but it returns 403 forbidden, it works on my localhost but it does not work when deployed online (LAMP)
Form Code
<form id="Links">
<input type="url" name="link1" id="link1" />
<input type="url" name="link2" id="link2" />
<input type="button" value="submit" id="submitLink" />
</form>
Jquery Code
$(document).ready(function()({
$("#submitLink").click(function(){
$.post("http://mysite.com/mycontroller/myfunction", $("#Links").serialized(), function(data){
alert("success!");
});
});
});
PHP CI Function
public function myfunction()
{
print_r($this->input->post());
die();
}
Viewing the ajax post on firebug console.. it shows 403 forbidden.. in online deployment.. but it works on localhost.
P.S.
My global xss filtering in config is set to false

Their are following things which need to be consider.
Check the controller and method is present
Is any restriction applied through .htaccess
Check file permissions for reading and writing.

Related

recaptcha v3 frontend returning strange, emptyish (invalid?) result with )]}'

I am trying to follow the instructions for reCAPTCHA v3 but can't seem to get even the basics down. Seems like the grecaptcha execute is returning a very strange, unusable result. I am testing this on localhost:7684
<script src='https://www.google.com/recaptcha/api.js?render=MYSITEKEY'>
</script>
<script>
grecaptcha.ready(function() {
grecaptcha.execute('MYSITEKEY', {action:
'action_name'}).then(function(token) {
console.log(token);
alert(token);
});
});
</script>
<form action="http://localhost:7684/botcheck" method="post">
<input type="text" name="name" value="" placeholder="name" required />
<button type="submit">submit</button>
</form>
The console is showing the token is null, and my chrome debugger is showing this response:
)]}'
["rresp",null,null,null,null,null,10]
chrome dev tools
Ok, that was stupid. The problem was I had to change the action parameter to anything else. Looks like they return that result for the default action name "action_name"

POST form data using AJAX and return object

I have created a form which has two inputs and a submit button. The form will post to a RESTful service which is all set up.
I want to use AJAX in order to POST to this RESTful service and then return the object so I can then validate the form.
The object will return something like this for an error and one similar for success
{"status":"error","message":"Incorrect username or password."}
My code is below. When i test I am using XAMPP on localhost:81. When I submit the form I receive this error.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
<form name="login-form" id="login-form" method="post" action="SERVICEHERE">
<label id="error">Sorry it seems your credentials are incorrect</label>
<div class="inputBlock">
<label for="username">Username</label>
<input type="text" id="username" name="username"/>
</div>
<div class="inputBlock">
<label for="password">Password</label>
<input type="password" id="password" name="password"/>
</div>
<input type="submit" value="Login" id="submit" />
</form>
$(document).ready(function () {
$("#login-form").submit(function (e) {
e.preventDefault();
var formData = $("#login-form").serialize();
console.log(formData);
$.ajax({
type: "GET",
url: $("#login-form").attr('action'),
data: formData,
success: function(data) {
alert(data);
}
});
});
});
You can't post content to a different domain from javascript. It's not allowed for security reasons, and it is blocked by your browser.
When you execute an XmlHttpRequest by your webpage's javascript to another domain, your browser sets your domain name in the Origin header in your request. That target domain has to respond with a header called Access-Control-Allow-Origin containing your domain as well, meaning it allows your domain's clients to call it. Otherwise the browser will block the call.
Reference : https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
EDIT: There are ways to bypass the browser security and allow CORS all the time : https://www.thepolyglotdeveloper.com/2014/08/bypass-cors-errors-testing-apis-locally/

How to show flash.message in Grails after AJAX call

I want to show some flash message after completion of AJAX call. I am doing like this ..
Controller Action --
def subscribe()
{
def subscribe = new Subscriber()
subscribe.email = params.subscribe
if (subscribe.save())
{
flash.message = "Thanks for your subscribtion"
}
}
View Part --
Subscribe :
<g:formRemote onSuccess="document.getElementById('subscribeField').value='';" url="[controller: 'TekEvent', action: 'subscribe']" update="confirm" name="updateForm">
<g:textField name="subscribe" placeholder="Enter your Email" id="subscribeField" />
<g:submitButton name="Submit" />
</g:formRemote >
<div id="confirm">
<g:if test="${flash.message}">
<div class="message" style="display: block">${flash.message}</div>
</g:if>
</div>
My AJAX working fine but it is not showing me flash.message. After refresh page it displaying message. How to solve it ?
When you use ajax your page content isn't re-parsed, so your code:
<g:if test="${flash.message}">
<div class="message" style="display: block">${flash.message}</div>
</g:if>
will not run again.
So I agree with #James comment, flash is not the better option to you.
If you need to update your view, go with JSON. Grails already have a converter that can be used to this:
if (subscribe.save()) {
render ([message: "Thanks for your subscribtion"] as JSON)
}
And your view:
<g:formRemote onSuccess="update(data)" url="[controller: 'TekEvent', action: 'subscribe']" name="updateForm">
<g:textField name="subscribe" placeholder="Enter your Email" id="subscribeField" />
<g:submitButton name="Submit" />
</g:formRemote >
<script type='text/javascript'>
function update(data) {
$('#subscribeField').val('');
$('#confirm').html(data.message);
}
</script>
You have couple options,
First you can try to return the message from your controller in a form of json or a map and render it on the screen your self using javascript libraries, which is a bit different if you want to use Grails ajax tags.
The other option is using a plugin like one-time-data , which
Summary A safe replacement for "flash" scope where you stash data in
the session which can only be read once, but at any point in the
future of the session provided you have the "id" required.
Description
This plugin provides a multi-window safe alternative to flash scope
that makes it possible to defer accessing the data until any future
request (so long as the session is preserved).
more
Hope it helps

Load Dojo form from ajax call

I am trying to implement something like this.
http://app.maqetta.org/mixloginstatic/LoginWindow.html
I want the login page to load but if you click the signup button then an ajax will replace the login form with the signup form.
I have got this to work using this code
dojo.xhrGet({
// The URL of the request
url: "'.$url.'",
// The success callback with result from server
load: function(newContent) {
dojo.byId("'.$contentNode.'").innerHTML = newContent;
},
// The error handler
error: function() {
// Do nothing -- keep old content there
}
});'
the only problem is the new form just loads up as a normal form, not a dojo form. I have tried to return some script with the phaser but it doesnt do anything.
<div id="loginBox"><div class="instructionBox">Please enter your details below and click <a><strong>signup</strong>
</a> to have an activation email sent to you.</div>
<form enctype="application/x-www-form-urlencoded" class="site-form login-form" action="/user/signup" method="post"><div>
<dt id="emailaddress-label"><label for="emailaddress" class="required">Email address</label></dt>
<dd>
<input 0="Errors" id="emailaddress" name="emailaddress" value="" type="text"></dd>
<dt id="password-label"><label for="password" class="required">Password</label></dt>
<dd>
<input 0="Errors" id="password" name="password" value="" type="password"></dd>
<dt id="captcha-input-label"><label for="captcha-input" class="required">Captcha Code</label></dt>
<dd id="captcha-element">
<img width="200" height="50" alt="" src="/captcha/d7849e6f0b95cad032db35e1a853c8f6.png">
<input type="hidden" name="captcha[id]" value="d7849e6f0b95cad032db35e1a853c8f6" id="captcha-id">
<input type="text" name="captcha[input]" id="captcha-input" value="">
<p class="description">Enter the characters shown into the field.</p></dd>
<dt id="submitButton-label"> </dt><dd id="submitButton-element">
<input id="submitButton" name="submitButton" value="Signup" type="submit"></dd>
<dt id="cancelButton-label"> </dt><dd id="cancelButton-element">
<button name="cancelButton" id="cancelButton" type="button">Cancel</button></dd>
</div></form>
<script type="text/javascript">
$(document).ready(function() {
var widget = dijit.byId("signup");
if (widget) {
widget.destroyRecursive(true);
}
dojo.parser.instantiate([dojo.byId("loginBox")]);
dojo.parser.parse(dojo.byId("loginBox"));
});
</script></div>
any advice on how i can get this to load as a dojo form. by the way i am using Zend_Dojo_Form, if i run the code directly then everything works find but through ajax it doesnt work. thanks.
update
I have discovered that if I load the form in my action and run the __toString() on it it works when i load the form from ajax. It must do preparation in __toString()
Firstly; You need to run the dojo parser on html, for it to accept the data-dojo-type (fka dojoType) attributes, like so:
dojo.parser.parse( dojo.byId("'.$contentNode.'") )
This will of course only instantiate dijits where the dojo type is set to something, for instance (for html5 1.7+ syntax) <form data-dojo-type="dijit.form.Form" action="index.php"> ... <button type="submit" data-dojo-type="dijit.form.Button">Send</button> ... </form>.
So you need to change the ajax contents which is set to innerHTML, so that the parser reckognizes the form of the type dijit.form.Form. That said, I urge people into using a complete set of dijit.form.* Elements as input fields.
In regards to:
$(document).ready(function() {});
This function will never get called. The document, youre adding innerHTML to, was ready perhaps a long time a go.
About Zend in this issue:
Youre most likely rendering the above output form from a Zend_ Dojo type form. If the renderer is set as programmatic, you will see above html a script containing a registry for ID=>dojoType mappings. The behavior when inserting <script> as an innerHTML attribute value, the script is not run under most circumstances (!).
You should try something similar to this pseudo for your form controller:
if request is ajax dojoHelper set layout declarative
else dojoHelper set layout programmatic

AJAX call then page redirect

I can call an AJAX request when a form submit button is clicked, but if the page reloads/redirects due to the form submission, will the AJAX request still complete? I'm asking this so I could do something like upload a file via AJAX as the form is submitted.
I'm pretty sure I can't get the output of the AJAX call, but could I be wrong?
It's possible, but there's no guarantee that the request would have completed by the time you leave the page. If you're submitting a form via AJAX and also want to submit a file, you might consider placing the file upload in a completely separate form tag, then trigger the form submission after the AJAX call is successful. For example:
<!-- First form with your data -->
<form action="/your/url/here" method="post" id="form1">
<input type="text" name="title" />
<input type="submit" value="Save" />
</form>
<!-- Second form with your file -->
<form action="/uploadfile" method="post" id="form2" enctype="multipart/form-data">
<input type="file" name="fileupload" />
</form>
Then in Javascript (using jQuery example for brevity, note I haven't tested this code at all):
$('#form1').bind('submit', function() {
$.ajax({
url: $(this).attr('action'),
data: $(this).serialize(),
type: 'post',
success: function() {
$('#form2').submit();
}
});
return false;
});

Resources