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!
Related
I am trying to get a div to reload once a checkbox has been selected or unselected and the form has been submitted. I have used AJAX and can get the form to submit on change, which works no problem. However the page has to reload to display new data.
I have built the php in such a way that it doesn't need to refresh the page or fetch a new page. If the div and it's content refreshes that should be sufficient to display the new filtered data.
Below is what I have written so far
$(document).ready(function() {
$("input:checkbox").change( function() {
$.ajax({
type: "POST",
url: "index.php?action=resortFilter",
data: $("#locationFilter").serialize(),
success: function(data) {
$('.resorts').html(data);
}
});
})
});
What do I need to do to get the div to reload after the request has been made?
I use class methods to handle the processing which return only the array of data. The requests are made to the class from a php function.
What I'm trying to do isn't actually possible to because PHP is a server side language. The best bet is to create a new intermediate file that can handle the display of the data so that it can be brought in through a normal AJAX request and get the new display from it
Where is the Ajax request? You are submitting your form through HTML/Browser. You need to use the following code:
$(document).ready(function() {
$("input:checkbox").change( function() {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#locationFilter").serialize(), // serializes the form's elements.
success: function(data)
{
$('.resorts').html(data);
}
});
})
});
Source: jQuery AJAX submit form
this sample loading code maybe help you
<div id="loadhere"></div>
$('div#loadhere').load('ajaxdata.php',{datatosend:whatyouwantforexamplehelloworld});
I need a jQuery popup to ask the user for some required data before loading the same page it's on.
The data entered will become a php variable that I'll use to query a mysql table and pre-populate some form fields.
Any advice?
Thanks!!
you can make an AJAX call to the PHP and load it to div that you want. For the ajax calls you can use jquery it really makes you job easy.
eg:
$.ajax({
url: 'getitems.php',
success: function(data) {
$('#manage_inventory').html(data);
//alert('Load was performed.');
}
});
like in the example it is calling getitems.php and getting the list and loading it into #manage_inventory. The data being returned can be XMl or other type which can be parsed and be used according to your needs.
Your solution could be as simple as using a prompt() box in javascript and then passing the information via ajax
var stuff = prompt('Gimme Stuff');
$.ajax({
url: 'dostuff.php',
data: 'stuff=' + stuff,
success: function(data) {
//process stuff
}
});
I have a page with multiple forms that do the same thing, acting as a like button for each post in the page, and right next to it the number of likes inside a div named "likes".$id, so I can identify where to write the likes count after the ajax call. I was trying to use jQuery ajax function, but I couldn't set what div to write the results of the function.
$.ajax({
type:'POST',
url: 'likepost.php',
data:$('#like').serialize(),
success: function(response) {
$('#like').find('#likediv').html(response);
}
});
And how would I access the data on likepost.php? I am terrible with javascript, so I hope someone could help me and explain how the jQuery function really works, because I've been copying and pasting it without really knowing what I was doing.
Would this work?
$(function () {
$("#likebutton").click(function () {
var id = $('input[name=id]'); // this is me trying to get a form value
$.ajax({
type: "POST",
url: "likepost.php",
data: $("#like"+id).serialize(), // the form is called like+id e.g. like12
success: function(data){
$("#likes"+id).html(data); // write results to e.g. <div id='likes12'>
}
});
});
});
I put this in the code but when the button is clicked, the usual post refreshing page is done. Why is that?
Making a mini-form, serializing it, and POSTing it seems like a lot of heavy lifting when all you really want to do is send the ID to the likepost.php script.
Why not just retrieve the ID and post it to the script?
First let's break down your function:Type is the type of the request we're making, you specified POST here. This means in your PHP file you'll access the data we're sending using $_POST. Next up is URL which is just the url of where you're sending the data, your php file in this case.
After that is data, that is the data we're sending to the url (likepost.php). You're serializing whatever has a ID of "like" and sending it to the php file. Finally success is a function to run once the request is successful, we get a response back from the PHP and use it in the function to output the response.
As for the multiple forms I'd recommend doing something like:
http://www.kavoir.com/2009/01/php-checkbox-array-in-form-handling-multiple-checkbox-values-in-an-array.html
Here's documentation on the stuff we talked about, if you're every confused about jquery just break it down and search each part.
http://api.jquery.com/serialize/
http://api.jquery.com/jQuery.ajax/
you can try :
function submitform(id) {
var jqxhr = $.post('./likepost.php',$("#"+id).serialize(), function(data) {
$("#"+id).find('#likediv').html(data);
}, "json")
return false;
}
in form:
<form method="post" id="likeForm" onsubmit="return submitform(this.id);">
<input..... />
<input type="submit" value="Submit" />
</form>
in likepost.php add first line:
if ($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
header("location: " . $_SERVER['HTTP_REFERER']);
exit();
}
you can see more : http://api.jquery.com/serialize/
working for me.
I'm writing a game in html5 and using wordpress for the rest of the site. I want users to be able to save their progress, but I'm not clear on how the architecture looks.
I would just do an ajax call to a php page that access the database, but I feel like using the existing wordpress database and API is the correct thing to do. Not only that, but using the wordpress api will give me access to things like nonce.
That said, do I write a wordpress plugin to do this? How do I properly execute the save request from the javascript that runs my game?
In your js file, do your ajax request like this:
jQuery.post('path/to/wp-admin/admin-ajax.php', {action:'save_progress',other_parameter:'other_value'}, function(response) {
// let your user know if his progress is saved or not
});
add this to your theme's functions.php:
function save_progress() {
global $wpdb;
// do the saving job with received parameters here
die(); // this is necessary
}
add_action('wp_ajax_save_progress', 'save_progress');
If you're interested in a more generalizable solution than what the wordpress API allows (for more overall understanding), below is a simple, but complete demo:
Here's the HTML:
<input id="posted_data" ></input>
<button id="saveBtn">Save</button>
Here's the JS:
$(document.body).on('click', '#saveBtn', function(){
var posted_data=$('#posted_data').val();
var url="/submit_page.php";
$.ajax({url: url, data: {posted_data:posted_data }, type: "POST",
success: function(response){
//do something with the `response` data
} //success
}); //ajax
}); //.saveEditBtn
Here's the submit_page.php:
$posted_data=$_POST['posted_data'];
$posted_data; //do something with this variable, like insert it into a database
echo "Success"; // this will be the `response` variable in the JS above.
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