Calling PHP script with Cordova - javascript

I'm working on an app that's supposed to contain the same information as an already existing website.
What I wanted to do was create a Cordova app that calls an external PHP script which in turn gets information from the database that the website is using.
Right now I'm working on calling the PHP script but it just doesn't seem to work.
Here is the script I'm trying to call:
<?php
$a = 1;
$b = json_encode($a);
return $b;
?>
Ofcourse this is just to test the connection. The URL for this file is http://localhost:8888/get_posts.php
Here is the code for the app:
$('#page1').bind('pageshow', function () {
$.get('localhost:8888/get_posts.php', function (data) {
$(this).find('.homeText').html(data);
});
});
This fetches the file whenever the page is shown (handy) and then puts the new data into the page. The problem is that the page remains empty at all times, when it should be showing a "1". Can anyone see where it goes wrong?
Error message: XMLHttpRequest cannot load localhost:8888/get_posts.php. Cross origin requests are only supported for HTTP.
UPDATE: The error message dissapeared when adding http:// to the url, but the problem persists.
I've changed the code to:
$('#page1').bind('pageshow', function () {
$.get('localhost:8888/get_posts.php', function (data) {
alert(data);
});
});
and it shows me an empty alert box.
Solution: Had to use echo instead of return for the script to show me a result.
http:// was also required so the script is allowed to communicate.

You have to 'echo' your response not returning it like so
<?php
$a = 1;
$b = json_encode($a);
echo $b;
?>

Related

PHP method calls from Javascript not showing up in Wordpress source

I am running a Wordpress website, and trying to call PHP methods from my Javascript code.
When a button is tapped, the saverFoo() Javascript method is called, and attempts to call the PHP method save_image_data().
function saverFoo() {
var dataURL = canvas.toDataURL();
<?php echo save_image_data(dataURL); ?>;
}
function loaderFoo() {
var loadedImage = <?php echo loadimagedata(); ?>;
console.log(loadedImage);
}
The PHP method's implementation is in the function.php file, and is simply attempting to save some image data (dataURL) in the user's meta
function save_image_data($imageData) {
global $current_user;
update_user_meta( $current_user->ID, 'user_design', $_POST['$imageData']);
}
function loadimagedata() {
global $current_user;
$old_notes = get_user_meta($current_user->ID, 'user_design', true);
return $old_notes;
}
Inspecting my web-page in Chrome, shows me an empty space where loaderFoo () (javascript) is supposed to be calling loadimagedata() (php) , and loadedImage is an undefined variable, when I try to log it, such as:
function loaderFoo() {
var loadedImage = ;
console.log(loadedImage);
}
Not sure what fundamental mistake I'm making here.
Always remember that PHP runs on the server side, and javascript on the client side. So we have an order here, the server receives the request PHP processes what it should process and render the page, only here Javascript will be executed.
In this example, when the 'saverFoo()' function is executed, this function <? Php echo save_image_data (dataURL); ?>; has already been written on the page. PHP will not be able to get the information contained in the dataURL variable, not on this way. To do this, we must make a request to the server with this desired information, but with an "image" is not trivial to do this, as there is a limit on the size of the post when using a normal String field.
function saverFoo () {
    var dataURL = canvas.toDataURL ();
    <? php echo save_image_data (dataURL); ?>;
}
PHP doesn't work that way. It is a pre-processor. It is all run and done server side and the resulting text/html/binary data/whatever is sent out to the client. In the case of a content type of text/html the browser will load it, parse it, render it, and run whatever javascript is called.
How you can mix PHP and JavaScript in-line like that would be to use PHP to fill in variables. For example
alert("<?php print($_SERVER['SCRIPT_FILENAME']); ?>");
would work because the client would see
alert("/path/to/foo.php");
and render that for the user.
To really interact with PHP using JavaScript, you'll want to look into using a http based REST type service and perhaps one of the various popular tool sets like Angular, Vue, etc.

AJAX and 500 Internal Server Error

