dynamic loading of html via php javascript not executing - php

i have a simple setup, with php pulling html content from a database. if i go to my template page, it loads the data and returns it to the browser via a simple php echo ... not rocket science.
now, i've written an html file using jquery and an ajax call. i load the html file in my browser and the javascript / ajax query works.
when i load the html into the database and print it out via the php / echo, the content is the exact same when i view the source, but the ajax query doesn't execute.
<html>
<head>
<title>random query - api - get</title>
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
</head>
<body>
<pre>
executing the GET method
<script language="javascript" type="text/javascript">
$.ajax({
type: "GET",
url: "http://some-rand.om.api.com",
data: "011b38b8-011f-4b03-bb21-4c5bb26600b3",
success: function(msg){
alert( msg );
}
});
</script>
</pre>
</body>
</html>
Any comments / suggestions would be great. What I find bizarre, is i have no problem copying the source of http://jquery.com/ and pasting it into the db and doing the php / echo. this works fine. maybe an onLoad() would help...hm.

The issue is outlined in the following url:
XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin
When I load the javascript console in chrome I get this:
XMLHttpRequest cannot load http://some-rand.om.api.com/user?011b38b8-011f-4b03-bb21-4c5bb26600b3. Origin http://localhost is not allowed by Access-Control-Allow-Origin.

To resolve the problem, on the api vhost, in the code that serves the content accessed by the ajax query, i added this (it is also php):
header('Access-Control-Allow-Origin: http://some-rand.om.client.com');
Now when I access it, it's all good and loads as expected. So, infact, it wasn't related to it being stored in the database, php or javascript. It was related to cross site scripting.
Or, to be super lazy (probably not a great idea...):
header('Access-Control-Allow-Origin: ' . $_SERVER["HTTP_ORIGIN"]);

If in your description of the problem you are listing the whole of the code, then the JavaScript should be wrapped in a $(document).ready(function(){ ... });.
i.e.
$(document).ready(function(){
$.ajax({
type: "GET",
url: "http://some-rand.om.api.com",
data: "011b38b8-011f-4b03-bb21-4c5bb26600b3",
success: function(msg){alert( msg );}
});
});

Related

GET request using jquery AJAX to a php backend - returns entire page of php code

I'm learning the basics of PHP and am trying to create the most basic PHP backend possible, with a JS/jQuery frontend. My current problem is that a GET request does not execute the .php file, like I was expecting, but instead returns a whole page.
I've tried many jQuery and PHP scripts based on tutorials and stack overflow posts, and the current configuration is based on this post here.
I have read some other StackOverflow posts about this issue here, here, and here but couldn't get those solutions to work, or didn't understand the answer.
Here's my setup: I have an index.html page that will render the results of my jQuery AJAX request & a data.json.php page, where I would like a basic response to be sent from. These files are in the same directory.
--- jquery.js ---
$(function () {
$.ajax({
url: "data.json.php",
success: function(result){
alert(result);
}
});
});
---data.json.php---
<?php
header('Content-Type: application/json');
$output = "hello"
echo json_encode($output);
?>
I am using the live server addon to render the html and I have started the php server through the command php -S localhost:4000.
I do get an alert, but it's returning the contents of the .php file rather than executing it. I think that I may be misunderstanding how to start the PHP server correctly, the proper way of running a PHP script, or how the flow of information goes.
Any help, tips, or resources would be greatly appreciated. Thanks!
./test
./test/test.php
./test/test.html
#cd test
#php -S localhost:4000
test.php content:
<?php
header('Content-Type: application/json');
$output = "hello";
echo json_encode($output);
test.html content:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.2.min.js"></script>
</head>
<body>
<script>
$(function () {
$.ajax({
url: "http://localhost:4000/test.php",
success: function(result){
alert(result);
}
});
});
</script>
</body>
</html>
how to and test video

Passing Javascript Variable To PHP Using Ajax Echo's Undefined Index

