Retrieve data from PHP file by ajax - php

I found a script on the net, which makes two PHP files interact.
Specifically, the first file (details.php) shows some statistical data of a football match. If the match is in progress, I show the live score by running another PHP file (live_score.php). The two files interact thanks to the following script, present in the details.php file
$(document).ready(function(){
setInterval(function() {
var id=<?php echo"$id"?>;
var x = "<?php echo"$cod"?>";
$("#risultato").load("live_score.php", {var:id, x});
refresh();
}, 5000);
});
from details.php, I call live_score.php passing it some parameters.
These parameters are used by the live_score.php file to retrieve the score and other information in real time.
To print the result on the screen in details.php, I use a simple ECHO inside the live_score.php file, but I would like to retrieve this data and the others in a different way, via ajax if possible, but I don't know if it can be done and how....can you help me please? Thank you

I think you have already solved half of your problem. From your code , you should first remove the "refresh()" to stop reloading the page every 5 seconds.
then make sure that the the payload is correct, because the word "var" is a reserved keyword in JavaScript.
HTML
<div id="risultato"></div>
Javascript
$.ajax({
url: "live_score.php",
type: "POST",
data: { id, x},
success: function(response) {
//this response will be the data from "live_score.php"
//now assuming that
// 1. you use vanilla javascript with plain html + css
// 2. the returning reponse looks like this
// [{"teamName": "theTeam1", "score": 10}, {"teamName": "theTeam2", "score": 10}]
//Clear the current score
$("#risultato").empty();
// Now iterate through the response,
$.each(response, function(index, item) {
var teamName = item.teamName;
var score = item.score;
var html = "<p><strong>" + teamName + "</strong>: " + score + "</p>";
// this code will append (add to the end) the data iterated
$("#risultato").append(html);
});
},
error: function(xhr, status, error) {
//if your code or ajax call had any problems ,
//you can debug here and write error handling logic here, like
if(error){
alert("failed to fetch data");
console.log(error);
}
}
});

Related

How to set the ajax success result value to PHP variable in same page

