I'm trying to send an ASP.NET AJAX request to my application. In the application's controller, I have:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "ID,Name,Instructions,Glass,Notes")] Drink drink,
[Bind(Include= "ID,Amount,Brand,IngredientID,DrinkID")] IEnumerable<DrinkIngredient> DrinkIngredients)
{
if (ModelState.IsValid)
{
//and so on
my javascript looks like this:
console.log($('#editDrinkForm').serialize())
var x = new XMLHttpRequest();
x = $.post(window.location,
{
data: $('#editDrinkForm').serialize()
})
.done(function () {
console.log("done");
})
.fail(function () {
console.log(x.responseText);
})
and yet, I'm seeing this output:
You'll notice that __RequestVerificationToken is the first value! So what gives?
everything else
output transcription (from a later run)
"__RequestVerificationToken=ZxW-JtClcOb-vYXDarYGYAEXtY84LzeiigiOKRhg4-sLSd1ixS4rwPtU-prisQ_D_vmoOYKP6cZ38ZTn5lhyg8Sh7V_F2VOgve6FkGNDOWcJy8JL8tEwPS7gy8uPd6Xl1_K8VdmWh6UGJBp372w8_w2&ID=1&Name=7%267&DrinkIngredients.index=3&DrinkIngredients%5B3%5D.ID=3&DrinkIngredients%5B3%5D.DrinkID=1&DrinkIngredients%5B3%5D.DrinkIngredientID=3&DrinkIngredients%5B3%5D.Brand=Seagram's+7+crown&DrinkIngredients%5B3%5D.ingredientID=2&DrinkIngredients%5B3%5D.Amount=1+part&DeleteDrinkIngredients.index=3&DrinkIngredients.index=4&DrinkIngredients%5B4%5D.ID=4&DrinkIngredients%5B4%5D.DrinkID=1&DrinkIngredients%5B4%5D.DrinkIngredientID=4&DrinkIngredients%5B4%5D.Brand=7-up&DrinkIngredients%5B4%5D.ingredientID=1&DrinkIngredients%5B4%5D.Amount=4+parts&DeleteDrinkIngredients.index=4&Instructions=combine%2C+stir&Glass=&Notes=fff"
(and)
"<!DOCTYPE html>
<html>
<head>
<title>The required anti-forgery form field "__RequestVerificationToken" is not present.</title>
<meta name="viewport" content="width=device-width" />
<style>
body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}
p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
.marker {font-weight: bold; color: black;text-decoration: none;}
.version {color: gray;}
.error {margin-bottom: 10px;}
.expandable { text-decoration:underline; font-weight:bold; color:"[…]
x = $.post(window.location, {data: $('#editDrinkForm').serialize()})
is wrong. Do this:
x = $.post(window.location, data: $('#editDrinkForm').serialize())
(some credit to stephen's comment)
Related
I want to create an automatic chat system with Botman, but I have a problem. I do not receive a response when I send a message, and i get this message in console, "chat.js:1 POST http://127.0.0.1:8000/botman 404 (Not Found) (anonymous) # chat.js:1 t.exports # chat.js:1 t.exports # chat.js:1 Promise.then (async) r.request # chat.js:1 r. # chat.js:1 (anonymous) # chat.js:1 callAPI # chat.js:1 e.say # chat.js:1 r.handleKeyPress # chat.js:1 m # chat.js:1 chat.js:1 Uncaught (in promise) Error: Request failed with status code 404 at t.exports (chat.js:1:13996) at t.exports (chat.js:1:17470) at d. (chat.js:1:12823)" So here is my code
//route :
Route::get('/show_my_chat_form', 'BotManController#index')->name('chatform');
Route::get('/botman', 'BotManController#handle');
Route::post('/botman', 'BotManController#handle');
//here is my Controller
use BotMan\BotMan\BotMan;
use Illuminate\Http\Request;
use BotMan\BotMan\Messages\Incoming\Answer;
class BotManController extends Controller
{
public function index()
{
return view('chatform');
}
public function handle($language)
{
$botman=app("botman");
$botman->hears("{message}", function($botman,$message)
{
if ($message == "Hello")
{
$this->askName($botman);
}
else
{
$botman->reply("Please write hi to start conversation! ");
}
});
$botman->listen();
}
public function askName($language,$botman)
{
$botman->ask("what's your name? ", function(Answer $answer)
{
$name=$answer->getText();
$this->says("nice to met you M.-Mm ".$name);
});
//the config.php and web.php located in /config/botman/..
//config.php
<?php
return [
'conversation_cache_time' => 40,
'user_cache_time' => 30,
];
//web.php
<?php
return [
'matchingData' => [
'driver' => 'web',
],
];
//view
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Form</title>
<link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/botman-web-widget#0/build/assets/css/chat.min.css">
<style>
html,
body {
background-color: #fff;
color: #636b6f;
font-family: 'Nunito', sans-serif;
font-weight: 200;
height: 100vh;
margin: 0;
}
</style>
</head>
<body>
</body>
<script>
var botmanWidget = {
aboutText: 'write',
introMessage: "✋hi",
//frameEndpoint: ''
};
</script>
<script src='https://cdn.jsdelivr.net/npm/botman-web-widget#0/build/js/widget.js'></script>
</html>
I'm trying to load a local file to MapBox getting error messages:
ERROR parsererror No conversion from text to geojson from ajax function and
Error {message: "Input data is not a valid GeoJSON object."} for evented.js
Features are structured are like this:
{ "type": "Feature", "properties": { "score": 0.77, "pokemon": "Squirtle", "color": "#42b9f5" }, "geometry": { "type": "Point", "coordinates": [ 2.768403197476528, 39.806888683241638 ] } }
I'm creating geoJSON file with Python, http://geojson.io load it just fine without any errors I suppose is something about my Ajax request.
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title></title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v1.11.1/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v1.11.1/mapbox-gl.css' rel='stylesheet' />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
</style>
</head>
<body>
<div id='map'></div>
<script>
mapboxgl.accessToken = 'MY_TOKEN';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11'
});
map.on('style.load', function() {
map.addSource("pokemons", {
type: "geojson",
data:
$.ajax({
type: "GET",
file: "../data_wrangling/points.geojson",
dataType: "geojson",
success: function(data) {
return data;
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('ERROR', textStatus, errorThrown);
}
})
})
})
</script>
You're passing an ajax object to as your data which is not supported. Try to fetch the data first before passing it in .addSource. This demo may be helpful.
Alternatively, since your geojson is stored at an URL, you can pass that url instead of the ajax object/promise.
I want to get my current location using Google Maps Geolocation by Latitude and Longitude and I also want to set the origin as my current location but I'm not getting the current location. What should I do?
This is my code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Draggable directions</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>
var rendererOptions = {
draggable: true
};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
var lat, lon, mapOptions;
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(
function(position){
lat = position.coords.latitude;
lon = position.coords.longitude;
mapOptions = {
zoom: 7,
center: new google.maps.LatLng(lat, lon),
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directionsPanel'));
google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
computeTotalDistance(directionsDisplay.getDirections());
});
calcRoute();
},
function(error){
alert('ouch');
});
}
else {
alert("Your browser doesn't support geolocations, please consider downloading Google Chrome");
}
}
function calcRoute() {
var request = {
origin: new google.maps.LatLng(lat, lon),
destination: new google.maps.LatLng(10.5200,76.2100),
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function computeTotalDistance(result) {
var total = 0;
var myroute = result.routes[0];
for (var i = 0; i < myroute.legs.length; i++) {
total += myroute.legs[i].distance.value;
}
total = total / 1000.0;
document.getElementById('total').innerHTML = total + ' km';
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas" style="float:left;width:70%; height:100%"></div>
<div id="directionsPanel" style="float:right;width:30%;height 100%">
<p>Total Distance: <span id="total"></span></p>
</div>
</body>
</html>
I am building an application in which i am using the famous fullCalendar. Now i need to populate my calendar using the values that are present in my database. I am trying to do it using an AJAX call. But its not working . Any help would be appreciated.
This is my jsp . The one which im using to display my calendar.
<!DOCTYPE html>
<html>
<head>
<link href='css/fullcalendar.css' rel='stylesheet' />
<link href='css/fullcalendar.print.css' rel='stylesheet' media='print' />
<script src='js/jquery.min.js'></script>
<script src='js/jquery-ui.custom.min.js'></script>
<script src='js/fullcalendar.min.js'></script>
<link href="jquery-ui-1.10.0.custom.css" rel="stylesheet" type="text/css" media = "all"/>
<link rel='stylesheet' type='text/css' href='cssdata/fullcalendar.css' />
<script src="js/jquery-1.9.0.js"></script>
<script src="js/jquery-ui-1.10.0.custom.min.js"></script>
<script type='text/javascript' src='js/fullcalendar.js'></script>
<pre>
<script>
$(document).ready(function() {
getEvents();
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
editable: true,
events: [ getEvents()
/* {
title: 'All Day Event',
start: new Date(y, m, 1)
}, */
]
});
});
function getEvents(){
alert("hi");
$.post("http://localhost:8080/S360Portal/eventAjax.action", {},
function(data){
alert("Hello");
alert(data);
});
}
</script>
<style>
body {
margin-top: 40px;
text-align: center;
font-size: 14px;
font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;
}
#calendar {
width: 900px;
margin: 0 auto;
}
</style>
</head>
<body>
<div id='calendar'></div>
</body>
</html>
Try using eventSources instead of events, this considering your function is in fact returning any events. Why not use $.Ajax({}) instead of $.post? It will make your life easier.
Here's an example of how i do it:
EventSources array.
var sources = {
sourceone: {
url: ajaxcallURL(),
type: 'POST',
data: { 'year': y },
cache: false, //this is optional
color: '#6C92A8', //this is optional
textColor: 'white' //this is optional
}
}
In Fullcalendar call I have this:
var calendar = $('#calendar').fullCalendar({
...
eventSources: [sources.sourceone],
...
});
This works for me, notice that I'm returning JSON so if you are returning XML for example you will have to iterate the XML.
Also if your events returns Dates different from the accepted they wont be mapped in the calendar, ( yyyy-mm-dd ) works.
Good Luck
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>ajax div example</title>
<script type="text/javascript" src="jscripts/jquery-1.6.4.min.js"></script>
<script type="text/javascript">
var dbn,machine_name;
function main_draw(d,m,r)
{
dbn = d;
machine_name = m;
draw_charts();
if ( r > 0 )
{
setRefreshid = setInterval("draw_pie()",r);
}
}
function draw_charts()
{
document.getElementById('ajdiv4').innerHTML = "";
document.getElementById('ajdiv3').innerHTML = "";
document.getElementById('ajdiv2').innerHTML = "";
document.getElementById('ajdiv1').innerHTML = "";
draw_pie();
draw_line();
draw_space();
draw_backup();
}
function draw_pie()
{
setTimeout(function() {
$.ajax( {
url: 'JSCharts/graph_pie1.html',
success: function(html)
{
$("#ajdiv4").html(html);
}
}); }, 100);
}
function draw_line()
{
setTimeout(function() {
$.ajax( {
url: 'JSCharts/graph_line1.html',
success: function(html)
{
$("#ajdiv3").html(html);
}
}); }, 200);
}
function draw_space()
{
setTimeout(function() {
$.ajax( {
url: 'JSCharts/space_graph.php',
success: function(html)
{
$("#ajdiv2").html(html);
}
}); }, 300);
}
function draw_backup()
{
setTimeout(function() {
$.ajax( {
url: 'JSCharts/backup_graph.php',
success: function(html)
{
$("#ajdiv1").html(html);
}
}); }, 400);
}
</script>
</head>
<body>
<div id="ajdiv1" style="float:left"></div>
<div id="ajdiv2" style="float:left"></div>
<div id="ajdiv3" style="float:left"></div>
<div id="ajdiv4" style="float:left"></div>
<button id="b1" onclick="main_draw('CQ1','va2apsap010',10000)">Display Content</button>
</body>
</html>
Above is an entire code which makes AJAX calls upon clicking on "Display Content" and after that it refreshes content of div "ajdiv4" by calling function "draw_pie". The only problem with this is that when it refreshes, it moves the pie graph all the way to the left. I would like it to stay and update it in the current position. Please help if any of you know what is going on here, Thanks.
Have you tried specifying the dimensions of your DIVs? With your current code, you could probably do:
<style>
#ajdiv1, #ajdiv2, #ajdiv3, #ajdiv4 {
height:200px;
width:200px;
}
</style>
Alternatively, add a class attribute to simplify things:
<style>
.chartContainer {
height:200px;
width:200px;
}
</style>
If you have a working version up, or can post something on JSfiddle, that would make things easier to troubleshoot.