PHP Newsfeed with Reload - php

I'm have a PHP and MYSQL based newsfeed. To get new content, the user has to refresh the page. I'm working on a push system that would update the element with new posts without refreshing the whole page. How would I go about that?

Sounds like a job for Ajax!
Also if you want to make the work really easy, use jquery. The Syntax would look something like this:
$.ajax({
type: "post", url: "/SomeController/SomeAction",
success: function (data, text) {
//....
},
error: function (request, status, error) {
alert(request.responseText);
}
});
EDIT
to have the page update when a user clicks on a "show more content" link you can either use javascripts onclick function or use jquery's built in stuff.
Regular JS:
<somekindOfLinkOrButton onclick("moarStories();")/>
<script>
function moarStories(){
//ajax here
};
</script>
Jquery way (much eaiser)
<script>
$("#ElementId").click(function(){
//ajax here
});

You just send a request to the server and server tries to keep the connection alive until you get new update. When you get new update from the database, you just push it to the client and close this connection

Related

Counting clicks on an <a> link in a MySQL database

I have different links on my website which lead to other websites. I want to count the amount of clicks on the different links with my MySQL database.
I thought about doing a redirection over a php file which adds it in the database, but I would prefer to not redirect the user. Is it possible that the user just clicks on the tag gets immediately to the external website, and I can still count the click?
Thanks for you answers,
Till
yes you can run an ajax request and when the request is completed then you can redirect user to where ever you want to.
in the ajax request you will count the clicks and save it to the database.
you can do something like
$("a").click(function(){
$.ajax({url: "scriptthatwillcountclick.php", success: function(result){
window.open('redirect_here');
}});
});
Use ajax.
var data = {link:"value"};
$.ajax({
url : "your_file.php",
type: "POST",
data : data,
success: function(data, textStatus, jqXHR) {
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error");
}
});
You can run this code inside .click function when the link is pressed.
And in your php file just increment the count.
You can use jQuery Ajax funcionality to accomplish your goal, just create an on click even for your "a" element and execute your Ajax to save the click information on your database.
$('a').on('click', function(){
$.ajax({
method: "POST",
url: "save-my-click.php",
data: { 'extrainfo' : "Some extra info" }
});
});
Do not return false, or event.preventDefault() on your click event, because it will brake the redirection.
UPDATE:
You don't need to set the success and error functions because it is going to redirect anyway and you are not going to handle them.

run a query code to retrieve array from database without page refresh

Am kind of not into ajax or json requests, but it seems i might be needing it now or any alternative means, am working on a school management software, i have a page with forms in which when i select a class on the form, it loads all subjects attributed to the class from the database, i already have a php code that would query that, but since php is a server-side language, i would have to reload the page to get the list of subjects from the selected class.. please how can i go about it using any means; here is my code to get classes based on class selected into an array... how can i make this run without a reload
$subjects = $this->crud_model->get_subjects_by_class(class_id);
Basic ajax call:
<script>
$('#button').click( function () {
$.ajax({
type:"POST",
url: "phpsite.php",
data: {
postdata: variable
},
success: function(data){
$('#divtochange').html(data);
}
});
} );
</script>
In phpsite.php, just put the code you would usually refresh. You will need to include jQuery.
Here is a tutorial

callback race: button click to trigger ajax, whose callback won't execute on time

I have what I think is a fairly classical problem involving what looks to me like a callback race, but in spite of all my reading, I'm still stuck. You'll find the code pasted below.
It's a simple log in form and you can see that when a certain button is clicked, I'll send the form data "ajaxically" to an external php file. Once the php has run, I'm to receive the results back, and as a test here, to simply alert out the email address from the php file.
When I run this, the ajax callback doesn't execute. If I click the button fast and repeatedly, I get the right alert. I also get the right response if I put in an extra alert.
How do I get it to run without doing these other silly things?
Thanks in advance
RR
$('#'+this.loginForm[0].parentId+"logIn")
.on('click', function() {
var jax = $.ajax(
{
type: "POST",
url: "../sharedfunctions3/act-membership.php",
data: {email: document.getElementById(that.parentId+'email').value,
password: document.getElementById(that.parentId+'password').value,
path: that.path,
action: "logIn"
}
});
jax.done(function()
{
obj = JSON.parse($.trim(jax.responseText));
alert(obj.email);
});
jax.fail(function() { alert("error"); });
alert(1);
});
I had a hunch that when you clicked the button the browser was submitting synchronously and asynchronously.
The return false; tells the browser to not submit the form and to prevent default actions from there on.
When a button inside of a form tag is clicked, most browsers will submit the form even though it is not a submit input.

