I have a simple jQuery post function that calls PHP script in order to return value from the database.
In Firebug I see that the PHP file is being called with 200 OK status, however the success function in JS is not being called.
To test the problem I have changed the PHP to only echo a simple string, but it doesn't work as well.
When I view the PHP file directly in the browser I do see the echoed string.
Here is the JS code:
$.post(PATH + "load.php", { id: _id },
function (data) {
console.log("LOADED " + data);
});
And here is the simple PHP code:
<?
echo "bla bla bla"
?>
I don't know what the problem is.
My HTML+JS file is local and it calls an online PHP file. Maybe this is the reason?
Any help will be appreciated.
My HTML+JS file is local and it calls an online PHP file. Maybe this is the reason?
Answer: Yes
Reason: Same origin policy rule
http://en.wikipedia.org/wiki/Same_origin_policy
Grant Thomas suggested a possible workaround: you can delegate the call to a method on same-origin server which calls external resource.
Related
\
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
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.
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;
?>
I'm having some trouble getting some php code working in my app.
The setup is rather easy: 1 button, 1 function and 1 php file.
script.js
$(document).ready(function ()
{
$("#btnTestConnectie").click(testConnectie);
});
function testConnectie()
{
$.get("script/SQL/testConnection.php");
}
testConnection.php
<?php
echo "It works!";
php?>
According to this post, it should work (How do I run PHP code when a user clicks on a link?)
Some sources claim that it is impossible to execute php via javascript, so I don't know what to believe.
If I'm wrong, can somebody point me to a method that does work (to connect from a javascript/jQuery script to a mySQL database)?
Thanks!
$.get('script/SQL/testConnection.php', function(data) {
alert(data)
});
You need to process Ajax result
You need to do something with the response that your php script is echoing out.
$.get("script/SQL/testConnection.php", function(data){
alert(data);
});
If you are using chrome of firefox you can bring up the console, enable xhr request logging and view the raw headers and responses.
Javascript is run by the browser (client) and php is run on the remote server so you cannot just run php code from js. However, you can call server to run it for you and give the result back without reloading of the page. Such approach is called AJAX - read about it for a while.
I see you are using jQuery - it has pretty nice API for such calls. It is documented: here
In your case the js should be rather like:
$(document).ready(function ()
{
$("#btnTestConnectie").click($.ajax({
url: '/testConnection.php',
success: function(data) {
//do something
}
}));
});
[EDIT]
Let's say you have simple script on the server that serves data from database based on id given in GET (like www.example.com/userInfo.php?id=1). In the easiest approach server will run userInfo.php script and pass superglobal array $_GET with key id ($_GET['id']=1 to be exact). In a normal call you would prepare some query, render some html and echo it so that the browser could display a new page.
In AJAX call it's pretty much the same: server gets some call, runs a script and return it's result. All the difference is that the browser does not reload page but pass this response to the javascript function and let you do whatever you want with it. Usually you'll probably send only a data encoded (I prefer JSON) and render some proper html on the client side.
You may have a look on the load() of jQuery http://api.jquery.com/load/
You should place all of your functions in the document ready handler:
$(document).ready(function(){
function testConnectie() {
$.get("script/SQL/testConnection.php");
}
$("#btnTestConnectie").click(function(e) {
e.preventDefault();
testConnectie();
});
});
You will have to have your browser's console open to see the result as a response from the server. Please make sure that you change the closing PHP bracket to ?> in testConnection.php.
One other note, if you're testing AJAX functions you must test them on a webserver. Otherwise you may not get any result or the results may not be what you expect.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Creating jQuery AJAX requests to a PHP function
I am trying to run a really simple formula,
Call a web page, and every few seconds or so Ajax calls a php function to echo "Hello World"
<?php
function test(){
echo "Hello World";
}
?>
<script type="text/javascript">
function testingTimer()
{
//CALL PHP FUNCTION CALLED TEST
}
setInterval('testingTimer()',5000);
</script>
All I need is the code that calls the already declared php function.
You cannot call that directly. Write code of AJAX and call URL like myfile.php?action=test and in file myfile.php write if action GET variable is equal to test then call that function and don't forget to exit code to prevent any other output.
Google on how to do ajax calls. It's basic knowledge explained in too many tutorials, and varies depending on if you are using a framework or not, and which.
You can post something for example :
function testingTimer()
{
$.post(URL,
{
foo : 'foo'
}
);
}
and in php check post:
if (isset($_POST['foo']))
test();
AJAX does not have the ability to call an arbitrary php function on its own. AJAX allows you to connect to a given page and request data. That being said, you can use AJAX to load a given page and all that page does is call your test function:
Based on your example code I assume you're trying to do this all within a single file. The issue you have is that PHP is run server side before/as the page loads. Once loaded it cannot be re-executed without a refresh.
You need to have your PHP in a separate file so that it can be called over HTTP by AJAX and return a response.
So something like this (if using jQuery):
$.ajax('helloworld.php', function(data){
alert(data);
}, 'html');
Should popup with hello world if implemented correctly.
You should use jQuery to use the ajax function.
You should not use a setInterval, but a setTimeout after the response of server because if the server take more than 5000 seconds to respond, then you'll have two requests at the same time.
If you want to put a timeout, you can always see the abort function on the jqXHR Object.
For example, you could do:
function refresh() {
$.ajax({
type: 'GET', // can be POST or GET
url: 'page.php' // php script to call
// when the server responds
}).done(function(response) {
console.log(response);
// call your function automatically
setTimeout(refresh, 5000);
});
}
I am making an ajax call to a php file, But I dont want it to return anything.
My php file has HTML content or rather a JS code, which needs to be executed over there itself. Please help me with this. I dont Know why this is happening
This is my ajax code:
$.ajax({
type : "POST",
url : "<?php echo CALLBACKURL; ?>mobile_profile.php",
data : data,
success: function(response){
}
});
I am not giving any console.log but syill in the response its giving the whole of html
code.
I need to execute that js code there itself and I dont want anything as response Or if we cant do this atleast can i run the JS code return nothing
Where do you want your code to execute? In the browser or at the server?
If you do not want it to contact server and run there itself(inside browser), why are you using AJAX? You simply call a function which will do whatever you want.
on success what do you expect it to do? There is nothing inside the braces...
success: function(response){
}
Browsers cannot process php code. they can process only html and javascripts and some third party scripts with the help of add-ons.
Kindly be clear what you are expecting.
url: "<?php echo CALLBACKURL; ?>mobile_profile.php"
replace it with:
url: "mobile_profile.php"
and put those php tags inside that mobile_profile.php, if required.
If you wish, you can pass parameters to that php file by suffixing your? and a querystring so that the called php file understands what to do.
I think this helps.
I can post the data using jquery (Checked with the mysql insert from that php file, it does insert, so i'm 100% sure that posting works), even though something is echoed in the php file, i can't seem to return that to the page with my data function (also checked if it echoes normally)... I know it should work, any ideas why it wouldn't?
$('#formbutton').click(function() {
var user = $('#nameinput').val();
$.post("usercount.php", {
username: user
}, function(data) {
alert("Data Loaded: " + data);
});
});
If the data is inserted, there should't be anything wrong with the request. My guess is that a fatal error occurs after the data is inserted, thus preventing the output. You should check your PHP logs for a clue.
You should also check the response code of the request in the Net panel in Firebug or similar tools. If the response fails, the callback function in $.post won't execute. Try using the $.ajax function instead, and provide both a success and an error callback.
Everything seems correct (or at least I can't see anything wrong now).
Use the network panel in firebug or chrome developer tools to inspect the request and the response of the ajax calls and see if they are correct (and also if the response comes with http status code 200). Also check the javascript console, put a breakpoint here or there and play with it (it's fun :D)