So I'm trying to pass some data from my front-end to the back-end. It is the user's nickname and the location of the user. But while I can read and print out the nickname in flask, I always get None when I want to read the location value in the backend. I'm not really sure why this is happening, since I can actually print the location value in the javascript console before passing it to the backend and everything is allright. I would really appreaciate any help :)
This is my relevant code:
JS
$(document).on("submit", "#get_nickname", function(e)
{
var coords = {};
//Get location
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(loc){
var latlng = loc.coords.latitude + "," + loc.coords.longitude;
String(latlng);
latlngContainer = latlng;
coords.latlng = latlngContainer;
});
}
console.log(coords);
e.preventDefault();
$.ajax({
type: "POST",
url: "/add_address",
data: {
nickname:$("#nickname").val(),
location: coords
},
success: function()
{
set_address_cookie(31);
session_memory();
add_address_toggle();
}
})
});
PYTHON
#app.route("/add_address", methods=['POST'])
def add_address():
nickname = request.form.get("nickname")
location = request.form.get("location")
print(f"Hi {nickname}, you are here {location}")
return "", 201
Here are some pictures:
my chrome console log with everything allright
the error shown on flask
Location is being dropped because it's an object. Try to send the data as json however you will have to modify your flask app to accept it.
$.ajax({
type: "POST",
url: "/add_address",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
nickname:$("#nickname").val(),
location: coords
}),
success: function()
{
set_address_cookie(31);
session_memory();
add_address_toggle();
}
});
EDITS:
I just noticed geolocation.getCurrentPosition callback is asynchronous meaning it executes later when the ajax already happened. You have to wait for it to finish executing before posting. I am not sure what environment you're working from but I re-wrote your JS try it and see if it works for you.
$(document).on("submit", "#get_nickname", function(e)
{
e.preventDefault();
function addAddress(data){
$.ajax({
type: "POST",
url: "/add_address",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
success: function()
{
set_address_cookie(31);
session_memory();
add_address_toggle();
}
});
}
var data = { nickname: $("#nickname").val() }
var coords = {};
//Get location
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function(loc){
var latlng = loc.coords.latitude + "," + loc.coords.longitude;
String(latlng);
latlngContainer = latlng;
coords.latlng = latlngContainer;
data.coords = coords;
addAddress(data); //submit with coords
}, function(){
addAddress(data); //submit without coords when failed to get coords
});
} else addAddress(data); //submit without coords when not supported
});
Related
I have an HTML page that populates data using PHP - testcommand.php.
On a button press the page should update a record in MySQL- updmeal_order.php, and then call a new webpage - add-meals.php.
This works in chrome and explorer but in firefox, it does not. In firefox the button fires and calls the new webpage but does not do the update.
If I remove the calling of the new webpage, the update does work.
Thanks in advance
Osie
$(document).ready(function () {
var xparam = getUrlParameter('ref');
$("body").delegate("#addmeals", "click", function(event){
// update table in mysql
event.preventDefault();
var mo_desc = document.getElementById('mo_desc').value;
var bh_no = document.getElementById('bh_no').value;
var updparam = bh_no+mo_desc;
//alert (xparam);
var url = "../js/updmeal_order.php";
// var dataString = $(this).serialize().replace(/\'/g,'\\\'');
// POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
data: ({xparam: updparam}),
success: function (data)
{
//var myJSON = JSON.stringify(data);
//alert (myJSON);
}
});
// call a new webpage
var path = '../command/add-meals.php?ref='+bh_no;
window.location.href=path;
$.ajax({
url: path,
type: "POST",
// data: ({mo_desc: mo_desc}),
success: function()
{
// var arraydata = $.parseJSON(data);
// $("#command").html(arraydata[0]);
}
});
/*
*/
});
// display data in main htm page
$.ajax({
url: '../command/testcommand.php',
type: "POST",
data: ({xparam: xparam}),
success: function(data){
var arraydata = $.parseJSON(data);
$("#command").html(arraydata[0]);
}
});
});
The problem I had was that pressing the back button(from add-meals.php) on firefox seems to rollback the mysql update, whereas on chrome/explorer it is commited... bizarre?
Calling the page first and then the update seems to have solved this
I have created a WebView for macOS app and it contains one AJAX call. The same WebView is working fine when the app calls my local URL, but when it calls the live URL, the AJAX call is not working.
$(document).ready(function () {
$('#pripolcheck').click(function () {
var pripolcheck = $('#pripolcheck').val();
var app = $('#app').val();
var user_id = $('#user_id').val();
var contact = $('#contact').val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'pripolcheck1=' + pripolcheck + '&app1=' + app + '&user_id1=' + user_id;
if (pripolcheck == '') {
alert('Please Fill All Fields');
} else {
// AJAX Code To Submit Form.
$.ajax({
type: 'POST',
url: 'http://mywebsite.com/ajaxformsubmit.php',
data: dataString,
cache: false,
success: function (result) {
// alert(result);
// $(".pripol").hide();
$('.pripolcheck').prop('checked', true);
$('input.pripolcheck').attr('disabled', true);
}
});
}
return false;
});
});
My local PHP version is 7.1.8 and my live server PHP version is 5.4.
Change your function to onclick of checkbox directly,put this code in your checkbox onclick="MyFuncion",why I'm telling this is for web view we need to give exact command in exact position it's not a browser
And your AJAX call will be like below,
function myFunction()
{
var pripolcheck = $("#pripolcheck").val();
var app = $("#app").val();
var user_id = $("#user_id").val();
var contact = $("#contact").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'pripolcheck1='+ pripolcheck + '&app1='+ app + '&user_id1='+ user_id;
if(pripolcheck=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "ajaxformsubmit.php",
data: dataString,
cache: false,
success: function(result){
// alert(result);
// $(".pripol").hide();
$('.pripolcheck').prop('checked', true);
$("input.pripolcheck").attr("disabled", true);
}
});
}
return false;
}
"My local PHP version is 7.1.8 and my live server PHP version is 5.4."
I think this explains everything.
However, try setting an absolute URL in your call:
url: 'ajaxformsubmit.php',
to
url: '/ajaxformsubmit.php',
Or whatever the actual path would be. Just a single slash will give you
http://wherever.com/ajaxformsubmit.php
if u use same site url plz use relative path not absolute path then its ok.
if use defrant site url plz comment me so give me new solution
PLZ try
$(document).ready(function () {
$('#pripolcheck').click(function () {
var pripolcheck = $('#pripolcheck').val();
var app = $('#app').val();
var user_id = $('#user_id').val();
var contact = $('#contact').val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'pripolcheck1=' + pripolcheck + '&app1=' + app + '&user_id1=' + user_id;
if (pripolcheck == '') {
alert('Please Fill All Fields');
} else {
// AJAX Code To Submit Form.
$.ajax({
type: 'POST',
url: '/ajaxformsubmit.php',
data: dataString,
cache: false,
success: function (result) {
// alert(result);
// $(".pripol").hide();
$('.pripolcheck').prop('checked', true);
$('input.pripolcheck').attr('disabled', true);
}
});
}
return false;
});
});
I am building a chatroom-type app using the Parse Javascript API. The task is to get some data from Parse, display it, add user input to the messages, and send it right back to parse.
The problem is I am not being able to see the data from parse, and receive a 502 error. I am a bit newer to javascript, so any advice on how to accomplish this, or any mistakes you may see in my code, would be fantastic. I also commented out my code the best I could. Thanks for the help.
Here is my code;
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages')
//fetches data from parse
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success: console.log("Success"),
function message(a) {
my_messages.append('<ul>' + a +'</ul>'); //adds ul 'text' to messages
};
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
function(message){
window.location.reload(1) //refresh every 3 seconds
});
});
});
</script>
you have syntax error in both of your success functions of $.ajax calls. In the first ajax call you have places console.log, which should be inside the success callback. In the second one u haven't even added success: callback.
Try below updated code
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages');
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success:function message(a) {
console.log("Success")
$.each(a,function(i,item){
my_messages.append('<ul>' + item.username +'</ul>'); //adds ul 'text' to messages
});
}
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
success:function(message){
window.location.reload(1) //refresh every 3 seconds
}
});
});
});
I am loading map data from a GeoJSON file and attaching a click event for every polygone. on click, the script should fetch data from the server AND modify one of the clicked polygon's properties. i.e:
function onClick(e) {
var status = e.target.feature.properties.ACCESS;
$.ajax({
url: "http://127.0.0.1:8080/?&u=x&p="+e.target.feature.properties.ID_PARCELL,
dataType: 'jsonp',
type: 'GET',
success: function(data) {
status = data.status;
e.target.feature.properties.ACCESS = data.status;
e.target.bindPopup("Owner: <b>"+ data.status +"</b>").openPopup();
},
error: function(data){console.log(data)}
});
e.target.feature.properties.ACCESS = status;
map.fitBounds(e.target.getBounds());
}
But since the success function is an callback (synchronous or not, it doesn't really matter), I am not able to get back to the original event source (namely e) so I could modify one of its properties.
My question is: How can I get back to the event source after loading this data? Is there any generic Javascript way? If not, is there any way I can query the GeoJSON layer by feature ID ? (=> I can therefore send the feature ID in the ajax call, and simply get it back with the response)
The solution is to send the desired variable e to the anonymous function by using the context entry:
function onClick(e) {
var status = e.target.feature.properties.ACCESS;
$.ajax({
url: "http://127.0.0.1:8080/?&u=x&p="+e.target.feature.properties.ID_PARCELL,
dataType: 'jsonp',
context: e,
type: 'GET',
success: function(data) {
status = data.status;
e.target.feature.properties.ACCESS = data.status;
e.target.bindPopup("Owner: <b>"+ data.status +"</b>").openPopup();
},
error: function(data){console.log(data)}
});
e.target.feature.properties.ACCESS = status;
map.fitBounds(e.target.getBounds());
}
You'r using the same event name 'e' on both Click and success functions. Try to change one of them. ie
function onClick(e) {
var status = e.target.feature.properties.ACCESS;
$.ajax({
url: "http://127.0.0.1:8080/?&u=x&p="+e.target.feature.properties.ID_PARCELL,
dataType: 'jsonp',
type: 'GET',
success: function(data, evt) {
status = data.status;
e.target.feature.properties.ACCESS = data.status;
e.target.bindPopup("Owner: <b>"+ data.status +"</b>").openPopup();
},
error: function(data){console.log(data)}
});
e.target.feature.properties.ACCESS = status;
map.fitBounds(e.target.getBounds());
}
now you can change the initial event 'e' properties when the result is returned.
Hope this helps.
I Have to do a cross-domain request and fetch content from a url using $.ajax function.
But the below code only displays the first alert i.e alert(myUrl),
After that the execution stops.The second alert is not displayed. I don't know what is wrong with the code i have written.
Can somebody tell me what i am doing wrong here?Thanks in advance.
function getContentFromUrl(){
var myUrl="http://icant.co.uk";
alert(myUrl);
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?" +
"q=select%20*%20from%20html%20where%20url%3D%22" +
encodeURIComponent(myUrl) + "%22&format=xml'&callback=?",
dataType: 'json',
data: data,
success: function () {
alert("***********"+data.results[0]);
if (data.results[0]) {
var htmlText = data.results[0];
var jsonObject = parseAndConvertToJsonObj(htmlText);
} else {
document.getElementById("displayerrors").innerHTML = "Could not load the page.";
}
},
error: function() {
document.getElementById("displayerrors").innerHTML = "Could not load the page.";
}
});
}
Same Origin Policy:
The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites.
You can't use regular JSON for cross-domain requests because of the same-origin policy. Instead, you'll need to use JSONP. In jQuery, you can do so like this:
$.ajax({
dataType: 'jsonp',
crossDomain: true
// other info
});
Note that there are security issues involved with JSONP. Only use JSONP if you trust the host domain.
I assume this is jQuery?
Try the following:
url = "http://query.yahooapis.com/v1/public/yql?" +"q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(myUrl) + "%22&format=xml'&callback=?";
getContentFromURL(url);
function getContentFromURL(url)
{
$.get(url, function (data) {
console.log(data);
});
}
If it dumps out to the console a response, you can build from there.
The data here is not defined
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?" + "q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(myUrl) + "%22&format=xml'&callback=?",
dataType: 'json',
data: data,
and you forget to add a param for the callback function
success: function (data) {
....
}
The finally code should like this
function getContentFromUrl() {
var myUrl = "http://icant.co.uk";
alert(myUrl);
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?" + "q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(myUrl) + "%22&format=xml'&callback=?",
dataType: 'json',
data: {},
success: function (data) {
alert("***********" + data.results[0]);
if (data.results[0]) {
var htmlText = data.results[0];
var jsonObject = parseAndConvertToJsonObj(htmlText);
} else {
document.getElementById("displayerrors").innerHTML = "Could not load the page.";
}
},
error: function () { document.getElementById("displayerrors").innerHTML = "Could not load the page."; }
});
}