i will try to a bulk data send to another domain via api that will created at controller in laravel project
my function
public function test_prod_insert()
{
$usrl= url('/public/wheel_images/rohana_imgs');
$users = DB::table('products')->select('id','title','sku','image1')->skip(0)->take(2)->get();
echo"<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
<script type='text/javascript' src='https://trk.mtrl.me/tracking.js?token=**********'></script>";
foreach($users as $data){
echo"<script>
var model = {
'time': 1518004715732,
'token': '***************',
'platform': 'laravel',
'pluginVersion': '1.1.0',
'params': {
'categories': [
'2'
],
'id': '<?= $data->id ?>',
'sku': '<?= $data->sku ?>',
'imageUrl': '<?= $usrl ?>/<?= $data->image1 ?>',
'name': '<?= $data->title ?>',
'price': '',
'url': '',
'options': [
]
}
};
$.ajax({
type: 'POST',
data: JSON.stringify(model),
url: 'https://trk.mtrl.me/product',
contentType: 'application/json'
}).done(function(res) {
console.log('res', res);
// Do something with the result :)
});
</script>";
}
}
in console show " mysite has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response " i try some similar answer but the issue is not solved please help me to solve this issue...
There is nothing that you can do much in CORS: But it's all realted to the host site that you are calling, Basically it's a browser feature so it will prevent the request to host site if in the headers it doesn't see
"Access-Control-Allow-Origin: *"
So in your host site which you are calling, just make sure that it accept connections from your domain and then you can call the API.
EDIT
Writing this again don't make sense, But this is how you can implement it
Add CORS as Middleware in Laravel
Related
I'm currently building a web application using CodeIgniter 4. In one of my forms, I need ajax to send a post request and get the data result to modify the form base on item selected on a combo box.
The first requests were always okay, but it won't work for the next one. When I refresh the page, it redirects me to login page, due to my filter. It turns out that the AJAX request either destroy all my sessions, or update it to the new ones.
this is my ajax :
`
$('#penilaian_jenis').on('change', function() {
$.ajax({
OST type: "P",
url: '<?= base_url('guru/penilaian/get_nilai') ?>',
data: {
'kelas_id': '<?= $kelas->kelas_id ?>',
'kd_id': '<?= $kd->kd_id ?>',
'penilaian_jenis': $('#penilaian_jenis').val(),
},
dataType: 'json',
success: function(data) {
var result = JSON.parse(data);
alert(result);
}
})
})
`
This is my Controller :
`
public function get_nilaii()
{
echo json_encode('success');
}
`
This is how I stored my session at the auth controller:
$data = [
'user' => $user,
'guru' => $model->where('user_id', $user->user_id)->first(),
'guru_logged_in' => 1,
];
session()->set($data);
My Ajax codes I user are the simplest one. Can Anyone help give me the solutions to this problem, or recommend me another way to do HTML request without losing all my sessions?
Sorry for bad grammar, and thank you in advance
I've this problem with Laravel ajax when hosted in AWS-EC2 resulting in 419 unknown status response.
I've searched and tried almost all solutions given, but the problem still exists.
My meta tag includes CSRF
<meta name="csrf-token" content="{{ csrf_token() }}">
Below is my laravel ajax code
$(document).ready(function () {
var BASE_URL = "{{url('/')}}";
$("form[name='logForm']").validate({
rules: {
log_email: {
required: true,
email: true
},
log_password: {
required: true,
minlength: 5
},
},
messages: {
log_email: "Please enter a valid email address",
log_password: "Enter a valid password",
log_email: "Please enter a valid email address"
},
submitHandler: function(form) {
logForm();
}
});
function logForm() {
log_email=$("#log_email").val();
log_password=$("#log_password").val();
error=0;
if (log_email == '' && log_password=='') {
error = 1;
}
if (error == 0) {
$.ajaxSetup({
// beforeSend: function(xhr, type) {
// if (!type.crossDomain) {
// xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
// }
// },
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
//url : BASE_URL + '/userlogin',
url: '/userlogin',
data: {
'_token': '{!! csrf_token() !!}',
'email': $("#log_email").val(),
'password': $("#log_password").val()
},
dataType: 'json',
type: 'POST',
cache: false,
success: function (response) {
if (response.type =='success') {
#if(Request::is('page-not-found'))
window.location=BASE_URL;
#else
window.location.reload();
#endif
} else if(response.type=='suspended'){
$('#log_suspended').show();
$('#log_spiner').hide();
}
else {
$('#log_err').show();
$('#log_spiner').hide();
//alert(response.message);
}
},
});
}
}
});
I've commented few lines above in the jquery, those are the solutions i tried.
Tried adding,
contentType: false,
processData: false,
as well, if i add processData, in the console Form-Data its displayed as [object Object]
And below is the Request Headers and Form Data which is taken from console :
And in my web.php page i have the following :
Route::post('/userlogin', 'HomeController#login');
The same above code works in existing hosting and in my localhost as well.
I also made sure that the APP_URL and SESSION_DOMAIN in .env to be same.
I can give any more information if needed.
*The question might sound as a Duplicate, but those answers didn't work for me when tried.
Kindly advise.
Thanks
-Vijay
I Found the solution.
Many questions pointed to check for this :
I also made sure that the APP_URL and SESSION_DOMAIN in .env to be
same.
But i found in one of the stack questions to remove SESSION_DOMAIN from .env and then make sure
'domain' => env('SESSION_DOMAIN', null),
line is present in config/session.php
This worked for me.
Might kelp someone who's facing similar problem like mine.
I am making a Ajax call to the admin-ajax.php with a fetch API syntax. Here is the code that calls the back-end script:
fetch(ajax_obj.ajaxurl, {
method: "POST",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
body: JSON.stringify(this.data),
headers: {
"Content-Type": "application/json"
}
})
and getting 400 Bad Request response.
Can someone tell me where does this request is not right?
When checking the Network Development Tools in chrome, I can see that the body that is sent is ok, the url is also ok...
... and as far as I know 4xx status codes are for errors on the client, so I don't even look on the server side code... if I am wrong please give me feedback on this...
Actually, I had jQuery ajax call like this:
this.data = {
'action': 'ajax_product_query',
'locations': this.locations,
'type': this.category != '' ? this.category : [],
'all-locations': this.filters['locationFilter'].all.checked,
'page': ajax_obj.current_page
};
$.ajax({
url: ajax_obj.ajaxurl,
method: 'post',
dataType: 'json',
data: this.data,
beforeSend: function(xhr) {
button.innerHTML = 'Loading...';
},
success: (data) => { ...
... and it worked like a charm...
Than, willing to remove jQuery dependency, wanted to turn the jQuery ajax call into Fetch API syntax like this:
fetch(ajax_obj.ajaxurl, {
method: "POST",
mode: "cors",
cache: "no-cache",
credentials: "same-origin",
body: JSON.stringify(this.data),
headers: {
"Content-Type": "application/json"
}
})
.then(response => response.json()) ...
And than the requests turned into 400 Bad Requests...
Thanks!
Because after JS fetch 'POST' request you can't get $_POST data in Php. Dirty solution. You could add this code in u "/wp-admin/admin-ajax.php" to resolve this:
if ( !empty( trim( file_get_contents("php://input" ) ) ) ) {
$post = trim(file_get_contents("php://input"));
$_POST = ( array ) json_decode( $post );
$_REQUEST['action'] = $_POST['action'];
}
Or try to find a better solution.
P.S. Sorry for my English
I'm developing an Extjs-6 application. My server application is RestFul. I have to login with Ajax. I send an Ajax request as follow:
Ext.Ajax.request({
url: 'localhost:8084/Calk/j_spring_security_check',
params: {j_username: 'ali', j_password: '123456',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
success: ...,
faiulure: ...,
});
Result of the request is as follow:
After client receive 200 OK, it read a store as follow:
Ext.define('Calk.store.Calk', {
extend: '...',
model: '...',
proxy: {
type: 'ajax',
url: 'localhost:8084/Calk/calk/all',
withCredentials: true,
useDefaultXhrHeader: false,
reader: ...,
method: 'POST'
});
But result is as follow:
Why cookie set wrong? How Can I Fix it?
Set the following lines in Ext config:
Ext.Ajax.on("beforerequest",function(con){
con.setUseDefaultXhrHeader(false);
con.setWithCredentials(true);
});
So all of ajax requests will send cookie.
I try to send an HTTP POST request from ajax to PHP, but I have a syntax error that I don't understand..
Is there anyone who can help me ?
index.php
var key = "keytest";
$.ajax({
url: 'requests.php',
type: 'post',
contentType: 'application/json',
dataType: 'json',
data: '{"uniqueKey" : '+key+'}',
success:function( rep ) {
$('#content').html(rep.content);
},
error:function(a,b,err){
console.log(err);
}
});
requests.php
header('Content-type: application/json');
$uniqueKey = filter_input(INPUT_POST, 'uniqueKey');
$key = "newKey";
$retour = array('key' => $key);
echo json_encode($retour);
Don't build JSON by hand, use JSON.stringify
data: JSON.stringify({uniqueKey: key}),
Php does not populate $_POST(INPUT_POST) when the request body is JSON, only for application/x-www-form-urlencoded or multipart/form-data
To get json you'll have to read it from php://input
$json = file_get_contents('php://input');
$obj = json_decode($json);
$uniqueKey = $obj->uniqueKey;
Also you code only responds with a key value but the ajax request expects a content value. You should change the dataType to text to see if you get back what you expect.
$.ajax({
url: 'requests.php',
type: 'post',
contentType: 'application/json',
dataType: 'text',
data: JSON.stringify({uniqueKey: key}),
success:function( rep ) {
$('#content').html(rep);
},
error:function(a,b,err){
console.log(err);
}
});