Send $_GET vars on click link - PHP & Ajax - javascript

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();
}

Related

Why doesn't ajax show the content of updated JSON?

I am new to JavaScript. What I want to do is sending an ajax request and get the content of a JSON file and simply put it into a div. This is my code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>Ajax 1 - Text File</title>
</head>
<body>
<button id="button">Get Text File</button>
<br><br>
<div id="text"></div>
<script>
document.getElementById("button").addEventListener('click', loadText);
function loadText(){
var xhr = new XMLHttpRequest();
xhr.open('GET', 'users.json', true);
xhr.onload = function(){
if(this.status == 200){
document.getElementById('text').innerHTML = this.responseText;
}
else if (this.status == 404){
document.getElementById('text').innerHTML = 'not found';
}
}
xhr.send();
}
</script>
</body>
</html>
And this is users.json:
[
{
"id":1,
"name":"Rick",
"email":"rick#gmail.com"
},
{
"id":2,
"name":"Negan",
"email":"negan#gmail.com"
}
]
This works fine. But, when I manually updated users.json and change it and refresh the browser, the browser does not show the updated json. It still gives me the previous json file. How can I fix it?
It is possible that the browser is responding with a cached response.
Try appending 'timestamp' so that every time a new request would be made to the server to get updated contents.
document.getElementById("button").addEventListener('click', loadText);
function loadText() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'users.json?ts=' + Date.now(), true);
xhr.onload = function() {
if (this.status == 200) {
document.getElementById('text').innerHTML = this.responseText;
} else if (this.status == 404) {
document.getElementById('text').innerHTML = 'not found';
}
}
xhr.send();
}
<button id="button">Get Text File</button>
<br><br>
<div id="text"></div>
As you have included jQuery in your webpage, I would recommend to use jQuery version of ajax. To disallow the use of the cached results, set cache to false.
$.ajax({
url: 'myurl',
type: 'GET',
dataType: 'json',
data: jsonDataObject,
cache: false, // Appends _={timestamp} to the request query string
success: function(data) {
// data is a json object.
}
});
try check the disable cache checkbox on network panel of the dev tool.
it might be caused by the cache of your web server
You need to pass header
content_type="application/json"

How get steam nickname via javascript

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.

Why is PHP not receiving my AJAX request string?

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'];

Javascript doesn't update document in browser

I have a data.json in my server directory. I am using the following code from w3school to show the data in the browser. W3school Snippet Link
<button type="button" onclick="loadDoc()">Change Content</button>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "/static/data.json", true);
xhttp.send();
}
</script>
</html>
When i click the button, I am able to see the data.json in my webpage. But when i change the data.json and click the button again (without refreshing the page), the updated data isn't shown in the browser.
Am i missing something here?
Well since you are using XMLHttpRequest, you need to make sure that every request is kind of unique, you can do something like:
var uniqueId = (new Date()).getTime()
xhttp.open("GET", "/static/data.json?debug=" + uniqueId, true);
If you were using jQuery ajax (http://api.jquery.com/jquery.ajax/), you just have to pass cache=false, like this:
$.ajax({
cache: false,
//other options...
});
xhttp.open("GET", "/static/data.json?something=RANDOMGUID", true);

Mysql update with JQUERY

I'm having a bit of trouble understanding how to get this to work. I'm loading a page with data from mysql db table using jquery. I'd like to be able to do mysql updates on individual records without refresh. Here's the code I've tried, but can't get the update to work.
index.php
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","data_ajax.php?q="+str,true);
xmlhttp.send();
}
}
Here I have a drop-down in a while loop to retrieve the desired records and post it into a <div id="txtHint"></div>. So far, so good.
Now, I'm putting the following in data_ajax.php to do the mysql update.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".update_button").click(function() {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();
$.ajax({
type: "POST",
url: "update_ajax.php",
data: dataString,
cache: false,
});
return false;
});
});
</script>
Where I have a text link <a href='#' id='".$row['id']."' class='update_button'>".$label."</a> that should call the action above to do the update. All this does it jumps the page to the top and nothing happens. The update_ajax.php doesn't seem to get called when link is clicked. I know it's something simple I'm missing. Any help would be appreciated.
What I would suggest is including jQuery directly in index.php, which would then allow you to use event delegation to handle most of the work.
With jQuery being included in index.php, you can use jQuery to do the showUser ajax request too.
function showUser(str) {
if (str == "") {
$("#txtHint").empty();
return;
}
$("#txtHint").load("data_ajax.php?q=" + str);
}
$(document).ready(function () {
$("#txtHint").delegate(".update_button", "click", function () {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();
$.ajax({
type: "POST",
url: "update_ajax.php",
data: dataString
});
return false;
});
});
Update your version of jQuery. Your example shows you using version 1.4.2.
The $.ajax shorthand code was introduced after version 1.5.

Categories

Resources