I have been researching on how to make an Ajax request and came up with this:
function ajax_post(){
// Create our XMLHttpRequest object
var xmlhttp = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "http://localhost:888...-files/test.php";
// Set content type header information for sending url encoded variables in the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var return_data = xmlhttp.responseText;
document.getElementById("demo").innerHTML = return_data;
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send(); // Actually execute the request
document.getElementById("demo").innerHTML = "processing...";
}
I saved this script as a file under: http://localhost:888...ascript/test.js <-- I have tested other scripts saved at this location and they work perfectly fine. My php file contains the following data (it is named "test.php"):
<?php
echo(rand(10,100));
?>
After I make the request to the php file which should display a random number according to the php code, my html looks like this:
<div style="display:none;">
<body onload="ajax_post()"> <------ Here you can see that I have called the function which executes the AJAX Request after the page has loaded.
<script type="text/javascript" src="http://localhost:888...ascript/test.js"></script>
</body>
</div>
<div id="demo"></div>
I keep refreshing the page and nothing appears. Does it have to do with my php code? Perhaps my Ajax request is wrongly structured? In terms of Ajax request, I have tried "GET" and "POST" as well and still nothing happens. I am new at Ajax and the might syntax my not make sense... Thank you in advance for the support.
Regards!!
I added some html to the php file and everything loads except the php file (php appeared as a comment). Then, I came up with the idea to compare the php file I created with the other php files on my local server. I identified a little difference. The other php files do not close the php, i.e. <?php echo 'Hello World'; without putting ?> at the end, and now it works. My php file looks like this:
<?php
echo 'Hello World';
I also simplified my script, making my structure look like follows:
<div id="demo"><div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready( function() {
$('#demo').load('http://localhost:8888/...php-files/test.php');
});
</script>
I used JQuery .load() property as it is simpler than the normal script (same principle).
Related
Hello friends i want use ajax on same php page. But problem is i can use ajax on different pages but not in same page. I saw people accomplished it with jquery but i dont wanna use jquery. Thanks-
<?php
$gg = $_POST['day'];
echo 'today is '.$gg;
?>
<html>
<head>
<script>
function clickMe(){
// Create our XMLHttpRequest object
var req = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "example.php";
var dayName = document.getElementById("dayName").innerText;
var vars = "day="+dayName;
req.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
req.onreadystatechange = function() {
if(req.readyState == 4 && req.status == 200) {
let return_data = req.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
req.send(vars); // Actually execute the request
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
<p id="dayName">saturday</p>
<button onclick="clickMe()">btn</button>
<br><br>
<div id="status"></div>
</body>
</html>
First of all in your php code you are getting input via $_GET and in your code you are sending a POST request which is counter intuitive. What you can do is when certain parameters are passed either through query string or request body with a post request, you can write your desired output and call die() to not display the rest of it which will interfere with the response you get. I don't see a real reason to do so in the same file but, here's an example using query string:
<?php
if(isset($_GET['day'])) {
die('Today is ' . htmlspecialchars($_GET['day']));
}
?>
Then in your javascript code make sure you send a valid request according to your needs.
It's not a good idea to use the same page to print html and do some php stuff. But, if you really want to do so, with javascript you can send another var like ajax=1 and change you php code :
<?php
if(isset($_POST['ajax'])) {
echo 'today is '.$_POST['day'];
exit;
}
?>
I've tried every solution I could google, but I can't read the data from a POST array in my external PHP file. Here's the HTML of the text field.
<form>
<textarea id="comment_text_area" name="comments" rows="5" cols="40">
</textarea>
<label for="comment_text_area">Comment:</label>
<br>
<input type="submit" name="submit" value="Submit" onclick="SaveComments()">
</form>
... and the JS function making the AJAX call
function save()
{
var data = document.getElementById("comment_text_area");
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.open('POST', 'save_comments.php', true);
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4 && xhr.status == 200)
{
alert("Comments saved!");
}
}
xhr.send(data);
}
... and the PHP file
<?php
if(isset($_POST['comments']))
{
$data = htmlentities($_POST['comments']);
$file = "comments.txt";
file_put_contents($file, $data, FILE_APPEND | LOCK_EX);
}
else
{
$data = "empty";
$file = "comments.txt";
file_put_contents($file, $data, FILE_APPEND | LOCK_EX);
}
?>
What I know is working:
The AJAX call is completing successfully, and the script is being run and "empty" is being written.
Things I have tried:
I read that event listener functions should be attached to HTML elements before they are made, which seems counter-intuitive. Made no change.
Using
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
Didn't work. And, based on the research I've done for that, shouldn't that only seem necessary for GET calls? (I need to use POST)
Making the POST call synchronous. Nothing changed.
I Know that the name of the element you're passing needs to be what you rely on in the PHP script, but it's not working. I don't want to set form action="" because I don't want redirection, which is why I'm going through AJAX.
Finally, something I've noticed, it's changing the URL as I click submit, something I would expect from GET. That is GET specific, right? I clearly marked it as POST though.
Does anyone see what I am doing wrong?
P.S. - Please, if it's on the JS side of things, no jQuery. I've avoided it thus far, I'm trying to keep it that way.
You need a variable to pass in the request not just the value as
xhr.send("comments="+data);
So that in server side you can retrieve the data by param name.
I need to get the text behind the hashtag in the url (http://www.example.com/#TEXT) so i can use it in a php script. I know that I have to gather the text using javascript then save it as a cookie or something like that. The only problem is that I'm not good at javascript and I have tried but failed.
How can i do this the easiest way?
Here is one thing i have tried:
<script>
var query = window.location.hash;
document.cookies = 'anchor=' + query[1];
<?php if (!$_COOKIE['anchor']) : ?>
window.location.reload();
<?php endif; ?>
<?php
echo $_COOKIE['anchor'];
?>
Most sites that use the fragment like this (such as Facebook) will use JavaScript AJAX calls, depending on location.hash, to send its request to the server. Try that!
var xhr = new XMLHttpRequest();
xhr.open("GET","something.php?hash="+location.hash.substr(1),true);
xhr.onreadystatechange = function() {
if( this.readyState == 4 && this.status == 200) {
// do something with this.responseText
}
};
xhr.send();
The hash part of the URL is not sent to the server, so you need to do so yourself.
The cookies set by the client too are not sent to the server either; the client just remembers them when it talks to the server.
This means that you have to retrieve in Javascript, as you already did, and make an explicit call.
// Example in jQuery
jQuery.ajax({
type: "POST",
url: "/path/to/php/script.php",
data: {
hash: window.location.hash
}
});
Then in the script.php you receive a $_POST['hash'] variable and can store it in the session. But remember that when you do, the sending page has already been loaded and is "stopped". If you want to trigger a reload, you need to send back some kind of response and react to it in jQuery's return function.
You can't. hashtags don't fly to the server. that's why MEGA site is still alive. hashes live only in the browser.
This question already has answers here:
Can scripts be inserted with innerHTML?
(26 answers)
Closed 8 years ago.
Using Ajax, I'm calling a php file that contains javascript, but in this way, the javaScript doesn't work.
The main.html file is given here. It just uses Ajax for calling a php file called test1.php for updating all page at client.
<!DOCTYPE html>
<html>
<body>
<!-- run php file to fill the page -->
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.body.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","test1.php",true);
xmlhttp.send();
</script>
</body>
</html>
And the test1.php file is very simple test as follows:
<p id="demo">Hi there</p>
<script>
document.write("Yes! Hi there");
alert('Welcome!');
</script>
Now, just for checking that test1.php is ok, I put in the browser's url line:
localhost/test1.php
and everything works ok, the text of the html and js are displayed and an alert window with the word Welcome! is displayed.
But if I call the main page
localhost/main.html
Then only the html text 'Hi there' is displayed. The JS is ignored.
Anybody knows why is this?
Thanks
Krasimir Tsonev has a great solution that overcome all problems. His method doesn't need using eval, so no performance nor security problems exist. It allows you to set innerHTML string contains html with js and translate it immediately to an DOM element while also executes the js parts exist along the code. short ,simple, and works exactly as you want.
So in this case, the response from ajax is the src string which then translated to a DOM object according to Krasimir Tsonev and then you have it works with js parts that are executed.
var el = str2DomElement(xmlhttp.responseText);
document.body.innerHTML = el.innerHTML;
Enjoy his solution:
http://krasimirtsonev.com/blog/article/Convert-HTML-string-to-DOM-element
Important notes:
You need to wrap the target element with div tag
You need to wrap the src string with div tag.
If you write the src string directly and it includes js parts, please take attention to write the closing script tags correctly (with \ before /) as this is a string.
Here are 3 basic examples of what you can do with ajax & how you should do it:
Main html
js
function ajax(a,b,c){ // Url, Callback, just a placeholder
c=new XMLHttpRequest;
c.open('GET',a);
c.onload=b;
c.send()
}
function changeHTML(){
document.getElementById('mytext1').innerHTML=this.response;
}
function executeJS(){
(new Function(this.response))()
}
var array=[];
function loadJSON(){
array=JSON.parse(this.response);
updateFields();
}
function updateFields(){
for(var a=0,b;b=array[a];++a){
document.getElementById(b.id).textContent=b.data;
}
}
window.onload=function(){
ajax('getHTML.php',changeHTML);
ajax('getJS.php',executeJS);
ajax('getJSON.php',loadJSON);
// even if this works you should execute ajax sequentially
}
html
<div id="mytext1"></div>
<div id="mytext2"></div>
getHTML.php
<?php
echo "<div>i'm html</div>";
?>
getJS.php
<?php
echo "var a='hello';alert(a);";
?>
getJSON.php
<?php
$arr=array(array('id'=>'mytext2','data'=>'data'));
echo json_encode($arr);//json_decode
?>
if you want to execute a javascript function use the executeJS function and pass a valid javascript string.
There is no need for EVAL!
TIP:using json you can pass a function as data but as the parsing does not like the string function at the beginning a nice trick is to convert the javascript to base64 and back into a normal string with javascript with atob(base64) and have something like this:
function updateFields(){
for(var a=0,b;b=array[a];++a){
if(b.func){
(new Function(atob(b.func)))()
}else{
document.getElementById(b.id).textContent=b.data;
}
}
}
php
<?php
$arr=array(
array('id'=>'mytext2','data'=>'data'),
array('func'=>base64_encode("alert('jsonfunc')"))
);
echo json_encode($arr);//json_decode
?>
maybe there are some little errors ... i wrote that now. and can't check ajax atm.
if you have any questions just ask !!
I want to give you one advice that insted use of javascript you can use jquery ajax it will be easy and latest thing for ajax.
You can use $.ajax function. You can use json easily with this function
When you make an AJAX call you contact to a server url. If your url is, as in this case, a php page, it will execute on the server and return to your AJAX call the HTML that it produces... now you can play with that HTML and manage it or publish into your current's page DOM.
-AJAX is a server call that executes server code.
-A script tag embeded on a php page is HTML that will execute the code it contains on client when parsed and executed by a browser.
So... your code isn't executing because it's never being called... the response to your AJAX call will be exactly
<p id="demo">Hi there</p>
<script>
document.write("Yes! Hi there");
alert('Welcome!');
</script>
The php page executes and return that to your current page as text/html.
If you want to execute client code from your javascript you should have it on the same .js file or in another one included, but if you include it on a server page you'll need to redirect your browser to that page, if you call it with AJAX the code won't execute as the client browser won't parse it.
I have a js file. Is it possible to do inside the js file a php coding? On my header I include my js file like this.
<script type="text/javascript" src="js/playthis.js"></script>
now inside my jsfile:
function getURL(e) {
alert(e+' javascript varibale');
<?php $url; ?> = e;
alert('<?php echo $url; ?>'+' php variable');
}
in my php file
<?php $url = "www.google.com"; ?>
<a href="#" onclick="getURL('<?php print $url; ?>');" class="title">
It's not working. Is there something wrong?
you have to make a new object for Ajax transaction named XMLHTTP REQUEST in some browsers and in I.E this is ActiveXObject basically; and this object belong to window object;
so the first step is:
if ( window.XMLHttpRequest ) {
XHR = new XMLHttpRequest();
}
else if ( window.ActiveXObject ) {
XHR = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
alert("You Cant see because Your Browser Don't Support Ajax!!!\n Change Your Browser To A Modern One");
}
now, you have the right object
in next step, there is some methods for XHR object for send and receive you should know:
1/ onreadystatechange
2/readyState
3/status
4/open
5/send
6/setRequestHeader
first open a connection with open:
XHR.open("POST", url, true);
as you know, post is method of sending, and now you have to set the url you want to information send to, for example if you want to send the variable to the test.php, then the url is test.php...
true means the request will sent asynchronously..
next is set your request header, because your are using post method, in get method you don't need this:
XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
next is sending the request with send method with this format send(name, value):
XHR.send('value=' + value);
first string 'value=' is the index of $_POST that you will get in php, so in your php code, you'll give this with $_POST['value'], if you set the name to 'name=', in php you have $_POST['name'], be careful that in Ajax send param you have to use = after the name of data, but in php the = is not used...
after you sent the request; it's time to mange response:
XHR.onreadystatechange = function() {
if ( XHR.readyState == 4 && XHR.status == 200 ) {
document.getElementById('your target element for show result').innerHTML == XHR.responseText;
}
}
XHR.readyState == 4 and XHR.status == 200 means every thing is O.K.
this is the basics of Ajax as you wished for; but there is so many information for Ajax, and either you can use jQuery Ajax method that is so simple and flexible; But as you want I described the basics for you...
No it's not possible to have PHP code inside JS file.
You can make $.ajax call to a PHP file and that file can handle the setting of the variable required.
Hope this helps.
There are a few ways to handle this.
1 - Have .js files parsed by php. You will need to change your webserver configuration to do this.
2 - Use AJAX to interact with php.
3 - Have php render an additional JS snippet in the body onload event that sets this JS parameter (but still have the library as a seperate file).
this is not necessary, when you print the url with print $url in onclick attribute inside the php page as an argument for getURL function, it means the value of $url will be sent to the function with name getURL in your js file...
so, you have to write:
alert(e);
and if you are just asking, as the other friends told, you should use Ajax for this...
when you assign a variable to a function as an argument, just like getURL(e), the time that you call the function,getURL('print $url") you have to set the value of that variable, so, the program set the value you give to the function to the default variable...e = $url
you can change .js file to .php file and work with javascript and php together
change this
<script type="text/javascript" src="js/playthis.js"></script>
to this
<script type="text/javascript" src="js/playthis.php"></script>