Getting Data from php through Ajax [duplicate] - javascript

This question already has answers here:
Ways to circumvent the same-origin policy
(8 answers)
Closed 8 years ago.
I am a novice to PHP, trying to learn.
I have my php file present in www folder in the WAMP server.
<?php
echo 'Hi';
?>
This can be run if I go http://127.0.0.1/testRequestParameter.php from my Browser, it prints Hi
So now I created an HTML page(not present in the same directory)
<html>
<head>
<script src="jsLibrary/jquery-1.11.1.min.js" ></script>
</head>
<body>
<script type="text/javascript">
function getTestDataFromAjax()
{
var url = 'http://127.0.0.1/testRequestParameter.php';
$.ajax({
url: url,
success: function(data) {
alert(data);
},
async:false
});
}
</script>
<input type="submit" name="Button" onclick="javascript:getTestDataFromAjax(); return false;" />
</body>
</html>
And when I try to call that php through AJAX, the response is blank.
May be it I am missing something, any help will be appreciated.
Finding1: In my firebug it is showing, Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1/testRequestParameter.php. This can be fixed by moving the resource to the same domain or enabling CORS.
Any setting which I need to change?

Scenario
I tested your script using EasyPHP: I created into http://localhost/script/test/ the file content.php
<?php
echo 'Hi!';
?>
Then, I added to my desktop index.php:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
function getTestDataFromAjax()
{
var url = 'http://localhost/script/test/content.php';
$.ajax({
url: url,
success: function(data) {
alert(data);
},
async:false
});
}
</script>
<input type="submit" name="Button" onclick="javascript:getTestDataFromAjax(); return false;" />
</body>
</html>
Then, I launched index.php and clicked on the button, which returned an error when clicked:
XMLHttpRequest cannot load http://localhost/script/test/content.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Solution
So, I edited my content.php like this:
<?php
header("access-control-allow-origin: *");
echo 'Hi!';
?>
And it's now working

Related

Use `window.top.$` to send ajax request in iframe, but the referer is not the url of iframe src

There are two html files, an index.html and inner.html.
** index.html **
<html>
<body>
<script src="./node_modules/jquery/dist/jquery.js"></script>
<iframe src="./inner.html" frameborder="1"></iframe>
</body>
</html>
It has referenced jquery.
** inner.html **
<html>
<body>
<input type="button" id="button" value="Get Data by AJAX">
<script src="./inner.js"></script>
</body>
</html>
** inner.js **
const $ = window.top.$
$('#button', window.document).click(function () {
$.ajax({
url: '/data.json',
success: function (data) {
console.log(data)
},
context: this
})
})
On the server side, I will print the header referer.
The url to open index.html is: http://localhost:3000.
I found when I make ajax requests in inner.html, using the $ from window.top, the referer printed in server is http://localhost:3000, which is the url of the outer page.
I expected to be the url of iframe, to be http://localhost:3000/inner.html, but can't find a way if I insist using the jquery from window.top.
PS: If I move the code <script src="./node_modules/jquery/dist/jquery.js"></script> from index.html to inner.html, and use window.$ to send ajax requests in inner.html, the referer is what I expect: http://localhost:3000/inner.html
This is a simplified demo for my project, in which we have to use the jquery provided by the platform, which is window.top.$

Javascript POST to PHP works locally, fails externally

This is really simple code I have, it works on my site (if link to php is just "/phpcode.php", but fails to retrieve data if I put the javascript request on the other site and call full link.
I am using godaddy.
I am beginner and have no freaking idea where to look for solution or troubleshoot it.
This is PHP side (full code of phpcode.php):
<?php
$val = 'apple';
echo json_encode($val);
?>
And here is javascript request:
$.post(
"http://website.com/phpcode.php",function(data){
alert(data);
},
"json");
And here is full code of the javascript page
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.post(
"http://website.com/phpcode.php",function(data){
alert(data);
},
"json");
});
});
</script>
</head>
<body>
<button>TEST POST</button>
</body>
</html>
Thanks for your help.
This could be something causing the error. Add the line
header("Access-Control-Allow-Origin: *");
after <?php in phpcode.php, this would make your code:
<?php
header("Access-Control-Allow-Origin: *");
$val = 'apple';
echo json_encode($val);
?>
In future, you'll be more likely to get a better answer from your question if you include any error messages / warnings that can be seen. You can often see these in the javascript console. [ctrl] + [shift] + [i] in chrome and then go to the console tab.
ok guys, it is solved.
1st issue was that php code was put into http: site and calls were made from https: sites.
2nd - the particular site could not do alert(data), but response was there. Thank you #stefan for reminding to check responses. Solved it with an extra variable.
Thank you for your help!

Can't get php POST sent by AJAX

