laravel 419 status code (unknown status) - ajax

I do an ajax call but I keep getting this error:
419 (unknown status)
i include in meta tag:
<meta name="csrf-token" content="{{ csrf_token() }}">
my table (without form):
<table class="table" id="dataTables">
<thead>
<tr>
<td>Full nametd>
<td class="text-center">Lớp</td>
<td class="text-center"><input type="checkbox" id="select_all"></td>
</tr>
</thead>
</table>
i use DataTables library load all data from Controller:
var table = $('#dataTables').DataTable({
"pagingType": "full_numbers",
"processing": true,
"serverSide": true,
"lengthMenu": [[5, 10, -1], [5, 10, "All"]],
"iDisplayLength": 5,
"ordering": false,
"ajax": '{!! url(Request::segment(1).'/lists?class_id='.Input::get('class_id')) !!}',
'createdRow': function (row, data, dataIndex) {
$(row).attr('id', data.id);
},
"columns": [
...
{
"data": "id", "sClass": "text-center",
"fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("<input type='checkbox' name='check[]' value='" + oData.id + "'>");
}
},
],
"language": {
"url": "{{url('public/extension/datatables/vietnamese.json')}}"
}
});
My Ajax:
$('#save').click(function () {
$.ajax({
type: 'POST',
url: "{{url('class/store')}}",
cache: false,
data: {"check": sThisVal }, //sThisVal get all input checkbox checked
success: function (r) {
$('#msg').html(r);
},
error: function (jqXHR, text, errorThrown) {
$('#msg').html(jqXHR + " " + text + " " + errorThrown);
}
});
});
My route:
Route::post('class/lists', 'ClassController#lists');
My controller method
public function store(Request $request){
var_dump($request->all());exit;
}
Result after click submit is null ???

In addition to putting the crsf-token value in the header meta you need to pass it through in your AJAX requests with something like:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
This is from: https://laravel.com/docs/5.6/csrf#csrf-x-csrf-token

I added the crsf-token in the data section on my ajax and it worked like a charm for me.
$('#save').click(function () {
$.ajax({
type: 'POST',
url: "{{url('class/store')}}",
cache: false,
data: {
"check": sThisVal,
"_token": "{{ csrf_token() }}",
}, //sThisVal get all input checkbox checked
success: function (r) {
$('#msg').html(r);
},
error: function (jqXHR, text, errorThrown) {
$('#msg').html(jqXHR + " " + text + " " + errorThrown);
}
});
});
Hope this Helps

sometimes all u need to do to fix this is to make the method post caps like the below

Related

Rust Hyper CORS Policy error on Ajax GET request

I am working to get the JSON response from the Rust Hyper Server using the AJAX. Here is the Rust code.
extern crate hyper;
extern crate futures;
#[macro_use]
extern crate serde_json;
use hyper::{Body, Response, Server, Method, StatusCode};
use hyper::service::service_fn_ok;
use futures::Future;
fn main() {
let router = || {
service_fn_ok(|req| {
match(req.method(), req.uri().path()) {
(&Method::GET, "/") => {
Response::new(
Body::from(
json!([{
"id": "01",
"Name": "faheem"
},
{
"id": "02",
"Name": "waseem"
}]).to_string()
)
)
},
(_, _) => {
let mut res = Response::new(Body::from("not found"));
*res.status_mut() = StatusCode::NOT_FOUND;
res
}
}
})
};
let addr = "127.0.0.1:3000".parse().unwrap();
let server = Server::bind(&addr).serve(router);
hyper::rt::run(server.map_err(|e| {
eprintln!("server error: {}", e);
}));
}
The Ajax code. This code is working fine and well with NodeJS server. By just adding the header Access-Control-Allow-Origin in the middle ware. But, in the rust hyper environment I could find any documentation which will help to add the Access-Control-Allow-Origin in the Server environment of Hyper.
<script>
$(document).ready(function () {
BindTable();
$("#btnSend").click(function () {
$.ajax({
crossDomain: true,
url: "http://localhost:3000/add",
type: "POST",
contentType: 'application/json',
data: JSON.stringify({
'student': $('#student').val(),
}),
success: function(data){
console.log(data);
$("#tbDetails").text("");
BindTable();
}
});
});
});
function BindTable()
{
$.ajax({
type: 'GET',
async: false,
headers: {
'Access-Control-Allow-Origin': 'http://localhost:3000/'
},
crossDomain: true,
url: "http://localhost:3000/",
contentType: "application/json",
dataType: "json",
success: function (msg) {
console.log(msg);
$.each(msg, function (index) {
var row = '<tr><td> ' + msg[index].id + ' </td> <td> ' + msg[index].name + ' </td></tr>';
$("#tbDetails").append(row);
});
}
});
}
</script>
<label for="student">Add student</label>
<input id="student" name="student" type="text" value="" />
<input id="btnSend" type="button" value="Send" />
<table id="tbDetails" border="1" cellpadding="2">
<tr>
<td>ID</td> <td>Name</td>
</tr>
<tbody>
</tbody>
</table>
The error
You should add Access-Control-Allow-Header entry in the HTTPResponse settings of the server you have hosted. Further in your code in Ajax request the header value is commented after http. Close this entry in double quotation.

