Rust Hyper CORS Policy error on Ajax GET request - ajax

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.

Related

Laravel Ajax delete record with button

I do not understand why it does not work:
Route
Route::delete('/dashboard/booking/deletebooking/{id}','ResourceController#deletebooking')->name('works.deletebooking');
ResourceController
public function deletebooking($id){
$booking = Booking::where('id','=',$id)->get();
$booking->delete();
return response()->json(['success' => true],200);
}
Table
<tr id="{{$booking->id}}">
<td class="roomId">{{$booking->room_id}}</td>
<td class="roomName">{{$booking->name}}</td>
<td class="roomLocation">{{$booking->sede}}</td>
<td class="start">{{$booking->start_date}}</td>
<td class="end">{{$booking->end_date}}</td>
<td>
<input type="hidden" name="_method" value="delete" />
<button class="btn btn-danger btn-xs" id="destroy" data-id="{{$booking->id}}" data-token="{{ csrf_token() }}">
<span class="glyphicon glyphicon-trash"></span>
</button>
</td>
</tr>
Request Ajax
$(".btn").click(function(){
var id = $(this).data('id');
// var $tr = $(this).closest('tr');
$.ajax({
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'POST',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
"id": id
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
I have this error:
Request URL: http://pickbooking.local/dashboard/booking/deletebooking/1
Request Method: POST
Status Code: 500 Internal Server Error
Remote Address: 192.168.10.10:80
The issue is in the method used for the ajax call post
// var $tr = $(this).closest('tr');
$.ajax(
{
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'POST',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
"id": id
},
success: function ()
{
console.log("it Work");
}
});
the data will be sent in the body of the request, and in a DELETE request, there is no body. so laravel wont see the _method, or the _token. Either you send them in a GET request and let the _method do it's job (it will be in the url, not in the body), Or use the DELETE method in the ajax call
// var $tr = $(this).closest('tr');
$.ajax(
{
url: "/dashboard/booking/deletebooking/"+id,
dataType: "JSON",
type: 'DELETE',
data: {
'_token': $('meta[name=csrf-token]').attr("content"),
},
success: function ()
{
console.log("it Work");
}
});
Because I think you have an error something like
Method Illuminate\Database\Eloquent\Collection::delete does not exist.
Instead try something like this
$booking = Booking::where('id', '=', $id)->first();
$booking->delete();
so that $booking can have method delete()

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

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>

Second $.ajax call stuck the code

I have an ajax+jquery navigation system with $.ajax, and I`m trying to do a second call to $.ajax to send a contact form infos, but, when I add the second $.ajax all just stop working.
First Call -
function loadPage(url)
{
url=url.replace('#!','');
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "loader.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#conteudo').html(msg);
$('#loading').css('visibility','hidden');
}
}
});
}
Second Call
$("#enviar").click(function() {
var str = $("form").serializeArray();
$.ajax({
type: "POST",
url: "update.php",
data: str,
success: function(mn) {
if(parseInt(mn)!=0)
{
$("#conteudo").html(mn);
$("#enviado").css('visibility','visible');
}
}
return false;
});
#EDIT
Very good! The first ajax is not stucking anymore, but this second is not working as expected.
This is intended to parse $_POST values to a php script and if ok just turn div visible..
How I`m doing that -
<form name="formcontato" id="form">
<fieldset>
<label>Seu nome</label>
<input type="text" name="nome" class="input-block-level">
<label>Email</label>
<input type="email" name="email" placeholder="seu#email.com" class="input-block-level">
<div class="form-actions">
<input type="button" name="enviar" value="Enviar" id="enviar" class="btn btn-baixar" />
</div>
</fieldset>
</form>
This is the form.
$("#enviar").click(function () {
var str = $("#form").serialize();
$.ajax({
type: "POST",
url: "update.php",
data: str,
success: function (mn) {
alert("Ok!");
if (parseInt(mn) != 0) {
$("#conteudo").html(mn);
$("#enviado").css('visibility', 'visible');
}
}
});
return false;
});
This is the js
if($_POST) {
$nome = trim($_POST['nome']);
echo $nome;
}
This is the update.php
In what you posted, the second function does not properly close the $.ajax() function with a }); so it would generate a parse error and none of the code in this block would be available.
Try this where the $.ajax() call is succesfully closed.
$("#enviar").click(function () {
var str = $("form").serializeArray();
$.ajax({
type: "POST",
url: "update.php",
data: str,
success: function (mn) {
if (parseInt(mn) != 0) {
$("#conteudo").html(mn);
$("#enviado").css('visibility', 'visible');
}
}
});
return false;
});
FYI, proper and consistent indentation is essential to spotting these issues.

How do i fire validation message on Button click instead of Submit button

I have to execute a authentication process using JQuery. I have two textbox UserName and Password and two button are Login and Submit.
If i am clicking on Submit button then it will automatically fire validation that good and this functionality i have to implement on Login button click.
So how could i achieve automatic validation on button click?
Why i would like this:
Usin JQuery it is sending a request to the server with UserName and
Password during that time i will display Processing....
Then it will verify supplied value with database and return response
with Success or Failed then i will display either Success or Failed.
Here is the code snippet:
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")
#using (Html.BeginForm(null, null, FormMethod.Get, new { id = "Form1", name = "Form1" }))
{
<table>
<tr>
<td>
User Name
</td>
<td>#Html.TextBoxFor(u => u.UserName, new { id = "txtUser" }) #Html.ValidationMessageFor(u => u.UserName)
</td>
</tr>
<tr>
<td>
Password
</td>
<td>#Html.TextBoxFor(u => u.Password, new { id = "txtPassword" }) #Html.ValidationMessageFor(u => u.Password)
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="button" value="Login" onclick="checkAuthentication();" />
<input type="submit" value="Submit" />
</td>
</tr>
<tr>
<td colspan="2">
<div id="dvStatus" class="loginMessageStatus">
</div>
</td>
</tr>
</table>
}
<script language="javascript" type="text/javascript">
function getUserCredentials() {
var user = jQuery('#txtUserName').val();
var pass = jQuery('#txtPassword').val();
return { UserName: user, Password: pass };
}
function clearUserCredentials() {
jQuery('#txtUserName').val("");
jQuery('#txtPassword').val("");
jQuery('#txtUserName').focus();
}
function checkAuthentication() {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
}
function redirectToPage() {
href = '#Url.Action("Index", "TabMaster")';
window.location.href = href;
}
Note:-
Validation completely work with Submit button
Verifying process completely work with Login button ( just i have to integrate validation with Login button)
you can do the validation using the onclick of the submit button with the following event handler:
Add an identifier to the button:
<input id="SubmitButton" type="submit" value="Submit" />
JavaScript:
$(document).ready(function(){
$("#SubmitButton").click(function(){
return checkAuthentication();
});
});
Change the Validation method to return whether it failed or not:
function checkAuthentication() {
var _user = jQuery.trim(jQuery('#txtUserName').val());
var _pass = jQuery.trim(jQuery('#txtPassword').val());
if (_user.length == 0 || _pass.length == 0) {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>User Name and Password are required!</div>")
return false;
}
else {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
return true;
}
}
This should then stop the submit if the validation fails.
I have solved this one:
I have used only submit button
<input id="btnLogin" type="submit" value="Login" />
Following are the updated code
<script language="javascript" type="text/javascript">
$(document).ready(function () {
//$.preloadCssImages();
$("#btnLogin").click(function () {
if ($("#Form1").valid() == true) {
checkAuthentication();
return false;
}
});
});
function getUserCredentials() {
var user = jQuery('#txtUserName').val();
var pass = jQuery('#txtPassword').val();
return { UserName: user, Password: pass };
}
function clearUserCredentials() {
jQuery('#txtUserName').val("");
jQuery('#txtPassword').val("");
jQuery('#txtUserName').focus();
}
function checkAuthentication() {
jQuery('#dvStatus').html("<div class='requestProcess'></div><div class='requestMessage'>Please wait...</div>")
var postData = getUserCredentials();
var ajaxResponse = $.ajax({
type: "post",
url: '#Url.Action("Index", "Login")',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postData),
success: function (result) {
var res = jQuery.parseJSON(result);
if (res.Success == true) {
jQuery('#dvStatus').html("<div class='requestSuccess'></div><div class='requestMessage'>Your are successfully logged in. Redirecting...</div>")
jQuery.doTimeout(100, redirectToPage);
}
else {
jQuery('#dvStatus').html("<div class='requestFailed'></div><div class='requestMessage'>Error: " + res.Message + ". <a href='javascript:void(0)' onclick='clearUserCredentials()'>Try Again</a></div>")
}
}
});
}
function redirectToPage() {
href = '#Url.Action("Index", "TabMaster")';
window.location.href = href;
}
</script>

Resources