I tried to use jQuery's ajax, but there is problem with cross domain requests(Canvas apps in Facebook are in iframe, and my browser Chrome, doesn't allow for making ajax requests to another domain (not facebook.com)).
Deprecated FBJS had Ajax proxy, but it is now deprecated.
How to deal with it?
Thanks for help.
If you use iframes, then making an AJAX call works. The iframe will be your own domain so it won't be a cross-domain request.
Actually you have to add cross domain requests in header.
I have done it in PHP.
JavaScript:-
Just have a look at it.
function ajax(id){
$.ajax({
type: "POST",
url: "json.php",
data: {id: id},
dataType : 'json',
forceIframeTransport: true, //force use iframe or will no work
success: function(result){
console.log(result);
},
error: function(errorThrown){
}
});
}
JSON.PHP:-
<?php
header('Access-Control-Allow-Origin: *');
$id = $_POST['id'];
$id = "test".$id;
$json = json_encode($id);
echo $json ;
?>
HTML CODE:-
<a onclick="ajax(3); return false;" id="result">Hello</a>
Related
I have an ajax function in jquery caling a cakephp4 function. The function doesnt work as it is giving a 403 forbidden error. The error is about headers but i cant find what I need to fix this exactly.
This code runs and it does get the var (alert verifies this). Nothing works ?
jquery
///
var freeassessmentid = "<?=$testid?>";
$.ajax({
url: "/freeassessments/freeasssesmenFinaltResult", //path is correct and it can be tested on its own
method: "POST",
dataType: "html",
data: { freeassessmentid:freeassessmentid },
success: function(response) {
//console.log(response);
$('#display-area').append(response); //no output
}
});
public function freeasssesmenFinaltResult($freeassessmentid=0)
{
//debug('test');
$html .= '<li class="listyle" style="height: auto;">hi<br/></li>';
$html .= '</ul>';
//no output
//https://stackoverflow.com/questions/36666256/jquery-ajax-call-results-in-error-status-403
The Ajax url should be:
url: "/freeassessments/freeasssesmen-finalt-result",
Use the kebab case for actions/methods in urls and the camel case for them in the controllers
You have to pass CSRF token in header during ajax call.
You can get CSRF token in many ways.
One of the simplest way is:
You can add bellow code to your head tag of parent layout or inside any of your template file.
<?php echo $this->Html->meta("csrfToken", $this->request->getAttribute("csrfToken")); ?>
At the time of ajax call you will have to get this csrf token and pass it to the ajax header.
Here is the example:
var token = $("meta[name='csrfToken']").attr("content");
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': token
}
});
$.ajax({
url: "path/to/controller/method",
method: "POST",
data: { pram1:val },
success: function(response) {
//console.log(response);
}
});
I hope it may help :)
I am working with CakePHP 3.6. I have a function that will return some data using AJAX call. This function will be called from any page of my website. It is like a button will be there and on clicking that button a modal will come with some data. Those data will come from AJAX call. So now the problem I am facing is with Csrf token. If I click from a page where a form is available then this AJAX call working perfect because there is a Csrf token available because of that form. But when I try clicking from a page where no form is available then AJAX is giving Csrf error. Because there is no Csrf added for that page.
This is how my button click and Ajax calling function looks like
$("#td-apt").on('click', function() {
getModalData();
$("#data-modal").modal('toggle');
});
function getModalData () {
$.ajax({
type: "POST",
url: "/function/Data",
headers: {
'X-CSRF-Token': $('input[name="_csrfToken"]').val()
},
dataType: "json",
success: function(data) {
console.log('success')
},
error: function() {
alert('Error');
}
});
}
So here are the things is it possible to generate Csrf token every time before calling this AJAX url. Or any other way to do this. Thanks
You can obtain the token from the request object in your view templates, for example in the layout to make it globally available:
<script>
var csrfToken = <?= json_encode($this->request->getParam('_csrfToken')) ?>;
// ...
</script>
You can then easily use it in your AJAX requests:
$.ajax({
headers: {
'X-CSRF-Token': csrfToken
},
// ...
});
Alternatively, if you already have some JS cookie parser at hand, you can obtain it from the cookie named csrfToken.
See also
Cookbook > Middleware > Cross Site Request Forgery (CSRF) Middleware
Cookbook > Middleware > CSRF Protection and AJAX Requests
Guys i have made a blog using Laravel framework, today I just heard about ajax, What I heard is in short: it loads data quickly. My issue is that I have many routes , controllers with views.
What steps do i need to use so called ajax javascript?
<script>
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content')
}
});
jQuery.ajax({
url:'/blog',
type: 'GET',
success: getIndex( ){
console.log( );
},
});
</script>
It is basically the same, when you make a HTTP request using ajax, you need to define the route you are requesting, for example this ajax request:
$.ajax({
type: 'post',
url: 'your/url',
dataType: 'json',
success: function (data) {
}
});
You define your route like a normal route would be, since this ajax request is type "post", you define your route as "post":
Route::post('your/url', 'yourController#yourFunctionInsideController')->name('your.route.alias');
Ajax can be used normally in Laravel, I particularly usually host my codes in '/ public / js' and then extend through the <script> so that the code is not mixed. I advise you to study Laravel's structure, read the documentation, see some videos. Your question is very broad, so I will leave some materials that are of interest to you.
Book by Novatec about Ajax:
https://www.novatec.com.br/livros/ajaxjquery/
Laravel Docs:
https://laravel.com/docs/5.4/
well after reading all the related topics still no success,
I have 4 files index.php with a simple form, after submit I use process.php to send back (ajax) errors to index.php using external script.js file and also send mail to the owner of this site,all i need is that the user will also be redirected to a thank-you.html page (if there are no errors of course) but no luck ,I have tried all the combinations suggested:
header("Location: http://www.mywebsite.com/thank-you.html");
header("Location:thank-you.html");
if (success).....
echo
<script type="text/javascript">
<!--
window.location = "http://www.website.com/thank-you.html";
//-->
</script>
I have tried to put it in the bottom of the process,php ,also in the top of the page also tried to put in the script.js-inside $ajax function but nothing:(((
Can anyone tell me what to do?
solved:
thank you all so much:))))) it should be inside the ajax function in the script , right after success: function(data){ I have placed it in the bottom of the script and it didnt work before but now its perfect!
If you're doing this inside of a jQuery $.ajax() call, use the "success" method instead.
$.ajax({
type: "post",
//etc...
success: function(){
window.location.href="thank-you.html"
}
});
The correct usage in JS is "window.location.href".
Also, a PHP file with "header" being set during an AJAX call won't redirect the client browser.
If I understand correctly you will need to handle the redirect once you get the response from process.php IE: in the success callback.
$.ajax({
success: function () {
window.location.href = 'thank-you.html';
}
});
echo '
<script type="text/javascript">
<!--
window.location = "http://www.website.com/thank-you.html";
//-->
</script>';
assuming that is from php you were missing quotes.
I handled it a little differently as I handled something similar recently. I have the PHP page echo back "true" (this could also just be an INT) and then run if/else statements in the ajax.
$.ajax({
url : "process.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
if (data == "true")
{
window.location = "http://www.website.com/thank-you.html";}
}
When dealing with OAuth from the server, such as Twitter and Facebook, you most likely will redirect the user to an URL asking for app permission. Usually, after clicking a link, you send the request to the server, via AJAX, and then return the authorization URL.
But when you try to use window.open when the answer is received, your browser blocks the popup, making it useless. Of course, you can just redirect the user to the new URL, but that corrupts the user experience, plus it's annoying. You can't use IFRAMES, but they are not allowed (because you can't see the location bar).
So how to do it?
The answer is quite simple, and works cross browser without any issues. When doing the AJAX call (I'll be using jQuery in this example), just do the following. Suppose we have a form with two buttons, Login with Twitter and Login with Facebook.
<button type="submit" class="login" value="facebook" name="type">Login with Facebook</button>
<button type="submit" class="login" value="twitter" name="type">Login with Twitter</button>
Then the Javascript code where the magic happens
$(function () {
var
$login = $('.login'),
authWindow;
$login.on('click', function (e) {
e.preventDefault();
/* We pre-open the popup in the submit, since it was generated from a "click" event, so no popup block happens */
authWindow = window.open('about:blank', '', 'left=20,top=20,width=400,height=300,toolbar=0,resizable=1');
/* do the AJAX call requesting for the authorize URL */
$.ajax({
url: '/echo/json/',
type: "POST",
data: {"json": JSON.stringify({"url": 'http://' + e.target.value + '.com'})}
/*Since it's a jsfiddle, the echo is only for demo purposes */
})
.done(function (data) {
/* This is where the magic happens, we simply redirec the popup to the new authorize URL that we received from the server */
authWindow.location.replace(data.url);
})
.always(function () {
/* You can poll if the window got closed here, and so a refresh on the main page, or another AJAX call for example */
});
});
});
Here is the POC in JSFiddle http://jsfiddle.net/CNCgG/
This is simple and effective :)
Try adding async: false. It should be working
$('#myButton').click(function() {
$.ajax({
type: 'POST',
async: false,
url: '/echo/json/',
data: {'json': JSON.stringify({
url:'http://google.com'})},
success: function(data) {
window.open(data.url,'_blank');
}
});
});