Jquery Datatable: Data won't load using ajax

This is my first time using Jquery datatable.
I don't know what's wrong with my code, but the data won't load into the datatable.
Here's the script:
$(document).ready(function () {
$.ajax({
type: "POST",
url: "TestDPRDetail.aspx/GetdtbScenario",
contentType: "application/json;charset=utf-8",
datatype: "json",
success: function (data) {
$('#grvScenario').dataTable({
data: data,
columns:
[
{ "data": "SCENARIO_ID" }
]
});
},
});
});
The url: TestDPRDetail.aspx/GetdtbScenario returns a datatable json serialized object
<System.Web.Script.Services.ScriptMethod()> _
<WebMethod()> _
Public Shared Function GetdtbScenario() As Object
Dim dtbScenarioTemp As New DataTable
Dim strDPR_ID As String
Dim clsScenarioBusiness As New ScenarioBusiness
Dim json As Newtonsoft.Json.JsonConvert
strDPR_ID = "DPR-201807-00001"
dtbScenarioTemp = clsScenarioBusiness.GetdtbScenario(strDPR_ID) 'getting data from sql
Return json.SerializeObject(dtbScenarioTemp)
End Function
I checked with a normal method (using array object) to load the datatable, it works fine:
var dataTemp = [{ "SCENARIO_ID": "SCN-201807-00008", "SCENARIO #": "B", "SCENARIO NAME": "Test Inquiry", "CONDITION": "Negative" }]
$('#grvScenario').dataTable({
data: dataTemp,
columns: [
{"data":"SCENARIO_ID"}
]
});
Here's the HTML:
<body>
<form id="form1" runat="server">
<div>
<table id="grvScenario">
<thead>
<tr>
<th>Scenario ID</th>
</tr>
</thead>
</table>
</div>
</form>
</body>
Is there something i missed from the ajax or datatable?
Try to initialize datatables first:
$(document).ready(function () {
$('#grvScenario').dataTable({
ajax: "TestDPRDetail.aspx/GetdtbScenario",
columns: [
{ "data": "SCENARIO_ID" }
]
})
});
After some trial and error, i've got my answer
It seems that TestDPRDetail.aspx/GetdtbScenario was returning a different json object after ajax call.
The return variable (data) needs to be parsed again in javascript. So it will look like this:
$.ajax({
type: "POST",
url: "TestDPRDetail.aspx/GetdtbScenario",
contentType: "application/json;charset=utf-8",
datatype: "json",
success: function (data) {
$('#grvScenario').dataTable({
data: JSON.parse(data.d),
columns:
[
{ "data": "SCENARIO_ID" }
]
});
},
});
Hope it will help anyone having the same issue

Opencart cart.add() with option