I minimized the code snippets to show only the code needed, and the url for the server side file is actually connected to a url on my server.
HTML FILE
<head>
<script>
var btid = 1;
$.ajax({
url: "serverSide.php",
method: "POST",
data: { "btid": btid }
});
</script>
</head>
<body>
<?php include("serverSide.php"); ?>
</body>
serverSide FILE
<?php
$btid = $_POST['btid'];
echo($btid);
?>
DESCRIPTION
So what is going on is when the page loads, the javascript code runs. It creates a variable named btid equal to 1. This variable is then sent to a file on my server that is a php file. I want to echo that variable through php. But when I load the page, I get an error log stating that the code $btid = $_POST['btid']; has an Undefined Index.
I don't think your code is going to work as designed. You are using include("serverSide.php"); in the body of the HTML, but it is never going to have any $_POSTvalues unless you are posting a form.
Your ajax call is not doing anything with the value that is being returned.
I think you should remove the include("serverSide.php"); from the body of your HTML (it is serving no purpose in its current incarnation) and use the returned value of your ajax call to put the value of btid in the HTML (if that is where you want it).
When you use PHP's include as in <?php include("serverSide.php"); ?> PHP will execute the code on the file being included. That is what is causing your error, when the code is first evaluated it has no $_POST['btid'] because you haven't called it yet.
Your javascript will run on page load and make the ajax call correctly, but you are not using the response anywhere. In order to store the response from the Ajax call you need to add a success handler.
If I understood what you are trying correctly, your code should look more like this:
HTML FILE
<head>
</head>
<body>
<div id="response"></div>
<script>
var btid = 1;
$.ajax({
url: "serverSide.php",
method: "POST",
data: { "btid": btid },
success: function(res) {
$('#response').text(res);
}
});
</script>
</body>
What we are doing is making the ajax call and when the call is successful we assign the returned value as the div content. Also, I switched the script tag to the end of the body because we need to be sure all the document has loaded before changing anything (could have used $( document ).ready()).

Getting info from PHP file - Not in same Directory

I'm completely baffled with this. I've tried seemingly everything, and nothing has worked so far!
Basically, I have a PHP script which does some stuff and will feed out a number. Now, this PHP file is being hosted on my server and I need to extract that number from the PHP file through a HTML script which I can put anywhere.
This script works fine when both the PHP file, and the HTML file (which contains this script) are in the same directory:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.get("index.php",function(data){
document.write(data);
});
});
</script>
However, as the PHP script will be uploaded on a server, I need to be able to get the number which is displayed on the PHP script from wherever I put this code. So basically, I need to be able to use this code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.get("http://www.myserver.com/scripts/index.php",function(data){
document.write(data);
});
});
</script>
But I am really unsure as to why it is not working when it isn't in the same directory. I'm not looking to overcomplicate this, and just need a small snippet of code that I can use to collect the number which is fed from that PHP script. Please note that I cannot put these files in the same directory as I'm going to be using this code to feed the number onto a site-editor made website.
Thanks!
Your requests are getting blocked because of the Same-origin policy, your only choice is to use the same domain or enable cors.
So as long as your page AND php file are both placed under www.myserver.com, it will work.
JSONP Examples can be found here and here
$.ajax({
url: "http://www.myserver.com/php/file.php",
jsonp: "callback",
dataType: "jsonp",
success: function( response ) {
console.log( response ); // server response
}
});

change php variable with ajax

