AJAX is not working in macOS WebView - javascript

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;
});
});

Related

Flask can read a POST datum but not another

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
});

Display openweathermap (API) data on website using AJAX and PHP

when i want enter a city here, nothing happens, no error in my console, i don't know why
this is my code :
ajax.js
$(document).ready(function(){
$('#submitLocation').click(function(){
//get value from input field
var city = $("#city").val();
$.post('PHP/controller.php', {variable: city});
//check not empty
if (city != ''){
$.ajax({
url: "PHP/router.php",
// url :"http://api.openweathermap.org/data/2.5/weather?q=" + city +"&lang=fr"+"&units=metric" + "&APPID=697edce53ba912538458a39d776ca24e",
type: "GET",
dataType: "jsonp",
success: function(data){
console.log(data);
console.log(data.weather[0].description);
console.log(data.main);
console.log(data.main.temp);
var information = show(data);
$("#show").html(information);
}
});
}else{
$('#error').html('Field cannot be empty');
}
});
})
function show(data){
return "<h3>Témpérature: "+ data.main.temp +"°C"+"</h3>" + "<h3>"+ data.weather[0].description +"</h3>";
}
this is my router.php, my js call the router
<?php
require('../PHP/controller.php');
if (isset($_GET['city'])) {
return getWeatherCity($_GET['city']);
}
else {
echo'Error';
}
?>
i know that i can do this only with js or only with php but i want use both of them.
Do you have any request happening in the "Requests" tab of your DevTool?
You should see a request towards PHP/router.php and the associated status code. Given that you might collect clues to debug what's going on.

Update in first php call not working in firefox.. but works in chrome and explorer

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

Codeigniter & Ajax - Condition statement in javascript

Im quiet confused with this code. Im reading this code of ajax which inserts the data automatically. but what im confused is this line if(result=='12') then trigger ajax what does 12 means why it should be 12 then conditioned to before ajax. Apparently im still learning ajax thanks. P.S this is working well btw im just confused with the code
here is the full code of the create function javascript / ajax
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var result = '';
if(empoyeeName.val()==''){
empoyeeName.parent().parent().addClass('has-error');
}else{
empoyeeName.parent().parent().removeClass('has-error');
result +='1'; //ALSO THIS NUMBER 1 WHY SHOULD IT BE 1?
}
if(address.val()==''){
address.parent().parent().addClass('has-error');
}else{
address.parent().parent().removeClass('has-error');
result +='2'; //ALSO THIS NUMBER 2 WHY SHOULD IT BE 2?
}
if(result=='12'){ //HERE IS WHAT IM CONFUSED
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type ="updated"
}
$('.alert-success').html('Employee '+type+' successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
}
});
As I have explained in my commentaries, and since you wanted an example. This is how I will proceed in order to avoid checking for result == '12':
$('#btnSave').click(function()
{
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
// Validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var formValid = true;
if (empoyeeName.val() == '')
{
empoyeeName.parent().parent().addClass('has-error');
formValid = false;
}
else
{
empoyeeName.parent().parent().removeClass('has-error');
}
if (address.val() == '')
{
address.parent().parent().addClass('has-error');
formValid = false;
}
else
{
address.parent().parent().removeClass('has-error');
}
// If form is not valid, return here.
if (!formValid)
return;
// Otherwise, do the ajax call...
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response)
{
if (response.success)
{
$('#myModal').modal('hide');
$('#myForm')[0].reset();
var type = '';
if (response.type=='add')
type = 'added';
else if (response.type=='update')
type ="updated";
$('.alert-success').html('Employee ' + type + 'successfully')
.fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}
else
{
alert('Error');
}
},
error: function()
{
alert('Could not add data');
}
});
});
It's just checking existence of values and appending string to it.
if(empoyeeName.val()=='')
This check empty name and add error if name is empty. else it concat 1 to result.
if(address.val()=='')
This check empty address and add error if address is empty. else it concat 2 to result.
So if both of them are non empty that means result will be 12 and than only you make ajax call else show error.

json login session error

i used a json login data file to login with php. i used javascript to search any user in the json data file and show me page or redirect to login page.
$(document).ready(function () {
$('#login').click(function () {
var email = $('#email').val();
var pass = $('#pass').val();
var error = true;
$.ajax({
type: "POST",
url: "login.json",
dataType: "json",
success: function (data) {
$.each(data, function (key, value) {
if (email == value.email && pass == value.pass) {
error = false;
}
});
if (error == false) {
document.location = "index.php?email=" + email;
} else {
$('#email').val('');
$('#pass').val('');
alert('please check your email or password!');
}
}
});
return false;
});
});
this works fine. but i used to login with my url and it also access any email to my index.php file. how to make to this correct.
i type like this on url and it also shows me index file.
http://json.test/index.php?email=test123#gmail.com
i want to restrict this method and only login with json file data. can anyone know how to make php session with this JavaScript code.

Categories