I know there's a lot of similar questions here, but I looked up over 20 of them, and no solutions worked for me.
Here's the problem: I'm sendind an ajax post value to my index.php. When I look at Firebug, the value is there, but when I try to echo it on the page, the POST is empty. I'm really stucked on this.
Here's my full code:
<?php
if(isset($_POST['action']))
{
echo $_POST['action'];
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="utf-8">
<!-- JQUERY LIBRARY AND SCRIPTS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
Test
<script type="text/javascript">
$(document).ready(function()
{
$('a').on('click', function()
{
$.ajax({
url: 'index.php',
type: 'POST',
data: {action: 'clicked'},
success: function(data)
{
console.log(data);
alert('Done!');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
return false;
});
});
</script>
</body>
</html>
This code does not try to print that to the page, but simply prepends the whole HTML document with a "clicked" string, in the ajax response. If you want to show this in the browser, you need print that data to the page. If you inspect the console in FireBug, you will see that the response for the Ajax call is exactly what I described above.
Now if you want to print that value back to your page, here is my suggestion, you create a separate file, ajax.php:
<?php
if(isset($_POST['action']))
{
echo $_POST['action'];
}
?>
And fix your index.php to include some element where you are going to print that value to. I.e. add <div id="response-results"></div> just after your element. Then change your Ajax call to go to ajax.php, not index.php.
Now you need to populate that Ajax response to the rendered page, and this can be done simply with jQuery like:
$("#response-results").html(data);
Ofcourse, this goes into the success handler of the ajax call.
As Jay Blanchard said
You're using AJAX to send a a variable to a page which is already rendered on your browser. This will never work because the PHP your're getting the variable from has been run server-side and returned via AJAX, not in the page you're currently viewing.
Try this it will work :
index.php :
<?php
if(isset($_POST['action']))
{
echo $_POST['action'];
}
?>
main.html :
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="utf-8">
<!-- JQUERY LIBRARY AND SCRIPTS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
Test
<div id="result"></div>
<script type="text/javascript">
$(document).ready(function()
{
$('a').on('click', function()
{
$.ajax({
url: 'index.php',
type: 'POST',
data: {action: 'clicked'},
success: function(data)
{
// console.log(data);
$("#result").html(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
return false;
});
});
</script>
</body>
</html>
As R J commented, it's impossible to do what I was trying to.
That happens because once my page is loaded, the top PHP script is proccessed, but there's nothing on my POST.
After my call to Ajax, the page is rendered again but the top PHP script will get nothing cause it's SERVER SIDE. Turns out that I even could print out my Ajax data on the page, but the PHP $_POST would never get its value.
Thank you guys.

AJAX wait until file exist on another server

I'm developing a website based in to servers. One is a free host and another is a Raspberry Pi. When you access a webpage in the free host, you get a form where you enter a link. The link is send to the Raspberry Pi which is permanently running a script that downloads some content of the link recieved and saves a big txt file. The script takes a bit to load (30 secs aprox) so I want to create a Javascript script in the primary page (free host one, with the form) wich shows a load icon and checks in the raspberry downloads folder until the file exists.
I think AJAX will be the best for this. The workflow is:
user access form.php and enters a link
the form is send directly to the RPi
the RPi begins to download things and returns the user to the refferrer page with the get parameter id=
here the ajax code begins to work checks into an url if .txt exists if it exists, it shows the download link else, it waits checking until it gets a 200 status code (This is what i need)
I know the problem with javascript and different servers so i've created a php script named check.php in the same server and folder of form.php which gets id as parameter and return 200 or 404 so the ajax code just needs to get that answer and act in consecuence
How can I do it? I'm new to AJAX, I know just a bit of Javascript. Could you help me withe the AJAX code?
My form.php?id= page:
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>downloader</title>
</head>
<body>
<div id="content">
<?
if (!$_GET){
?>
<form action="<<rpi server>>" method="post">
URL: <input type="text" name="link">
<input type="submit" value="Download">
</form>
<?
}else{
?>
<script>
$.ajax({
type: 'POST',
url: '/check.php',
data: {'id':'<? echo $_GET['id']; ?>'},
//check if response is 200 or 404, if it's 404 keep checking every second, else show mesage
}
});
</script>
<?
}
?>
</div>
</body>
</html>
Use this
function checkFile()
{
$.ajax({
type: 'POST',
url: '/check.php',
data: {'id':'999'},
error : function(){
setTimeout(function(){ checkFile(); }, 3000);
},
success : function(data) {
//do whatever you want
}
});
}
$(function() {
checkFile();
});

Retrieve the content of the JavaScript file

Using JavaScript, I want to retrieve the content of the script files. These script files remain in local(in web page).
For example.
In web page, there is a script,
<script src="tool.js"></script>
Latter, I want to get the content of tool.js and process the retrieved result (like dump its content).
I have tried to use jQuery.getScript. However, it tells me that Origin null is not allowed by Access-Control-Allow-Origin.
try an ajax like the following
$.ajax('/tool.js', {
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
success: function(data) {
console.log(data);
},
error: function() {
console.log("call failed");
}
});
You need to configure your Access-Control-Allow-Origin:
Access-Control-Allow-Origin: *
This lets you use any resource to obtain assets from an external domain. Do this first and either Mahan's or Lars's solution will work.
More info:
Access-Control-Allow-Origin Multiple Origin Domains?
try using jquery.load() and put its contents on an element and use .html()
<html>
</head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
//setup ajax to work locally
$.ajaxSetup({
crossDomain: false,
isLocal :true
});
$("#a").load('jquery.js', function() {
alert($("#a").html());
});
});
</script>
</head>
<body>
<span id="a" style="display:none;"></span>
</body>
</html>
Browser Check:
the code above works and tested in FF, Safari, Opera and IE
but if you keep on having problem with Origin null is not allowed by Access-Control-Allow-Origin then having a web server installed is needed as said here; Origin null is not allowed by Access-Control-Allow-Origin
Reference:
http://api.jquery.com/load/
code for your disposal : http://jsfiddle.net/PeaH3/1/

Categories

Resources