I have an php variable like this:
PHP Code:
$php_value = 'Am from PHP';
And I want to be able to change this variable with jQuery and the jQuery is on the same page?
You can't.
By the time the page has been delivered to the browser and the JavaScript has run, the PHP program that generated the page will have finished running and the variable will no longer exist.
JavaScript will allow you to send new data to the server (Ajax), where the server could store the data somewhere (a database is usual), and read the response.
JavaScript will also allow you to modify the page in in the browser (DOM) (including with the data included in the response for an Ajax request).
PHP code is run server-side, and jQuery runs on the client. The way to update a PHP variable from jQuery is to have a jQuery call which submits to the PHP page, and have the PHP look for it:
$php_value = 'Am from PHP';
if exists($_POST['php_value_from_jquery']) {
$php_value = $_POST['php_value_from_jquery'];
}
If I understand your question correctly, AJAX cannot post data to PHP code on the same page. I've been told that it can, but it is not trivial - still, I cannot imagine how that is possible. At any rate, AJAX is easy if a secondary PHP file is used.
Here is an example of what I mean. If you try this:
<?php
echo 'Hello';
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '',
success: function(data) {
alert(data);
}
});
}); //END $(document).ready()
</script>
</head>
<body>
</body>
</html>
The popup will contain the HTML for the page.
However, if you use two files:
file1.php
<?php
echo 'Hello';
?>
file2.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'file1.php',
success: function(data) {
alert(data);
}
});
}); //END $(document).ready()
</script>
</head>
<body></body>
</html>
The popup will contain only the word "Hello".
To use ajax, you must call an external PHP file.
After considering the above, note that Quentin's answer is important -- even if you use AJAX to set a PHP variable on the server, that variable disappears after the AJAX completes -- just like the PHP variables all disappear after your index.php has finished rendering the DOM and presenting it to the visitor's browser.
So, what's to be done? Two options.
(1) As Quentin points out, you can store values permanently in a database, or
(2) You can use a PHP superglobal, such as a $_SESSION variable. For example:
Client side: file2.php
var storeme = "Hello there";
$.ajax({
type: 'POST',
url: 'file1.php',
data: 'stored_on_server=' +storeme,
success: function(data) {
alert(data);
}
});
file1.php
<?php
session_start();
$SESSION['a_variable_name'] = $_POST['stored_on_server'];
You can later retrieve that variable value thus:
$.ajax({
type: 'POST',
url: 'file3.php',
success: function(data) {
alert(data); //a popup will display Hello There
}
});
file3.php
<?php
session_start();
echo $SESSION['a_variable_name'];
You can't able to change the php value using javascript. i.e Server scripts runs first after that client side script will take effect in that case you cant able to modify the same, since they already rendered in browsers
If jQuery is going to be processing the data, then you can assign the PHP variable to a jQuery variable like this:
<script>
var jquery_value = <?php echo $php_value; ?>
</script>
As far as I know, because jQuery is client-side and php is server side, it's not possible to assign a jQuery variable back to PHP.

ajax call is not responding

I am using ajax for retrieving data from my remote server when i am posting the ajax url directly in the address bar of browser, i am getting the data but when i am doing ajax call to that url in javascript file , it is showing error.I am pasting my code here.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$.ajax({
url:"http://www.appitechture.com/api/index.php?action=getContactDetails&id=96",
type:'get',
datatype:'json',
success:function OnSuccess(data , status){
alert(data);
} ,
error: function OnError(request , status , error){
alert('error');
}
});
</script>
</head>
<body>
<div id="images"></div>
</body>
</html>
so please if any one knows its solution please tell me.
Thank's
puneet
Are you trying to do a crossdomain AJAX request? Bad idea, read this article http://en.wikipedia.org/wiki/Same_origin_policy
If it is not the same domain, you need to use JSONP (JSON with padding). This is due to Same Orgin Policy, as Bogdan Burim states.
jQuery.getJSON can help you with this in a easy way. It will include a script tag like this on your page.
<script type="text/javascript"
src="http://example.com/jsonp?callback=parseResponse">
</script>
You will also need to change the response of the remote server to include the callback var like this:
parseResponse({"bar": "foo", "foo2": "bar2"});
You can also have a look at easyXDM:
easyXDM is a Javascript library that enables you as a developer to
easily work around the limitation set in place by the Same Origin
Policy, in turn making it easy to communicate and expose javascript
API’s across domain boundaries.
Wikipedia have a nice article about JSONP.

Categories