I'm building a web application in CodeIgniter and I'm using jQuery and AJAX. I created the whole app locally (using XAMPP) and everything worked fine. After I uploaded the app to my web hosting, one AJAX keeps failing. Here is the part of the code:
// Get all form inputs
var inputs = $('#app-options-existing-form :input[type="text"]');
// Put them in object as name=>value
var data = {};
for(i=0; i<inputs.length; i++) {
data[inputs[i]["name"]] = inputs[i]["value"];
}
// Put loader while AJAX is working
$(".app-content-container").html('<center><img class="loader" src="<?php echo base_url();?>/img/loader.gif" ></center>');
console.log(data);
// Generate POST request
$.post("<?php echo site_url("admin/ajax_app_options"); ?>",
{"add_existing_form_submited" : true, "data" : data2},
function (data) {
alert("test" + data);
});
Here's the console showing error and result of console.log(data)
First, I thought that the key ("d1d1d1") was the problem because I was first using "1-1-1" and after I manually changed it, it was working. But then I changed everything in "d1d1d1" and it doesn't work again. As I said, it works on XAMPP but not on server. Can be a problem in using full URL for AJAX, instead of relative one? But I'm using it in other AJAX requests as well and it works.
Pretty sure you problem is this guy '<center><img class="loader" src="<?php echo base_url();?>/img/loader.gif" ></center>'
Yours source is going to output literally to <?php echo base_url();?>/img/loader.gif which is of course not a real link. Therefore it is a resource that can not be loaded.
You might want to try instead using: '<center><img class="loader" src="/img/loader.gif" ></center>'
The base_url() function is just going to return '/' anyway.
Important! In general you can not write php in javascript. Or this would be a massive security hole that would give every user who visits your site unlimited access to your server.

Reloading url page with ajax

i'm trying to refresh page every 3 second, the url page change with $_GET variable.
i'm trying to save $_GET var into session and cookie, but get error header has already sent.
how to change url after page reload ?
here my script :
Index.php
<?php
session_start();
$skill =$_SESSION['skill'];
?>
<script type="text/javascript">
var auto_refresh = setInterval(function () {
$('#src2').load('monitor.php?skill=<?php echo $skill;?>').fadeIn("slow");
}, 3000);
</script>
monitor.php
<?php
include "conn.php";
session_start();
$_SESSION['skill'] = $_GET['skill'];
if ($_SESSION['skill']=='')
{
$a ="bro";
$_SESSION['skill']=4;}
elseif ($_SESSION['skill']==4){
$a = "yo";
$_SESSION['skill']='5';
}
elseif ($_SESSION['skill']==5){
$a = "soo";
}
?>
First off, "headers already sent" means that whichever file is triggering that error (read the rest of the error message) has some output. The most common culprit is a space at the start of the file, before the <?php tag, but check for echo and other output keywords. Headers (including setting cookies) must be sent before any output.
From here on, this answer covers how you can implement the "refresh the page" part of the question. The code you provided doesn't really show how you do it right now, so this is all just how I'd recommend going about it.
Secondly, for refreshing the page, you will need to echo something at the end of monitor.php which your JS checks for. The easy way is to just echo a JS refresh:
echo '<script>window.location.reload();</script>';
but it's better to output some JSON which your index.php then checks for:
// monitor.php
echo json_encode(array('reload' => true));
// index.php
$('#src2').load('monitor.php?skill=<?php echo $skill;?>', function(response) {
if (response.reload) window.location.reload();
}).fadeIn('slow');
One last note: you may find that response is just plain text inside the JS callback function - you may need to do this:
// index.php
$('#src2').load('monitor.php?skill=<?php echo $skill;?>', function(response) {
response = $.parseJSON( response ); // convert response to a JS object
if (response.reload) window.location.reload();
}).fadeIn('slow');
try putting
ob_start()
before
session_start()
on each page. This will solve your problem.
Without looking at the code where you are setting the session, I do think your problem is there. You need to start the session before sending any data out to the browser.
Take a look at: http://php.net/session_start
EDIT:
Sorry, a bit quick, could it be that you send some data to the browser in the 'conn.php' file? Like a new line at the end of the file?

Posting JavaScript Value to PHP via Ajax issue

