skip to Main Content

I am new at this and I need some help.

I want to create a Cordova project which is supposed to do this. On the main page there’s a "Send"

button, when I click on it an ajax request should be sent to the the php file and it should return

"hello", and in the success function the result is alerted. Instead of that it alerts the whole PHP

file. This only happens when I run Cordova on browser with cmd.

I tried to execute it like I would execute a php file and it worked, so I don’t really understand what’s

the problem here.

Sorry for my bad English, but I hope that by looking at the photos you’ll understand my problem.

Help me Obi-Wan Kenobi, you’re my only hope.

alert.php

<?php echo json_encode("HELLO"); ?>

index.js

document.addEventListener('deviceready', onDeviceReady, false);

function onDeviceReady() {
    // Cordova is now initialized. Have fun!

    console.log('Running cordova-' + cordova.platformId + '@' + cordova.version);
    document.getElementById('deviceready').classList.add('ready');
}

function send(){
$.ajax({
    type:"get",
    url: "alert.php",
    success: function(result){
    alert(result);
  }});
}    
document.getElementById("send").addEventListener("click",send);

https://i.stack.imgur.com/Pwl5m.png

after accessing http://192.168.0.111/Project/www/alert.php
https://i.stack.imgur.com/q7BXK.png

2

Answers


  1. The problem is that http://192.168.0.111/Project/www/alert.php will just return the source code of alert.php that happens because the web server installed on the host 192.168.0.111 is not configured properly to run PHP.

    Depending on the server installed on 192.168.0.111 check how to configure PHP with it( your webserver might be Apache, Nginx, etc).

    If you configure the webserver properly when you visit http://192.168.0.111/Project/www/alert.php in the browser you should see just HELLO.

    Login or Signup to reply.
  2. Reason why your code works on a localhost is because your file extension ends with .php

    In your case http://192.168.0.111/Project/www/alert.php

    You can not execute PHP code if file extension ends with .html

    That is why you get whole content of a alert.php instend of method output

    I would suggest you to use JSON format to return content of a PHP file and then handle that JSON in success() callback. In this case your JS code does not need refactoring but for a future reference please check out https://www.w3schools.com/js/js_json_intro.asp

    Your alert.php file should look something like this:

        <?php 
            $txt = "HELLO";
    
            $json = json_encode($txt);
    
            echo $json;
        ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search