Return results from a MySQL database using jQuery/AJAX and insert into a DIV

I am working on a project for reserving classrooms. One way of reserving a room is to select a room, see if the things it has (# of seats, # of computers, etc.) is ample for whatever the person needs it for, and then make a reservation.
I have a page that displays all of the available rooms as links in an HTML table, created dynamically in PHP/MySQL. My goal is when a user clicks on a room name, the AJAX request executes a query and returns the necessary data, and then displays it in a DIV on that same page.
Right now, I'm calling an external PHP file that gets the ID of the room that's clicked and executes the query. I'm still very much a novice at jQuery, and I'm pretty sure the problem is in my jQuery script:
<script type="text/javascript">
$(document).ready(function()
{
$('table.roomNums td a.rm-details').click(function()
{
var id = $(this).attr('id');
$.ajax(
{
type: 'POST',
url: 'roomInfo.php',
data: {
roomID: id
},
dataType: 'json',
cache: false,
success: function(result)
{
$('#room-details').empty();
$('#room-details').append("<ul>\n\t<li>Seats: " + result.numOfSeats + "</li>\n</ul>");
}
});
});
});
</script>
As of now, when I click on one of the room number links, nothing happens. I'm assuming that my problem resides in this script, but I'm not sure where or what. I've been reading into the ajax function in jQuery and I'm pretty sure I understand what's going on, but I'm having no luck at the moment.
You want to troubleshoot the following four things:
The HTTP Request Does the browser even issue an ajax request? If so, does it contain the form parameter you are trying to make it contain?
The HTTP Response Does your php script return the data you are expecting in JSON format so JQuery can automatically parse it for you? Copy and paste the response from the server into a test javascript file and see if it compiles as a valid JSON object in a javascript debugger.
AJAX success function Does your javascript error out? Can you step through each line of execution in a javascript debugger like firebug?
Click Event Handler Does your click handler properly return false so the page does not reload? Does your click event handler function fire at all upon click?
Somewhere in the above four things lies your issue. It looks to me like you just need to return false in your click handler so the page does not reload.

Need to add function

I'd like to add a simple functionality to my pages, where a user will see a "follow" button and by clicking it a db record will be created (userID and pageID). I'll handle query on the backend, I suppose. I think I need to do it in AJAX, but I havebn't done much with AJAX. I was also thinking that updating the button status from FOLLOW to FOLLOWING (or something similar) I could do with jQuery, with some sort of toggle, while the request is being processed on the background.
Am I on the right track with this?
You're on the right track.
I've created an example which uses a button like <input type="image" class="follow">. When I user clicks on it it sends a request to the server (url). On success it updates the button image.
$('input[type=image].follow').click(function() {
var button = $(this);
var current_img = $(button).attr('src');
var current_alt = $(button).attr('alt');
$(button).attr('src', '/style/icons/ajax-loader.gif');
$(button).attr('alt', 'Requesting data from the server...');
$.ajax({
url: url of script the processes stuff (like db update),
type: 'POST',
data: {},
dataType: "json",
error: function(req, resulttype, exc)
{
$(button).attr('src', '/style/error.png');
$(button).attr('alt', 'Error while updating!');
window.setTimeout(function() {
$(button).attr('src', current_img);
$(button).attr('alt', current_alt);
}, 3000);
},
success: function(data)
{
$(button).attr('src', '/style/followed.png');
$(button).attr('alt', 'Followed');
}
});
return false;
});
Above is just some example code. Change it at your will. Have fun with it.
AJAX is right, jQuery makes ajax easy.
//Post with jQuery (call test.php):
$.post('test.php', function(data) {
//Do something with result data
});
It sounds like you are on the right track here. If you're working with a smaller application then using an AJAX request and creating your record would be easiest using a Java servlet and putting for example some JDBC code in your doGet or doPost method to perform the database operations.
At the same time your onSuccess method for your AJAX request can call the jQuery code necessary to update your button. Good Luck!

Categories