I am puzzled as to why PHP sees my request string as undefined.
$_GET['ask'] in my php file
produces this error -> Notice: Undefined index: ask.
But when I query the php file from the url bar in the browser like this
localhost/Websites/webProject/data.php?ask=myquery
I have set the php file to echo my string and it does do exactly that but only when I query it from the browser URL bar.
But when running the AJAX code normally from the parent html/php file
request.open("GET", "data.php?ask=myquery", true);
The PHP file does not see the query string and thinks its undefined.
Why is this the case?
I have tried to use
$_REQUEST[]; but to no avail.
I am using pure javascript for the AJAX requests.
Here is the javascript
requestResponse();
function requestResponse()
{
var READY_STATE_DONE = 4; /* request finished and response is ready */
var SUCCESS = 200; /* "OK" */
setInterval(function(){
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(this.readyState == READY_STATE_DONE && this.status == SUCCESS)
{
var response = this.responseText;
console.log(request.responseText);
document.getElementById("test").innerHTML += "<br>" + response;
}
}
request.open("GET", "data.php?ask=myquery", true);
request.send();
}, 3000)
}
Here is the PHP content
testRequest();
function testRequest()
{
$reqString = $_REQUEST['ask'];
include("dbCredentials.php");
include("dbConnect.php");
if($reqString == "myquery")
{
echo("<br />REQUEST IS: " . $reqString);
echo("<br /> Your request is granted");
}
}
DISCLOSURE: I have replaced the previous php file with data.php.
Try using Jquery Ajax request. this is mostly effective when you want to pass strings instead of serialized data
HTML:
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script type='text/javascript'>
$(function(){
$.ajax({
type: 'post',
url: 'data.php?ask=whut',
success: function(response){
alert(response);
}
});
});
</script>
PHP Content:
echo $_GET['ask'];
Related
Hello i now using this php code for get steam nicknames
function EchoPlayerName($steamid){
$xml = simplexml_load_file("http://steamcommunity.com/profiles/$steamid/?xml=1");//link to user xml
if(!empty($xml)) {
$username = $xml->steamID;
echo $username;
}
}
or
$steam = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64", true);
$steamarray = json_decode($steam, true);
$name = $steamarray['response']['players'][0]['personaname'];
but i this using for listing players and loading page is slow
so i want this data load via javascript after full load page
any ideas?
API example
{"response":{"players":[{"steamid":"76561197964477177","communityvisibilitystate":3,"profilestate":1,"personaname":"The [G]amerX #ππ¨π‘π£πππ¬.π½πΏπΌ","lastlogoff":1558765863,"commentpermission":1,"profileurl":"https://steamcommunity.com/id/gamerxcz/","avatar":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013.jpg","avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013_medium.jpg","avatarfull":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/66/6673d6df066386d232164e8f9a5d9b36cad1d013_full.jpg","personastate":0,"realname":"Community Owner","primaryclanid":"103582791433644720","timecreated":1076786008,"personastateflags":0,"loccountrycode":"CZ"}]}}
First, you should get Data using ajax of pure javascript or jquery. Then you should target an HTML element that you want to fill it using this retrieved data. Imagine element with ID target.
jQuery:
$(document).ready(function () {
$.ajax({
url: "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64",
}).done(function (data) {
var json = JSON.parse(data);
$('#target').text(json['response']['players'][0]['personaname']);
});
});
pure javascript:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key={API_KEY}&steamids=$steamid64');
xhr.onload = function () {
if (xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
document.getElementById('target').innerHTML = json['response']['players'][0]['personaname'];
} else {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
Remember to place these scripts at the end of your document.
I have a simple website that uses JavaScript to collect user input and sends data to PHP script (script is an external php file) via AJAX request. PHP script updates database with this information.
Now, i have a JS function on my website that i want to call only after PHP script is sucessfuly run and database updated. I don't need any data from database or PHP script, i only want to make sure that database is updated before calling this Javascript function.
This is what AJAX request looks like:
function ajax_post(){
if (typeof featureId !== 'undefined') {
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "parse_file.php";
var fn = featureId;
var vars = "featureId="+fn;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
hilites.destroyFeatures();
featureId = undefined;
}
else {
window.alert("Select polygon first");
}
}
What is the best way to do this? Some examples would really help.
Looking at your code, you simply need to call the function around this part:
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
// CALL YOUR FUNCTION HERE
}
}
The best solution is to use a Promise. However, this is not supported in IE 11, so you will need to use a polyfill on some browsers.
Here is an example using jQuery.
// This is the function you want to call after the script succeeds
function callbackSuccess() {
console.log('Done!');
}
// This is the data you want to submit to the PHP script
var myData = {
hello: "world"
};
// This is the actual AJAX request
$.post('/my-script.php', myData).done(function(){
callbackSuccess();
});
Add this to the end of your php save-function:
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('status' => 'SUCCESS'));
Making the call:
$.getJSON('url_to_your_php_file.php', function(data) {
if (data.status == 'SUCCESS') {
console.log('Save complete');
}
else {
console.log('oops, something went wrong!!');
}
});
It's possible to return something like ERROR, this will return:
console.log('oops, something went wrong!!');
You may try the following:
In php you can use return code from sql statement
echo $sqlResult = $conn->query($sqlStatement);
On Javascript, you can try the following
$.ajax({
url: 'file.php',
type: 'POST',
data: {
data1 : data1,
data2: data2
},
success: function(data){
if(data == success_code){
alert("Success")
}
}
Hope this helps!
Completing ajax request without errors does not mean that the data is saved to DB without errors.
Even if your PHP script fails to save the data, it probably echos some error message or even empty output as regular HTTP response, and it would show as success as far as the ajax request goes.
If your intention is to make sure that the data is really saved before calling the JS function, then the PHP script should containg enough error handling.
If you write the PHP script to return response status code based on the real outcome of save operation, then you can rely on those status codes in ajax response handling (success = ok, error = not ok).
Bu what I usually do, is that instead of using HTTP status codes, I echo "OK" or something similar at the end of succesfull PHP execution (and "ERROR" if there are any errors), and then check for those strings in ajax response handler (hr.responseText in your code).
Maby you have to try this:
setTimeout(function(){
//your function here...
}, 500);
I want to autoupdate page using PHP and Ajax. Right now I have this code on a page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<i class="fa fa-heart-o"></i>
</body>
</html>
When the user clicks on the link it is redirected to another page called "Page-Like.php"
include("config.php");
//get vars
$idSubliminal=$_GET["idSubliminal"];
$idCategoria=$_GET["idCategoria"];
// mysql_query("insert into Rating .... (mysql insert query)
echo "<script>
location.href=\"AudioSubliminal.php?idSubliminal=$idSubliminal&idCategoria=$idCategoria\";
</script>";
What I want is to do this usig Ajax in order to not refresh the page. I know I'm missing the javascript code, but I would like to get some suggestions to complete this script.
Thanks!
All you need is a basic ajax request to achieve your functionality. check the sample request below.
function ajaxpr(){
var URLString="idSub=12&idCat=32";
ajax_request = $.ajax({
type: 'GET',
url: "Page-Like.php",
data: URLString,
dataType : 'html',
context: $(this),
success: function (msg)
{
//perform the required operation after success
});
}
add function onclick on tag . then define that function using :
$.ajax({
type: 'GET',
data: {idSub: "12", idCat: "32"},
url: "Page-Like.php",
dataType: 'JSON',
success: function (response, textStatus, jqXHR) {
//DEFINE FUNCTION HERE
}
});
This is using ajax function without refresh page.
You can use many methods to implement Ajax on you're code.
One of this is jQuery, other is mootools, etc.. Depends of wich library you know or want to learn.
Using ajax to load a page is easy. Follow this link http://www.w3schools.com/ajax/
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Change this to your desired DOM tag
document.body.innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "Page-Like.php?idSub=12&idCat=32", true);
xhttp.send();
}
Now it's just a matter of putting event listener to run loadDoc() function. If the link is dynamic, you can parse the parameter to the function.
However, I notice you have a js script inside your php which will redirect again to AudioSubliminal.php. If this is your desired flow then it's okay. If not, you can create another function
function loadAudioSubliminal(idSub, idCat) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Change this to your desired DOM tag
document.body.innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "AudioSubliminal.php?idSubliminal=" + idSub + "&idCategoria=" + idCat, true);
xhttp.send();
}
and modified loadDoc() to receive a parameter such that idSub and idCat can be passed again. for Example :
function loadDoc(idSub, idCat) {
var xhttp = new XMLHttpRequest();
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Change this to your desired DOM tag
document.body.innerHTML = xhttp.responseText;
// run the function after finished loading Page-like.php
loadAudioSubliminal(idSub, idCat)
}
xhttp.open("GET", "Page-Like.php?idSub=" + idSub + "&idCat=" + idCat, true);
xhttp.send();
}
I have a JavaScript function that I use to start a request. I need the GET parameter of this request, but trying to access it through PHP does not return anything. Any idea why?
I call the JS function in the same PHP file through which I try to access it (index.php)
JavaScript:
function aufloesung() {
var request = new XMLHttpRequest();
request.open("GET", "index.php?screen=1", true);
request.send();
}
PHP File:
<script> aufloesung(); </script>
...
echo $_GET["screen"]
But I don't get the parameter.
Its easy by using jQuery and slicing your index.php & ajaxphp files.
include jquery.js in your index.php:
<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
aufloesung();
</script>
app.js:
function aufloesung() {
$.ajax({
type: "get",
url: "ajax.php?screen=1",
success: function( data ) {
alert( data );
}
});
}
ajax.php:
<?PHP
echo $_GET[ 'screen' ];
?>
You are making two separate HTTP requests.
The first one made by typing a URL into the address bar of the browser doesn't include the query string parameter but is rendered in the page.
The second one, made by using the XMLHttpRequest object, does include the query string parameter, but you don't do anything with the response so you can't see it.
You could, for example:
function aufloesung() {
var request = new XMLHttpRequest();
request.open("GET", "index.php?screen=1", true);
request.addEventListener("load", function (event) {
document.body.appendChild(
document.createTextNode(this.responseText)
);
});
request.send();
}
I have a JS-PHP script where the JS sends information to the PHP script and then displays the PHP response in my HTML page. The script works properly if I display the responseText in one area. When I try to parse the responseText so I can display it in different areas, the script doesn't work. Where am I going wrong?
End of my PHP Script:
...
$expert = $obj;
$pro = $obj1;
$superview = $obj2;
echo json_encode(array(first=>$expert,second=>$pro,third=>$superview));
?>
PHP response:
{"first":1860,"second":1100,"third":340}
JavaScript:
// this calls the php script with the data we have collected from the geolocation lookup
function GEOajax(url) {
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = updatePage;
xmlHttp.send(null);
}
// this reads the response from the php script and updates the page with it's output
function updatePage() {
if (xmlHttp.readyState == 4 && xmlhttp.status==200) {
var response = JSON.parse(xmlhttp.responseText);
document.getElementById("geo").innerHTML='' + response.first;
document.getElementById("geo1").innerHTML='' + response.second;
document.getElementById("geo2").innerHTML='' + response.third;
}
}
HTML:
<div id="geo" ></div>
<div id="geo1" ></div>
<div id="geo2" ></div>
However, if I do not parse the text in JS, but just use the entire responseText, then the script works and displays the responseText in my HTML properly.
JavaScript - no parsing:
// this reads the response from the php script and updates the page with it's output
function updatePage() {
if (xmlHttp.readyState == 4) {
var response1 = xmlHttp.responseText;
document.getElementById("geo").innerHTML = '' + response1;
}
}
How can I parse the PHP response so I can display different variables in different areas in HTML?