How to use ajax for php in the same page? - javascript

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;
}
?>

Related

JS counter write to database

Is there any way I can use this JS second counter, to write to mysql:
var counter = 0;
setInterval(function () {
++counter;
}, 1000);
Can I export it as a variable and then use that variable to write to mysql?
What I'm attempting to do is save the time the user was on the page.
Is this even possible?
To help solve your ajax part (need jquery):
$.ajax({
type:'POST',
url: "yourfile.php",
data:{
"foo": filename // to add more variables you add on the spot after filename but remember the last one variable you send shouldn't have a comma
}
});
on the receiving end (php):
<?php
$filename = $_POST["foo"];
?>
basically ajax is used to send data to a php script.
Javascript is a language that is used in client side and can't write to MYsql. The code above will help you send data to your script. Your php script will run once it recieves the data through AJAX
You would need to write a bit of back-end php to handle ajax query from your front-end javascript.
Your JS may look like this:
function ajaxRequest(data) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", "path/to/back-end.php", true);
xmlHttp.timeout = 1000;
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) { //DONE
//success
console.log("Successfully sent to back-end.php");
}
};
xmlHttp.send(data);
}
You can refer to http://www.w3schools.com/ajax/default.asp for more information.
Then your php will retrieve the body of this POST request and insert it to mysql database accordingly.

Ajax request to get data from php file?

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).

Cannot read POST array from AJAX call in external PHP file

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 a hashtag value from the url in php

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.

How to pass javascript variable to php inside javascript function

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>

Categories

Resources