function submitID(){
// some codes working in here....
var text="A_1";
var name="test";
$.ajax({
url: 'callmethod.php',
type: 'post',
data: {'action':'methodname', 'text': text, 'name':name},
success: function(data, status) {
var results = JSON.parse(data);
for(var i = 0; i < results.length; i++){
var id= results[i]['ID'];
alert(id); --- I got the value of ID in here -- example output value : Hello
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
});
}
What I would like to do in here, I got the value of var id but I want to set as the PHP variable $valuephp= >>> id <<< how can I do for that? please help me to advice.
In short, its not possible, like that to set ajax response to php variable because
PHP runs - Server Side before page load and builds the page
JS (and thus AJAX) runs - Client Side AFTER the server gave your browser the page
So what you can do ?
You post data to your server with your ajax call, so in server side, you can set php variable.You can store this in a session variable if you need it later, or in the database.
You can store ajax result in php variable by embedding ajax result div into php tag.
Assign ajax response variable to js variable and then just assign it to your html div containing php variable as:
$('#result').text('test');
<?php
$result='<div id="result"></div>';
// Here you embed div in php tag and store in php varible
?>
In your ajax call, after success or error
<?php $variablephp = "<script>document.write(111)</script>" ?>
Now you can access that variable, make sure that variable actually used after ajax call
<?php echo $variablephp; ?>

DOM Parser Call with jquery ajax

I have a quite complicated problem:
I use the PHP Simple HTML DOM Parser to fetch some price data from different webshops.
The data is shown on my website. The problem is that I need data from about 10 shops with about each 50 products. So about 500 links all in all.
The Links are retrieved from an CSV.
I want it like this:
Open the csv -> retrieve the link -> parse the price data from the link -> show it on the website
My first try was this:
var file = 'shops.csv';
Papa.parse(file, {
delimiter: ";",
download: true,
header: false,
dynamicTyping: true,
complete: function(results) {
$.each(results.data, function(i, item){
$.ajax({
type: 'POST',
url: "parser.php",
data: {url:item[4]},
success: function(data,status){
if(data){
var output = '' + data +'';
$('table tbody tr[data="'+item[1]+item[3]+'"] td').append(output);
}
},
async:true
});
});
}
});
Now all links are parsed synchronous which crashes the server. When the ajax call is done asynchronous the data is only shown when the last call is done.
The perfect way should be step by step... get the link -> get the price -> show the price -> next.

Counting clicks changing link href

I asked this question but did not explain it thoroughly. I have a regular link:
Click Me
I want the change the href after the link is clicked 10 times not by the individual use but clicked 10 total times by all users.My jquery is obviously flawed but here is what i have:
var count = 0;
$(document).ready(function(){
$('a').click(function(){
count++;
if(count > 10){
$('a').attr("href","https://www.yahoo.com");
}
});
});
I am new to jQuery but from what ive read cookies and local storage store individual users information not the total websites information. So how could i use ajax with a database to do this? maybe even php?
You have a huge fundamental misunderstanding of how JavaScript works.
Firstly, when someone clicks that link, they're going to be navigated away from your page unless you do something to prevent that (e.preventDefault or return false in jQuery). Once they're navigated away, your counter is lost because is stored locally, in memory, for the life of the page.
Secondly, even if the counter wasn't cleared, or you stored the counter in a cookie, or localStorage, it will only count for a single user. If you want to count the clicks by all users, you're going to have to do that server side. i.e., in PHP.
So... how do we do that? Well, as I said before, when a user clicks that link, they're going to be sent to Google. Your site will have no knowledge of what has occurred.
We have two options to deal with this. We can intercept the click, and use AJAX (more appropriately "XHR") to send a request back to your server, where you can log the click, before forwarding them off to Google.
Or, you re-write the URL to something like /log_click.php?forward=http://google.com. Now when the user clicks the link, they will actually be sent to your log_click.php script, where you can log the click to your database, and then use $_GET['forward'] in combination with header('location: ...') to forward them off to their destination. This is the easiest solution. Through some JavaScript hackery, you can hide the link so that when they mouse over it, they won't even know they're being sent to your site (Google does this).
Once you've accumulated your 10 clicks, you again use PHP to write out a different HTML link the next time someone views that page.
HTML
<a href='http://www.google.com' data-ref='99'>Click Me</a>
Javascript
$("a").click(function() {
var _this = $(this);
var ref = $(this).data('ref');
$.ajax({
url: '/click_url.php',
type: 'POST',
data: {id:ref}
success: function(href) {
if(href != '')
_this.attr("href",href);
}
});
}
PHP (click_url.php)
if($_POST['id'] > 0){
$id = $_POST['id'];
//count increment
$sql = "UPDATE table SET count = count + 1 WHERE id = '$id'";
mysql_query($sql);
//get row count
$sql = "SELECT * FROM table WHERE id = '$id' LIMIT 1";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
//if count > 10 , return new url
if($row['count'] > 10){
die($row['href']);
}
}
While clicking the link you can call an ajax request and increment the count in the server. So that u should remove link from href and call manually by using javascript window.location.href each time. Hope that helps
var count = 0;
$(document).ready(function(){
$('a').click(function(e){
e.preventDefault();
count++;
if(count > 10){
$('a').attr("href","https://www.yahoo.com");
}
});
});
and use ajax like below
//send set state request
$.ajax({
type: "POST",
contentType: "text/xml; charset=utf-8",
datatype: "xml",// you can set json and etc
url:"your php file url",
data: {test:test1},// your data which you want to get and post
beforeSend: function (XMLHttpRequest) {
// your action
},
success: function (data, textStatus, XmlHttpRequest) {
// your action },
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
for more deatils see Ajax
Mark's answer is more useful, even you want to implement for the sake of some constraints then try below with jQuery 1.9
I have implemented for 3 clicks, AFAIU you need to change the URL on every 3rd successive click
var c=0;
$(document).on('click', 'a#ten', function(e){
c++;
alert('clicked ' + c + ' times');
if(c%3 == 0) {
$('a').attr("href","https://www.yahoo.com");
alert('changed');
c = 0;
}
e.preventDefault();
})
working DEMO
You must save no of times that link has been clicked in the database with php. when you render the link(with php) check the no of times it has been called before and decide what link to render.
Click Me
write this javascript in the page wher you place your link
$(function()
{
$('.mylink').click(function()
{
$.ajax({
type: "POST",
url: "listening/end/point", // enter your counting url here
async: false
);
});
});
And in server on the listening end point write php script to store no of times that link has been called.

Jquery:create a dictionary to autocomplete all inputs

i want to add an smart autocomplete to my project in which when ever user is typing a word in any input its autocompleted from his own dictionary.
his owner dictionary is built by saving every word he ever submit to server something like (array_values($_POST))
my current JS
$('input.complete').live('keyup.autocomplete', function(){
var hi=$(this).val().toUpperCase();
var was=this;
$(this).autocomplete({
//PROBLEM Should i consider to change source from ajax/mysql to different source ?
//since there gona be too many requests ??
source: function(request, response) {
$.ajax({ url: '<?=base_url()?>ajax/ac',
//PROBLEM how can i set term=word currently being edited..(start=' ',end=pointerpos)
data: { 'term': this.term },
dataType: "json",
type: "POST",
success: function(data){
if(data.length){
//response(data);
//Commented out cause i dont wana display dropdown.. just typeahead.
if(data[0]['value'].substr(0,hi.length).toUpperCase()==hi){
$(was).val(data[0]['value']);
//currently working with single word inputs..once i get how to select only current word will edit these..
was.selectionStart=hi.length;
was.selectionEnd=data[0]['value'].length;
}
}
}
});
},
select: function(event, ui){},
minLength: 2,
delay: 500
});
As u can see i have 2 problems
Question
how can i select current word that user is typing ?
is this a good approach to reach my goal, or i should consider different plugin
You are using PHP language as well. So in my opinion you can use PHP to solve your problem more easily. Let's say you have php function get_word($excerpt) in get.php file. So,
<?php
get_word($_POST['excerpt']);
function get_word($excerpt) {
// Find exact word from database or array using given $excerpt
// and return complete word.
return $complete_word;
}
?>
And in your jquery (assuming input field as .input),
$(document).ready(function() {
$('.input').live('keyup',function() {
var excerpt = $(this).val();
$.post("get.php", {excerpt:excerpt}, function(data) {
// do anything with data.
$('.input').val(data);
});
});
})
For more precise, you can get bunch of matching words from get.php file, and display list of words to be selected.

Send a request to a php page and then get back results using ajax

I have a script where i am trying to send some location information to a php page, carry out a mysql search query and get the results back without going to another page.
my php works fine, and i have had the page working that it redirects to the php page, however when i try and use the code below, i do not get any results passed back.
Javascript code
function phpRedirect(loc) {
// var radius = get('r'); // Retrieve GET values for search radius and
// var numResults = get('n'); // number of results
var radius = 10; // Retrieve GET values for search radius and
var numResults = 5; // number of results
var latitude = loc.coords.latitude; // Get long, lat and accuracy from
var longitude = loc.coords.longitude; // location object
var accuracy = loc.coords.accuracy;
var xmlHttp = new XMLHttpRequest(); //not the cross browser way of doing it
xmlHttp.open("GET", "find.php?lat=" + latitude + "&long=" +
longitude + "&acc=" + accuracy + "&r=" + radius
+ "&n=" + numResults, true);
xmlHttp.send(null);
}
$(function ()
{
$.ajax({
url: 'find.php', //the script to call to get data
type: "post",
data: { getData: true },
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var name = data[0];
$('#output').html("<b>username: </b>"+username);
}
});
});
function error(loc) {
// This is called if the location can't be found.
document.write("Error finding GPS location");
}
// Use navigator to get current user location. If found, calls 'phpRedirect()',
// If not available calls 'error()'. Includes timeout and ensures highest acc.
navigator.geolocation.getCurrentPosition(phpRedirect, error, {maximumAge:60000, timeout:5000, enableHighAccuracy:true});
<div id="output">this element will be accessed by jquery and this text replaced </div>
Below is the output from my php query,
$result=mysql_query($query) or die (mysql_error());
while($row=mysql_fetch_assoc($result)) $data[]=$row; // Turn result to array
$acc_package = array('location_accuracy'=>"$accuracy"); // Include result array
$output[] = $acc_package; // and accuracy value inside
$output[] = $data; // an output array.
print(json_encode($output)); // Convert output array to json format and print
Which gives the following results
[{"location_accuracy":"122000"},[{"username":"bobbyj","distance":"0.484367160806139"}]]
Sam, I have a few suggestions for you.
First, the jQuery library is great and the AJAX module works amazing :) It's great that you are using it! No need to mix that old XMLHTTP junk with it (they do basically the same thing). So get rid of that and replace it with jQuery ajax.
Let's start with something really basic:
$.ajax({
url: 'find.php',
type: "POST",
data: { lat: lattitude }
}).done(function( msg ) {
alert(msg);
});
Put your other variables in the data: as well.
On your PHP page, try a simple var_dump($_POST); so you can see what is coming through. The AJAX should make an alert with contents of the PHP page.
Work your way up from this with your Mysql :)

Categories