I'm looking for solution in opencart.
Need to rebuild cart.add function for adding product with option value.
By default:
'add': function(product_id, quantity) {
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
dataType: 'json',
beforeSend: function() {
$('#cart > button').button('loading');
},
success: function(json) {
$('.alert, .text-danger').remove();
$('#cart > button').button('reset');
if (json['redirect']) {
location = json['redirect'];
}
if (json['success']) {
$('#content').parent().before('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + '<button type="button" class="close" data-dismiss="alert">×</button></div>');
$('#cart-total').html(json['total']);
$('html, body').animate({ scrollTop: 0 }, 'slow');
$('#cart > ul').load('index.php?route=common/cart/info ul li');
}
}
});
checkout/cart/add php side for option:
if (isset($this->request->post['option'])) {
$option = array_filter($this->request->post['option']);
} else {
$option = array();
}
Any solutions?
You can do this in the following way. Create a simple Javascript object.
var productData = {'product_id' : PRODUCT_IDS.CARD, 'quantity': 1,'option':{'229':"Some option value"}};
And send the request as follows. Converting the object to post params using the param function.
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: $.param(productData),
dataType: 'json',
beforeSend: function () {
},
complete: function () {
},
success: function (json) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
Also there are some other ways to do this, you can see possible payload formats in the /controller/checkout/cart.php file.

ajax is not accessing to my button inside datatable

I want to access to my button inside datatable which is inside of my modal, but when I want to access it wont load any alert , ajax url or whatever thing even If I change id or class of "a" tag. how can I fix it? this ajax I know it wont load and error in console, but it also show it..
ajax
$(function(event) {
URL_GET_VIEW_SEARCH_PRODUCT = BASE_URL + 'sale/sales/getViewSearch';
URL_GET_DATATABLE = BASE_URL + 'sale/sales/datatable';
URL_SEARCH_PRODUCT = BASE_URL + 'sale/sales/search_product';
$('#btn-search').click(function (e) {
BootstrapDialog.show({
title: 'Search Product',
message: function(dialog) {
var $message = $('<div></div>');
var pageToLoad = dialog.getData('pageToLoad');
$message.load(pageToLoad);
return $message;
},
data: {
pageToLoad: URL_GET_VIEW_SEARCH_PRODUCT
},
onshown: function(dialog){
$('#example').DataTable({
lengthChange: false,
responsive: true,
ajax: {
url: URL_GET_DATATABLE,
type: 'POST',
},
columnDefs: [{
targets: 4,
data: null,
defaultContent: "<a href='#'><span class='glyphicon glyphicon-plus'></span></a>"
}],
});
}
});
});
$('#search').typeahead({
source: function (query,process) {
$.ajax({
url: URL_SEARCH_PRODUCT,
type: 'POST',
data: {query: query},
dataType: 'json',
async: true,
success: function (data) {
console.log(data);
process(data);
}
});
}
});
$('#example tbody').on('click', 'a', function(event) {
$.ajax({
url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
data: {param1: 'value1'},
})
});
});
table view
<table id="example" class="table table-bordered table-striped" cellspacing="0" width="100%">
<thead>
<tr>
<th>Code</th>
<th>Description</th>
<th>Stock</th>
<th>Price</th>
<th></th>
</tr>
</thead>
</table>

Getting textbox value from X-editable

How do you get the value of the textbox field and send as data inside of ajaxOptions? I tested my view and it prints out the test variable successfully from my Django views. I am using X-editable for Jquery. Heres what textbox input looks like:
http://jsfiddle.net/xBB5x/197/
views.py
def create_post(request):
print request.POST.get("test", "");
return HttpResponse(json,content_type="application/json")
HTML
<a id="other1" data-pk="First Name" data-name="test">First Name</a>
AJAX
$(document).ready(function() {
$('#other1').editable({
type: 'text',
pk: 1,
url: '/create_post/',
ajaxOptions: {
data: {
csrfmiddlewaretoken: '{{ csrf_token }}',
test: "hi",
},
},
placement: 'top',
title: 'New Expense',
success: function(response, newValue) {
if(response.status == 'error') return response.msg; //ms
},
});
});
Instead of ajaxOptions, use params. If I remember correctly, test and its value will be included in your POST request by x-editable. Try something like this:
Html
<a id="other1" data-pk="1" data-name="test">First Name</a>
AJAX
$(document).ready(function() {
$('#other1').editable({
type: 'text',
url: '/create_post/',
params : function(params) {
params.csrfmiddlewaretoken = '{{ csrf_token }}';
return params;
},
placement: 'top',
title: 'New Expense',
success: function(response, newValue) {
if(response.status == 'error') return response.msg; //ms
},
});
});

Resources