Using PhoneGap, I'm trying to build a basic android app that makes an AJAX call to a PHP API and return some JSON data. The code, in its entirety works on the desktop, but it doesn't seem to work for my Android when I make a build. When I build the app, install it on my device, and load it up, I get blank screen.
Here's the client that I wrote... Is there anything wrong with this code?
<head>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jquerymobile/1.4.3/jquery.mobile.min.css" />
</head>
<body>
<script>
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
// Now safe to use the PhoneGap API
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
$.ajax({
url: 'http://api.example.com/test.php',
dataType: 'json',
timeout: 5000,
success: function(data, status) {
//data loaded
$('#results').append(data[0].about);
},
error: function() {
//error loading data
$('#results').append('No data received.');
}
});
$(document).ajaxError(function(event, request, settings) {
$("#msg").append("<li>Error requesting page " + settings.url + "</li>");
});
$(document).ajaxComplete(function(event, request, settings) {
$("#msg").append("<li>Request Complete.</li>");
});
}
</script>
<p id="results"></p>
<p id="msg"></p>
</body>
</html>
I also set the access origins in the config.xml to:
<access origin="http://example.com" subdomains="true" />
<access origin="*"/>
It seems that the AJAX code (and the global AJAX event handlers) is not getting called.
Be sure to have cordova.js included in the right location and available (e.g. by alert(<some cordova property>);). Then try if the onDeviceReady is called at all:
document.addEventListener("deviceready", function(){
alert("deviceready");
},false);
Related
I have this code which works for me but when I try to actually use the form data in PHP I cant get it working. I've tried a number of snippets from stack overflow and the web but nothing seems to work. I did a reduced test case and discovered that I wasn't able to use var_dump($_POST) because I must have some misunderstanding of how fetch works because when I replace the php file with nothing but var_dump($_POST) or even echo("test") I'm not seeing anything.
Can anyone help me get at the data sent to the php file?
checkout.html ( this works fine )
<!DOCTYPE html>
<html>
<head>
<title>Buy cool new product</title>
<link rel="stylesheet" href="style.css">
<script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script>
<script src="https://js.stripe.com/v3/"></script>
</head>
<body>
<section>
<form id = "myForm">
<input type="text" name="">
<input type="submit" name="">
</form>
</section>
</body>
<script type="text/javascript">
// Create an instance of the Stripe object with your publishable API key
var stripe = Stripe("pk_9999999999999999999");
const myForm = document.getElementById('myForm');
myForm.addEventListener("submit", function (e) {
e.preventDefault();
const formData = new FormData(this);
fetch("/create-checkout-session-dump.php", {
method: "POST",
body: formData
})
.then(function (response) {
return response.json();
})
.then(function (session) {
return stripe.redirectToCheckout({ sessionId: session.id });
})
.then(function (result) {
// If redirectToCheckout fails due to a browser or network
// error, you should display the localized error message to your
// customer using error.message.
if (result.error) {
alert(result.error.message);
}
})
.catch(function (error) {
console.error("Error:", error);
});
});
</script>
</html>
creatch-checkout-session-dump.php ( this is just in place of the regular file as a reduced test case - the original file works for what i want it for but i need to be able to see the form contents here somehow but as it is I cant even get it so print "hello world")
<?php
echo('test');
I'm going to answer you again here.
In your PHP file you should ideally use the $_POST super global.
<?php
$data = $_POST['test'];
?>
This 'test' key tag is directly related to whatever you named your input/value in the form. Try this:
<input type="text" name="test" />
<script>
fetch("/create-checkout-session-dump.php",{
type: "POST",
body: formData
})
.then( response => response.ok ? response.json() : "ERROR LOADING" )
.then( data => console.log(data) )
.catch( err => console.error(err) );
</script>
So the issue I'm currently having is that I'm trying to use an ajax call to send information to a php page to create an entry within a SQL database.
If I have the code within the tag. (So it's not within a function and it just calls on page load).
This is what is imported:
<script type="text/javascript" language="javascript" src="js/jquery.js"></script>
<script type="text/javascript" charset="utf-8" src="js/cordova.js"></script>
<link rel="stylesheet" href="jquery.mobile-1.3.0.css" />
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=visualization"></script>
<script type="text/javascript">
var pos = "(44.18974214877667,-79.63154019848633)";
var place = "test";
var check = "on";
var priv = "yes";
$.ajax({ type:"POST",
url:"backMap/locationCreation.php",
data: { name: place, loc: pos, check: check, privacy: priv },
success: function(data) { $("#awesomet").html(data);},
error: function(xhr, textStatus, thrownError, data) {
alert("Error: " + thrownError); }
});
</script>
When this is called upon page load it will run correctly and enter the information into the database. The issue is that I would like this to happen when a button is called so the information could be entered by the user.
<button onClick="sendCreationRequest()" />Submit</button>
<script type="text/javascript">
function sendCreationRequest() {
var place = $("#place").val();
var pos = targetted.getPosition();
var check = $("#checker").val();
var priv = $("#privOp").val();
$("#awesomet").html("GOT HERE.");
$.ajax({ type:"POST",
url:"backMap/locationCreation.php",
data: { name: place, loc: pos, check: check, privacy: priv },
success: function(data) { $("#awesomet").html(data);},
error: function(xhr, textStatus, thrownError, data) {
alert("Error: " + thrownError); }
});
}
</script>
So the Awesomet div will be changed to "GOT HERE." when a button is pressed that should activate the function so it is entering the function. I also had an alert going with all of the variables and they are correct.
When the button is clicked this is what comes up within the console:
CordovaLog - https://maps.gstatic.com/cat_js/intl/en_ca/mapfiles/api-3/13/4/%7Bmain,visualization%7D.js: Line 12 : Uncaught TypeError: Cannot call method 'lat' of undefined
Web Console - Uncaught TypeError: Cannot call method 'lat' of undefined:12.
I looked everywhere for some place that I was calling this but I couldn't find it.
I don't understand why it will work from a on page load call, and why it won't work from a function call.
EDIT: Targetted is a Google Maps Marker. When the call to get position is called. It returns just fine. I have put a alert(pos); within the code so when the button is pressed the alert does come up with the correct string.
EDIT: Okay, so I changed the:
var pos = targetted.getPosition();
to...
var pos = "(44.18974214877667,-79.63154019848633)";
The function call now works perfectly! However I don't understand why. They are getting the same numbers within the variable. Any ideas?
Just to answer my own question.
Thanks to bystwn22 and Mansimran Singh.
It appeared the issue was with the targetted.getPosition();
targetted was a Marker from Google Maps. It's getPosition() function returns something. When printing it out using an alert() it appeared to be the same.
It turns out it wasn't actually a String but some sort of json statement.
The fix turned out to be:
var pos = ""+targetted.getPosition();
Simple but it works.
Thanks everyone for the input!
I have a bash script that connects to a telnet port; opens some diagnostics; exits; and, opens another telnet port.
To check if the script works fine, I can execute it with jQuery and AJAX, but I'm having trouble continually updating the div with the results.
I don't want to keep calling the same command when reloading the php to the div, but just want to refresh the results.
The bash script is pretty basic:
#!/bin/bash
{
sleep 2
echo diag gps info
sleep 2
echo exit
} | telnet 10.10.2.1 1700
telnet 10.10.2.1 1800
HTML/PHP file:
<!DOCTYPE HTML >
<html>
<head>
<meta charset="UTF-8">
<title>diag stuff</title>
</head>
<body>
<button id="startGpsDiag" >Start gps diag</button>
<div id="results"></div>
</body>
<!-- <script langauge="JavaScript" src="{#javaScriptDir#}/jquery-min-1.8.js"> </script> -->
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
jQuery(document).ready(function () {
jQuery.ajaxSetup({cache: false});
jQuery("#startGpsDiag").click(function () {
// alert('true');
callGpsDiag();
});
function callGpsDiag(){
jQuery.ajax({
type: "POST",
url: "gpsDiag.php",
data: "execGpsDiag=1",
success: function(data) {
alert('success');
jQuery('#results').html(data);
setInterval(function() {
jQuery('#results').html(data);
},3000);
},
error: function() {
// alert('fail');
}
});
}
});
</script>
php logic file:
if(isset($_POST['execGpsDiag'])) {
echo system('./gpsdiag.sh');
}
I may want to edit the bash file and remove the last telnet connection it's the one I want to monitor and move it to the php logic with an if we are not initially setting the diagnostics the monitor the port
I have also tried doing echo system(telnet 10.10.1.2 1800)
and tried the setinterval by itself to just load the monitoring port but could not get any results
if I run gpsDiag.php from command line with either just echo system(telnet 10.10.1.2 1800) or echo system('./gpsdiag.sh'); it works and displays results to screen.
You need to set a timeout and call your function inside the timeout callback.
function callGpsDiag(){
jQuery.ajax({
type: "POST",
url: "gpsDiag.php",
data: "execGpsDiag=1",
success: function(data){
alert('success');
jQuery('#results').html(data);
setTimeout(function(){
callGpsDiag();
},3000);
},
error: function() {
//alert('fail');
}
});
}
My question is that how to pass query string variables on same page without refreshing the page in php? My code is given below:
<img src="a.jpg">
<?php
$a = $_GET['id'];
$b = $_GET['pid'];
?>
Please help me to resolve this issue
<html>
<head>
<title>Test</title>
<meta name="" content="">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#image_id").click(function(){
var dataString = 'a=10&b=20';
$.ajax({
type:'POST',
url:'foo.php',
data:dataString,
success:function(data) {
if(data=="Something") {
// Do Something
} else {
// Do Something
}
}
});
});
});
</script>
</head>
<body>
<img id="image_id" src="images/bg.jpg" />
</body>
</html>
Then in the 'foo.php' page do this
if(isset($_POST['a'])) {
// DO SOMETHING
}
Remember the things that you want to send to the 'data' of
success:function(data)
must be echoed out in the foo.php page
You can't.
PHP requires execution on the server and so you'd have to either use AJAX and update your page accordingly, or just refresh your page.
You can by sending an AJAX request to the server. Ajax is a way to send asynchronous request via Javascript. Notice that jQuery has a good library about it.
Use jquery to resolve this. By using the $.ajax in jquery you can do the stuff you need without page refresh.
I feel like this is something that I should have learned by now, and I'm sure it's something small I'm missing, but I could use clarification to make sure my approach is correct.
I'm using AJAX to post data to self which is a file that contains php and html. I can write the php fine, but after a successful ajax post, how do I only return the data that is processed via php and not the remaining html? Is it better to just post to a separate script?
If you have the PHP handling the POST request in the beginning of the file, you can just do something like this:
<?php
if (isset($_POST['somevar'])) {
/* do something */
exit(0);
}
?>
exit() will stop the loading of the page at that line.
I, for one, think it's better to be utilizing a separate script to deal with dynamic AJAX requests.
You can scrape changed parts of the resulting document and insert them into the original page. This way you can also make your page work for a user with JavaScript disabled not doing anything specially.
Example:
<html><title>Unobtrusive AJAX Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script><script type="text/javascript">
$("form.ajax[id]").live('submit', function() {
$(this).find("input[type='submit']").attr("disabled", true);
$.ajax({
type: $(this).attr('method') || 'POST',
url: $(this).attr('action') || window.location.pathname,
data: $(this).serialize(),
context: $(this),
success: function(data) {
$(this).html(
$(data).find("#" + $(this).attr("id")).html()
);
}
});
return false;
});
</script>
</head><body>
<div><form method="post" class="ajax" id="main">
<p><?php echo date('H:i:s'); ?></p>
<p><input type="submit"></p>
</form></div>
<!-- keep the div: you got to have at least one div to make it work -->
</body></html>
It always depends on what are your needs, but if using the same script is enough for you then do it.
If you want the script not to send anything more than your answer to an XML HTTP Request, after sending the data, use an exit(); in PHP, which will make the script finish at that point.
Put to the of the script:
if($_POST['id']) {
$data = array('return'=>'returnValue');
$data = json_encode($data);
exit($data); }
Javascript:
$.ajax({
url: 'frmSelf.php',
data: $("#frmSelf").serialize(),
dataType: 'json',
type : 'post',
success : function(returnData) {
console.log(returnData);
}
});