I have a mysql feedback database constructed like this:
name | location | feedback
Ryan | England | great support
Obviously there's more entries than that. I am trying to build a feedback div, where it displays a new feedback item every 10 seconds via ajax.
So I have constructed this:
$(document).ready(function(){
new get_fb();
});
function get_fb(){
var feedback = $.ajax({//Ajax
type: "POST",
url: "feedback.php",
async: false
}).responseText;//end of ajax
$('div.feedback-box').html(feedback).delay(10000).queue(function() {
new get_fb();
});
}
And here's my PHP file:
$result = mysql_query("SELECT * FROM feedback ORDER BY RAND() LIMIT 0,1");
while($row = mysql_fetch_array($result))
{
$name = $row['name'];
$location = $row['location'];
$feedback = $row['feedback'];
echo "
<p>Name: $name, Location: $location, Feedback: $feedback.</p>
";
}
However, this only shows two. It doesn't keep showing new ones, it purely shows the first then the second and stops.
What am I doing wrong? Thanks :)
Are you going to want to do a setInterval()?
setInterval(function(){get_fb();}, 10000);
Or:
setInterval(get_fb, 10000);
Or, if you want it to run only after successfully completing the call, you can set it up in your .ajax().success() callback:
function get_fb(){
var feedback = $.ajax({
type: "POST",
url: "feedback.php",
async: false
}).success(function(){
setTimeout(function(){get_fb();}, 10000);
}).responseText;
$('div.feedback-box').html(feedback);
}
Or use .ajax().complete() if you want it to run regardless of result:
function get_fb(){
var feedback = $.ajax({
type: "POST",
url: "feedback.php",
async: false
}).complete(function(){
setTimeout(function(){get_fb();}, 10000);
}).responseText;
$('div.feedback-box').html(feedback);
}
Here is a demonstration of the two. Note, the success works only once because jsfiddle is returning a 404 error on the ajax call.
http://jsfiddle.net/YXMPn/
setInterval(function()
{
$.ajax({
type:"post",
url:"myurl.html",
datatype:"html",
success:function(data)
{
//do something with response data
}
});
}, 10000);//time in milliseconds
You could try setInterval() instead:
var i = setInterval(function(){
//Call ajax here
},10000)
This worked for me
setInterval(ajax_query, 10000);
function ajax_query(){
//Call ajax here
}
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!
I've got this variable $type and I want it to be month or year.
It should be changed by pressing a div.
I've tried creating an onclick event with an ajax call.
The ajax call and the variable are in the same script (index.php)
Inside the onclick function:
var curr_class = $(this).attr('class');
$.ajax({
type: "POST",
url: "index.php",
data: {
type: curr_class
},
dataType: 'text',
success: function(data) {
// Test what is returned from the server
alert(data);
}
});
But the alert returns the whole html page.
When I console.log the data (create a var data = { type:curr_class }) and console.log *that data* it returnstype = month` (which is correct)
while I just want it to return month or year
So on top of the page I can call
if(empty($_POST['type'])){
$type = 'month';
} else {
$type = $_POST['type'];
}
and change the PHP variable so I can use it in the rest of my script.
But how can I accomplish this?
With kind regards,
as you are sending request to the same page so as a result full page is return .You will have to send it to another page and from that page return the type variable
if(empty($_POST['type'])){
$type = 'month';
} else {
$type = $_POST['type'];
echo $type;
keep this code in separate file and make an ajax call to that page
//Try This It's Work
Get Value
Get Value
$(".btn-my").click(function(){
var curr_class = $(this).data('title');
$.ajax({
type: "POST",
url: "index.php",
data: {
type: curr_class
},
dataType: 'text',
success: function(data) {
// Test what is returned from the server
alert(data);
}
});
});
I have a mysql feedback database constructed like this:
name | location | feedback
Ryan | England | great support
Obviously there's more entries than that. I am trying to build a feedback div, where it displays a new feedback item every 10 seconds via ajax.
So I have constructed this:
$(document).ready(function(){
new get_fb();
});
function get_fb(){
var feedback = $.ajax({//Ajax
type: "POST",
url: "feedback.php",
async: false
}).responseText;//end of ajax
$('div.feedback-box').html(feedback).delay(10000).queue(function() {
new get_fb();
});
}
And here's my PHP file:
$result = mysql_query("SELECT * FROM feedback ORDER BY RAND() LIMIT 0,1");
while($row = mysql_fetch_array($result))
{
$name = $row['name'];
$location = $row['location'];
$feedback = $row['feedback'];
echo "
<p>Name: $name, Location: $location, Feedback: $feedback.</p>
";
}
However, this only shows two. It doesn't keep showing new ones, it purely shows the first then the second and stops.
What am I doing wrong? Thanks :)
Are you going to want to do a setInterval()?
setInterval(function(){get_fb();}, 10000);
Or:
setInterval(get_fb, 10000);
Or, if you want it to run only after successfully completing the call, you can set it up in your .ajax().success() callback:
function get_fb(){
var feedback = $.ajax({
type: "POST",
url: "feedback.php",
async: false
}).success(function(){
setTimeout(function(){get_fb();}, 10000);
}).responseText;
$('div.feedback-box').html(feedback);
}
Or use .ajax().complete() if you want it to run regardless of result:
function get_fb(){
var feedback = $.ajax({
type: "POST",
url: "feedback.php",
async: false
}).complete(function(){
setTimeout(function(){get_fb();}, 10000);
}).responseText;
$('div.feedback-box').html(feedback);
}
Here is a demonstration of the two. Note, the success works only once because jsfiddle is returning a 404 error on the ajax call.
http://jsfiddle.net/YXMPn/
setInterval(function()
{
$.ajax({
type:"post",
url:"myurl.html",
datatype:"html",
success:function(data)
{
//do something with response data
}
});
}, 10000);//time in milliseconds
You could try setInterval() instead:
var i = setInterval(function(){
//Call ajax here
},10000)
This worked for me
setInterval(ajax_query, 10000);
function ajax_query(){
//Call ajax here
}
I am working on an e-commerce project for practice and right now I am building product filters. So I have three files
catalogue.php
It basically shows all the products.
product filters on left and displays products on right. When user checks a box then AJAX call is made.
productsfilter.js
It contains Javascript and AJAX calls.
var themearray = new Array();
$('input[name="tcheck"]:checked').each(function(){
themearray.push($(this).val());
});
if(themearray=='') $('.spanbrandcls').css('visibility','hidden');
var theme_checklist = "&tcheck="+themearray;
var main_string = theme_checklist;
main_string = main_string.substring(1, main_string.length)
$.ajax({
type: "POST",
url: "mod/product_filter.php",
data: main_string,
cache: false,
success: function(html){
replyVal = JSON.parse(myAjax.responseText);
alert(replyVal);
}
});
product_filter.php
It is the PHP script called by the AJAX call.
$tcheck = $objForm->getPost('tcheck');
if(!empty($tcheck)) {
if(strstr($tcheck,',')) {
$data1 = explode(',',$tcheck);
$tarray = array();
foreach($data1 as $t) {
$tarray[] = "adv.attribute_deterministic_id = $t";
}
$WHERE[] = '('.implode(' OR ',$tarray).')';
} else {
$WHERE[] = '(adv.attribute_deterministic_id = '.$tcheck.')';
}
}
$w = implode(' AND ',$WHERE);
if(!empty($w))
{
$w = 'WHERE '.$w;
}
$results = $objCatalogue->getResults($w);
echo json_encode($results);
So product_filter.php returns an array of product_ids retrieved from the database and gives it back to AJAX. Now the problem is: that array of product ids I got from AJAX call, how do I use it in catalogue.php?
As I got {["product_id" : "1"]} from product_filter.php, I want to use this id in catalogue.php and find the related attributes and display the product details.
How can I pass this array to my catalogue.php page so that it can use this array and call further PHP functions on it?
If the question is unclear then kindly say so, and I will try to explain it as clearly as I can. Help would be much appreciated.
It seems you want to get data from one php and send it to a different php page then have the ajax callback process the results from that second page.
You have at least 2 options
Option 1 (the way I would do it)
In product_filter.php, near the top, do this
include('catalogue.php');
still in product_filter.php somewhere have your function
function getFilterStuff($someDataFromAjax){
// ... do some stuff here to filter or whatever
$productData = getCatalogueStuff($results);
echo json_encode($productData);
exit;
}
In catalogue.php somewhere have that function
function getCatalogueStuff($resultsFromFilter){
// ... get product data here
return $productData;
}
Then in your Ajax do this:
$.ajax({
type: "POST",
dataType: "json", // add this
url: "mod/filter_products.php",
data: main_string,
cache: false,
success: function (response) {
replyVal = response;
alert(replyVal);
}
});
Option 2
Nested ajax calls like this:
$.ajax({
type: "POST",
dataType: "json", // add this
url: "mod/filter_products.php",
data: main_string,
cache: false,
success: function (filterResponse) {
$.ajax({
type: "POST",
dataType: "json", // add this
url: "catalogue.php",
data: filterResponse,
cache: false,
success: function (catalogueResponse) {
alert(catalogueResponse);
}
});
}
});
I have the following code for requesting data from a mysql database:
jquery/javascript:
ajaxGet = function (url) {
var result = $.ajax({
url:url,
type:"POST",
data:{action:'call_this'},
dataType: 'json',
success:function(data) {
}
});
return result;
}
php:
<?php
if($_POST['action'] == 'call_this') {
// call waypoint search
include ('link.php');
$sql="SELECT * FROM Waypoints"; //data in table Waypoints
$result = mysqli_query($link,$sql);
$wptdata=array();
while($line = mysqli_fetch_assoc($result)){
$wptdata[] = $line;
};
mysqli_close($link);
echo json_encode($wptdata);
};
?>
To get the data as a javascript array, I would like to be able to say something like this:
wpdata=ajaxGet('datacall.php');
Suggestions on how to get this to work? If I put alert(data[0].name) within the success function, it comes up with the right result, so the call to the database table is definitely working. But I can't seem to figure out how to get the array out of the $.ajax call.
Thanks for any help- have been searching through other questions, and just came seem to find a solution. I would like to keep the ajaxGet function if at all possible- once I get it working, I will be able to update it so that it is flexible as to what kind of data are called from the table.
The answer is no. You cannot do this is any way that is sane. Use callbacks/promises - that's the way to go!
function ajaxGet(url) {
return $.ajax({
url: url,
type: "POST",
data: {
action: 'call_this'
},
dataType: 'json'
});
}
ajaxGet().done(function(wpdata) {
// use wpdata here
});