The code I have is at http://www.lesha.wemakesites.ru/
What it does is givng out reversed string and counting times the servise was used.
What I wanna do is that once the page is opened and somebody runs the code on any other device I can see the total number changed without reloading the page.
To do so I'm using 2 ajax-requests of following view:
var ajax_result = $.ajax({
url: 'count.php',
method: 'post',
success: function () {}
})
var ajax_write = $.ajax({
url: 'count.txt',
success: function (data) {
document.getElementById("total_global").style.display = ("none");
document.getElementById("global").style.display = ("inline");
document.getElementById("global").style.color = ("red");
document.getElementById("global").innerHTML = data;
}
In count.php I have:
<?php
$file = 'count.txt';
$file_open = file_get_contents($file);
$file_open = (int)$file_open;
$file_open = $file_open + 1;
file_put_contents($file, $file_open);
echo($file_open);
?>
and after I dynamically show the result with js.
Nevertheless I don't see changes when I run it from my phone until I reload the page at my PC.
Related
I am building my best attempt at a twitter clone and have run into a bit of a problem. I want to be able to click on a post and, without a page refresh, display that post in the overlay of the page (as you would on a twitter feed to look at replies, etc.).
In script.js, I check for a click and try to change the url.
$('body').on("click", ".chirp", function(){
var uid = $_GET['id'];
var pid = $(this).attr("id");
var pidSplit = pid.split("chirp");
var messageID = pidSplit[1];
var obj = {foo: "status"};
$('.chirpOverlay').addClass("active");
window.history.pushState(obj, "Status", "profile.php?id="+uid+"&status="+pid);
});
The javascript works as intended...but as I will soon find out, the victory is short-lived.
In profile.php, I attempt to GET the status id from the URL parameter.
<?php
$status_id = $_GET['status'];
$sql = $db->query("SELECT * FROM chirps WHERE id='$status_id'");
if (mysqli_num_rows($sql) > 0) {
$c = $sql->fetch_object();
}
?>
This doesn't work because, as I've learned, using 'window.history.pushState' only changes the url- but doesn't load the page. Thus the $_GET statement fails. I need a way to get the id of the post I click on into profile.php without a page refresh. Even if it means taking a different approach (instead of using a URL parameter).
PS: I tried to do an XMLHttpRequest as well- to no avail. :(
Thanks in advance!
$('body').on("click", ".chirp", function(){
var uid = $_GET['id'];
var pid = $(this).attr("id");
var pidSplit = pid.split("chirp");
var messageID = pidSplit[1];
var obj = {foo: "status"};
$('.chirpOverlay').addClass("active");
$.ajax({
url: "profile.php?id="+uid+"&status="+pid,
type: "GET",
data: obj,
dataType: "html",
success: function(data){
console.log(data);
}
});
});
You need to just get something up and going that works and then you can add more to it as you figure things out. This should give you a good starting place.
Here are your two files. Make sure they are both in the same directory.
You will need to make sure you have a jquery version loaded. Put this on whatever page you are calling the script.js from.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
script.js
$(document).ready(function(){
$('body').click(function(){
var id; //define your id.
var pid; //define your pid.
var datastring = 'id=' + uid + '&status=' + pid;
console.log(datastring);
$.ajax({
url: 'profile.php',
type: 'POST',
cache: false,
data: datastring,
dataType: 'json',
success: function(data){
console.log('Made it to the success function: ' + data);
if (data) {
//It works, do something.
console.log(data);
} else{
//It does not work, do something.
console.log('Your ajax failed to get the info from your php page. Keep troubleshooting');
}
}
});
});
});
profile.php
<?php
/*
$status_id = $_POST['status']; //This needs to be sanitized and validated.
$sql = $db->query("SELECT * FROM chirps WHERE id='$status_id'"); //This is unsafe sql practice.
if (mysqli_num_rows($sql) > 0) {
$c = $sql->fetch_object();
}
echo json_encode($c); //This is what gets sent back to script.js
*/
echo 'You made it to your php page.';
?>
A few things:
You can not call any php variable from within your js. var uid = $_GET['id']; does not work.
Any value that you pass to the php page needs to be validated to make sure it is a legitimate value.
Your SQL query is prone to sql injections. Please read up on how to parameterize your queries. Good Mysqli Practices
I have finally found a AJAX-based solution to my problem.
I created a new php file called "chirp_open_ref.php" and added this ajax to script.js:
var datastring = 'status=' + messageID;
$.ajax({
url: "chirp_open_ref.php",
type: "POST",
data: datastring,
cache: false,
dataType: "text",
success: function(data){
$('.chirp-container').html(data);
}
});
Inside of 'chirp_open_ref.php':
<?php
require 'core.inc.php';
if (isset($_POST['status']) && isset($_SESSION['user_id'])){
$chirp_id = $_POST['status'];
$c = "";
$sql = $db->query("SELECT * FROM chirps WHERE id='$chirp_id'");
if (mysqli_num_rows($sql) > 0){
$c = $sql->fetch_object();
}
include'chirp.inc.php';
}
?>
'chirp.inc.php' is simply a template for the layout/structure of each post.
This works like a charm, but I am always open to any criticism of how I am performing this. Thanks for all the help guys!
my website has an option of country like for different country the website layout is different. it is running on the basis of sessions if session is not set the user will be redirected to index to select a country then will be redirected from the page where he originally came from. here's the code
my session_check_client.php file that is included in every file except index
<?php
session_start();
if(!isset($_SESSION['country']))
{
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
header("location:index.php?return_uri=$actual_link");
}
?>
now what happens is when i go back to home page i wanna check whether this requested has some return parameter or just user has visited he website for the first time. there are two button for two countries of which i am showing the code.
function canada(){
$.ajax({
type: 'post',
url: 'ajax_country.php?country=canada',
success: function (data) {
var $_GET = <?php echo json_encode($_GET);?>;
if($_GET){
//window.location.href=$_GET['return_uri'];
alert($_GET['return_uri']);
}
else {
window.location.href = "home.php";
}
}
});
}
function us(){
$.ajax({
type: 'post',
url: 'ajax_country.php?country=us',
success: function (data) {
var $_GET = <?php echo json_encode($_GET);?>;
if($_GET){
//window.location.href=$_GET['return_uri'];
alert($_GET['return_uri']);
}
else {
window.location.href = "home.php";
}
}
});
}
now the problem is when i am alerting the value of $_GET['return_uri'] it is giving me a false value
e.g my return_uri value is http://localhost/interfold/products2.php?category=Aprons&id=57725599688 it actually shows the whole value in return_uri in index page like http://localhost/interfold/products2.php?category=Aprons&id=57725599688 but when is get the url value using javascript it is onlye giving me the value http://localhost/interfold/products2.php?category=Aprons it is missing the $ and afterwards parts!!! any recommendations?
Since you are only using super global variables, you can directly print a JS variable above the function you are describing:
var actual_link = "<?php echo "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; ?>";
function postCountry( country ){
$.ajax({
type: 'post',
url: 'ajax_country.php?country=' + country,
success: function (data) {
if(actual_link){
//window.location.href=actual_link;
alert(actual_link);
}
else {
window.location.href = "home.php";
}
}
});
}
postCountry('us');
postCountry('canada');
I'm trying to call an AJAX query and have had lots of trouble recently.
Im trying to call a api that I have custom made myself, it displays this when the url api/reverse/test - tset (is just uses a php function to reverse the text given in the slug3.
That function works fine, just wanted to give some back on what gets requested.
reverse.php - HTML File
<textarea id="input"></textarea>
<div id="output">
</div>
index.js - All of my jQuery and AJAX
$(document).ready(function(){
var $input = $('#input');
var $output = $('#output');
$input.on('keyup', function(){
var text = $input.val();
var url = 'http://coder.jekoder.com/api/?area=reverse&text='+text;
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
success: function(data) { var output = data; },
error: alert('fail')
}) // End of AJAX
$output.html = output;
});
});
api.php - PHP file being called
<?php
$area = $_GET['area'];
if ($area == 'reverse') {
if (isset($_GET['text']) ) $text = $_GET['text'];
else $text = 'Hello';
echo strrev($text);
}
It's then supposed to take the output variable and display that in a div but that's not the main thing that matters.
error removed - was trying to see if it fixed it
There are several issue I found:
Jquery:
var text = $('#input').val(); // if you are getting value from any inputbox - get value using .val() function
var url = 'http://localhost/test.php?data='+text; // pass data like this ?data='+text
// AJAX START
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
async: true,
success: function(data) { var output = data; alert(output)},
error: function(data) { alert('fail') }
});
In php you ca get data like this:
echo $_GET['data'];
exit;
Try this. Scope of variable output is within the success call and you are using it outside the ajax call.
$(document).ready(function()
{
var $input = $('#input');
var $output = $('#output');
$input.on('keyup', function()
{
var text = $input.val();
var url = 'http://coder.jekoder.com/api/?area=reverse&text='+text;
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
success: function(data) { var output = data; $output.html = output;},
error: alert('fail')
}) // End of AJAX
});
});
Am trying to generate multiple line charts at one go using the code below. However, it isn't working. What would be the best way to generate graphs using a for/while or any other looping mechanism? I have many charts to generate.
var db_query = Array();
db_query[1] = <?php echo json_encode($db_query_1) ?>;
db_query[2] = <?php echo json_encode($db_query_2) ?>;
var chartConfig1 = clone(chartConfigLineOne);
var chartConfig2 = clone(chartConfigLineOne);
for(var i=1, len=2; i <= len; i++) {
/* chart initialization */
var chart_num = "chart" + i.toString();
var plot_num = "plot" + i.toString();
var chartConfig_num = "chartConfig" + i.toString();
/*alert(chart_num);
alert(plot_num);
alert(chartConfig_num);*/
chart_num = AmCharts.makeChart(plot_num, chartConfig_num);
$.ajax({
type: 'POST',
url: "query_db.php",
data: {'db_que': db_query[i]},
dataType: 'json',
context: document.body,
global: false,
async: true,
success: function(data) {
//alert(data);
chart_num.dataProvider = data;
chart_num.validateNow();
}
});
}
UPDATED CODE
<script type="text/javascript">
var chartNameList = ['chart1','chart2'];
var divId = ['plot1','plot2'];
var configList = ['chartConfig1','chartConfig2'];
var dbQuery = [];
var chartConfig1 = clone(chartConfigLineOne);
var chartConfig2 = clone(chartConfigLineOne);
dbQuery[0] = <?php echo json_encode($db_query_1) ?>;
dbQuery[1] = <?php echo json_encode($db_query_2) ?>;
/* chart initialization */
for(var i =0; i < 2; i += 1) {
//window["chart"+i] = createChartObj(divId[i],configList[i]);
execDbQuery(divId[i],configList[i],dbQuery[i],chartNameList[i]);
}
</script>
/**
* Execute of DB query
*/
function execDbQuery(divId, configObj, dbQuery, chartObj) {
chartObj = AmCharts.makeChart(divId, configObj);
$.ajax({
type: 'POST',
url: "query_db.php",
data: {'db_que': dbQuery},
dataType: 'json',
context: document.body,
global: false,
async: true,
success: function(data) {
//alert(data);
chartObj.dataProvider = data;
chartObj.validateNow();
}
});
}
As many comments correctly pointed out, you should probably start with rethinking your approach to data loading. Passing SQL queries in from client-side is asking for trouble. Will you be able to properly sanitize your queries to guard against malicious code? You can't be sure.
It's far more reasonable to move your DB access layer to PHP. You can pass in parameters needed for PHP script running on server to identify what needs to be loaded from DB and construct and execute actual SQL queries.
I.e.: query_db.php?chart_id=5
It would be up for PHP script to determine what to do. Given that you're currently using PHP to format those SQL queries, I can hardly image it can be a problem.
This brings us to another issue. Your current setup will run multiple AJAX requests simultaneously. While it's probably OK in the example you posted which has two charts, it can bog down the performance if you you have, say, 30 charts you need to load data for.
The solution would be to daisy-chain the loading. Do not start loading of another chart, until the previous one finishes loading. I.e.:
var charts = [ {
"name": "chart1",
"div": "plot1",
"config": clone( chartConfigLineOne ),
"query": <? php echo json_encode( $db_query_1 ) ?>
}, {
"name": "chart2",
"div": "plot2",
"config": clone( chartConfigLineOne ),
"query": <? php echo json_encode( $db_query_2 ) ?>
} ];
// do whatever modifications to each chart's config you need here
// ...
// function that creates the chart
function processNextChart() {
if ( charts.length ) {
var chart = charts.shift();
$.ajax( {
type: 'POST',
url: "query_db.php",
data: {
'db_que': chart.query
},
dataType: 'json',
context: document.body,
global: false,
async: true,
success: function( data ) {
chart.config.dataProvider = data;
chartObj = AmCharts.makeChart( chart.div, chart.config );
setTimeout( processNextChart, 100 );
}
} );
}
}
// process first chart
processNextChart();
Please note how I simplified your whole chart array with a single array that holds all applicable data.
Please note, that the above code is not live-tested and is meant as a guiding point for your own implementation.
Do not make ajax calls inside the for loop. It's a burden on server. The less calls you make, the more responsive is your ui. So, the better way to implement what you want is to get all data for all graphs in one ajax call and on success to iterate through the data building your graphs with AmCharts.makeChart.
i want to redirect from page a to page profile and in between there is a post session on them. in this case let's say the data is variable $name in string. so far my code is like this on page a
jQuery("#result").on("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#searchid').val(decoded);
//the ajax script
$.ajax({
type: 'POST',
url: 'b.php',
data: 'result='+$name,
success: function() {
window.location.href = "profile.php"; // replace
}
});
});
and on page b the code is:
<?php echo $_POST['result']?>
the outcome should be the value from result in which determined on page a.
but so there is an error message saying unidentified index. so where am i doing wrong?
Could it be, that your data parameter is wrong?
I have my ajax calls as folowing:
jQuery.ajax({
type: "POST",
url: "b.php",
data: {
result: $name
},
success: function() {
window.location.href = "profile.php"; // replace
}
});
It is a new request after the redirect. In order to access the result you need to sotre it in som kind of session or pass it again.
You can pass it like this, then it will be in $_GET
success: function(data) {
window.location.href = "profile.php?result="+data; // replace
}