I need to get a value which is from jQuery to PHP so I can do a search function for my site.
I currently have tried:
<script>
$(document).ready(function () {
$('#search_button').click(function(e){
e.preventDefault();
e.stopPropagation();
carSearch();
});
});
function carSearch()
{
$.ajax({
type: "POST",
url: 'cars.php',
data:
{
mpg : $('.mpg').val()
},
success: function(data)
{
alert("success! "+$('.mpg').val()+"mpg");
}
});
}
</script>
This ajax is running when the button is pressed and js value is there as it is displayed in the alert.
However
if(isset($_POST['mpg']))
{
$query = "SELECT * FROM cars WHERE mpg =< ".($_POST['mpg'])."";
echo "<div class='test'></div>";
}
else
{
$query = "SELECT * FROM cars";
}
The isset doesn't trigger, the div is just a big blue box for testing purposes. The ajax is posting to cars.php which is also where the ajax is, so posting to its own file. Which I've not read about being done, but I've posted within the same file before just not with ajax.
I have also tried posting the value from the ajax to another file:
<?php
session_start();
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('cdb', $conn);
if(isset($_POST['mpg']))
{
$r = mysql_query ("INSERT INTO test VALUES ".($_POST['mpg'])."", $conn);}
}
?>
Just to test if it is doing anything and it isn't.
So
data:
{
mpg : $('.mpg').val()
},
Appears to be wrong, though I got this from looking at the many many other questions on here to do with passing js to php. I've tried all the variations for it I've seen on here, and only the above code results in the success function alert triggering.
I see a mistake here
$r = mysql_query ("INSERT INTO test VALUES ".($_POST['mpg'])."", $conn);}
The "}" at the end of the line probably throw an error. Is there error in your .php file when the ajax is running ?
To check if there is errors or see what the .php file is returning follow these steps:
Using Chrome right click on your page and choose "Inspect Element"
Click on "Network" in the menu
If not active click on the filter icon (depending on your chrome version)
Click on XHR element of submenu
Refresh your page and your .php file should appear
Click on it and see what the file is returning
(It could also be done in Firefox but not exactly the same titles)
Tell us what you got here.
Also, you should go with the extern file way. Because ajax data returning correspond to the .php file content. If your .php file contains anything else than what you need to return, there is a problem. Example: Any HTML on your .php file will be returning in the ajax data and this is probably far from what you want.

JS variable to PHP variable without buttons or refresh

I've searched for over an hour and tried many examples but none do what I need. From JavaScript I can display the necessary variable in PHP or HTML with <b id="citynm"></b> but I need to make citynm $citynm. I've tried looking in AJAX for the first time but could only get it to work with a button click or page refresh.
I need to run the JavaScript to get citynm and then make it into $citynm for PHP use on any page without running the JS again. The JS is only run once upon entering the site. But the $citynm will be run on several pages in different needs (such as echo "You live in ".$citynm).
The best way is to store the value you want for citynm into a session variable as below:
$_SESSION['citynm'] = $citynm
You have to do this either at page load, or by ajax. Then, you can use $_SESSION['citynm'] in any pages you want since its global.
USECASE 1: via user input
in your html document:
<input type="text" name="citynm" id="citynm" value="Brussels">
inside your javascript file (using jquery here for readability):
(function(){
$('#citynm').on('blur',function(){
// when the input value has changed, post its value to server.
var citynm = $(this).val();
$.post('http://domain.com/path/to/your/php/file.php',{citynm: citynm},function(data){
// if the request is successful, the following script will be executed.
alert("server said: "+data);
});
});
})(jQuery);
And inside the file.php file:
<?php
session_start();
if(isset($_POST['citynm']) && strlen($_POST['citynm'])>0){
$_SESSION['citynm'] = $_POST['citynm'];
}
echo "citynm is ". $_SESSION['citynm'];
?>
USECASE 2: no userinput
var cityname = city.short_name;
if (status == google.maps.GeocoderStatus.OK) { document.getElementById("citynm").innerHTML = cityname; }
(function(){
$.post('http://domain.com/path/to/your/php/file.php',{citynm: cityname},function(data){
// if the request is successful, the following script will be executed.
alert("server said: "+data);
});
})(jQuery);

Categories