Like function with Ajax / PHP / jQuery - javascript

1 week ago, i decided to start adding AJAX and more jquery to my Website.
I think, the "combination" of PHP / Jquery / AJAX is the best thing ever.
Now i want to create a "like - system" in my community board. I did something similar already:
$(function(){
$('.action-button.like').click(function(){
//ajax part
var articleId = $('.article-Id').html();
$.ajax({
type: "GET",
async: true,
url: '/wiki/parts/likeArticle.php',
data: { 'articleId': articleId },
//change button
success: function (msg){
$('.action-button.like span').fadeOut(400);
},
error: function (err)
{ alert(err.responseText)}
});
});
});
as you can see, the button / element disappears after a click() on it.
PHP data: the .php file "inserts the like" into the database ...
So - this works great !
Back to my question: After an user likes the post, i want to display a container with all users, which did this before.
I'm asking this, because i know how to do this / I have an Idea how i can realise my little project, but i dont know, if this is the propper way :)
My solution:
in $.ajax:
I want to create a function on "success:" (and a new .php file, which loads all users / "likers")
the function uses .load() and loads the file, so everything should be done right, shouldn't it ?
I hope you understand my problem,
Greets :)

Related

PHP doesnt see posted data from ajax by serializeArray()

I have a form, running through jquery validation which then submits via ajax to a PHP script to handle backend functions. Ajax collects form values through serializeArray() and looks to do the job. Script fires and data is sent through(I think) to PHP. I've tried probably close to 100 combinations to receive the data at the PHP side but with no luck. I'm convinced this must be simple, something I've overlooked. Code for the ajax is below, along with a screenshot of developer tools showing what's being sent.
No matter what I try on the PHP side, I either get an empty array, NULL through $_POST/$_GET. I've tried json_decode, parsing the string, var_dump etc.
var data=$(form).serializeArray();
$.ajax({
cache: false,
type: "POST",
dataType: "JSON",
url: "process/create_site.php",
data: data,
success: function(response) {
console.log(response);
//$(form).html("<div id='message'></div>");
//$('#message').html("<h2>Your request is on the way!</h2>")
// .append("<p>someone</p>")
// .hide()
// .fadeIn(1500, function() {
// $('#message').append("<img id='checkmark' src='images/ok.png' />");
// });
}
});
I managed to get to the bottom of this, after an embarrassing amount of time. I'd like to post the simple reason here to help others.
The entire JS block was wrapped in $(document).ready(function(){
which was causing the values to be stripped when posting to the PHP.
I can't find any documentation or answer to a question with a similar scenario - so here it is!

Auto saving JAVASCRIPT data via AJAX to database

Apologies if this particular question has been solved before, I have looked everywhere it seems and can't quite get the answer I'm looking for! I am no expert and can imagine the solution is embarrassingly easy.
My problem is this: I have some php and javascript code working on a html based website, linked to a database (reading data in and also writing data out via a save function called once at the end of the script). I need the javascript code to automatically save/update itself to db via an Ajax request, without the need to keep running the page. The data being saved here needs to be read by various other pages and is relied upon to give correct results elsewhere! (so a solution would be to have the user keep the page open in the background - but suggestions for this separate issue are also welcome!)
Anyway, at the moment I have:
function sessionSave () {
var newData = kpiCA.getData().concat(kpiHA.getData(),kpiStocks.getData(),kpiCV.getData(),kpiPD.getData());
$.ajax({
url: 'saveMain.php',
type: 'POST',
data: {'kpi': newData},
success: function () {
},
error: function () {
$console.text('Data Save Error');
}
});
}
sessionSave();
I have seen some autosave scripts and the addition of timers etc. but as I am a complete noob, some help would be much appreciated,
Thanks guys!
Basically it's just timers or intervals. For example:
window.setInterval(sessionSave, NUMBER_OF_SECONDS * 1000)
// where NUMBER_OF_SECONDS is, obviously, the number of seconds to repeat your function at

Triggering a jQuery Re-Draw After Getting Data With Ajax

Good day, all,
Long-time listener, first-time poster...
I have a client who has been promised a seemingly very complex bit of functionality. They want to load the contents of 3 separate pages into one, after a visitor to their site successfully logs in to their account. They want this to happen without a page refresh. Ajax is the solution. I am not, however, experienced with Ajax.
I'm having trouble figuring out how to tell when a $.get command (using jQuery's Ajax commands) has finished loading its content. My approach is to, once the login has been successful, to go and fetch the 3 separate pages, load their XHTML content into variables, and redraw the pages. Below you'll see my pseudo-code. I use "XXItemXX" to stand-in for actual paths. Each resulting page that I'm trying to pull in has a div with class "content" surrounding the data I want to retrieve. The XHTML looks like this:
<html>
<head>
<title>Page Name</title>
</head>
<body>
<div id="header">...</div>
<div class="content">
.
.
.
</div>
<div id="footer">...</div>
</body>
</html>
The jQuery code I've built follows. I'm able to get the form submitted and even get the content back from the various .get commands. The problem is, I can't seem to daisy-chain things as I normally would. I am struggling to figure out how to only fire the jQuery commands to draw the page once all 3 have been successfully retrieved. I'm afraid my biggest stumbling point is how to articulate this when searching with Google to see how others have dealt with this problem. I'm not sure exactly how to describe what I'm trying to accomplish in 10 words or less or in a fashion that will actually return the information I need.
Can anyone help with this? I'm afraid I have too little time and too much to learn.
<script type="text/javascript">
$('XXLoginFormXX').submit(function () {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
beforeSend: function() {
$('<div class="loading">Loading...</div>').insertBefore('XXLoginFormXX').css('position','absolute');
},
success: function(data) {
// On successful login, draw page.
$('.loading').fadeOut('slow');
var dr_editProfileXHTML, dr_accountOrderListXHTML, dr_wishListsXHTML;
$.get('XXPathToEditProfilePageXX', function(data1){
var dr_editProfileXHTML = $('div.content', data1);
});
$.get('XXPathToAccountOrderListPageXX', function(data2){
var dr_accountOrderListXHTML = $('div.content',data2);
});
$.get('XXPathToWishListsPageXX', function(data3){
var dr_wishListsXHTML = $('div.content',data3);
});
$('div.content').fadeOut(function(){
$(this).html(dr_editProfileXHTML);
$('XXEditProfileXHTMLXX').before(dr_accountOrderListXHTML);
$('XXEditProfileXHTMLXX').before(dr_wishListsXHTML);
}).fadeIn();
}
});
return false;
});
</script>
Thank you very much for your time, help, and consideration.
Yours,
Sylvan012
If your problem is to wait that all 3 requests have returned, then:
store the results in variables scoped a bit higher so that each of the callbacks can access them
add a variable drawing in the same scope
in each of the callbacks, check if all 3 variables are non-null and drawing is false
if that's the case, then set drawing to true, and do the work
After working on this with people's generous help, I believe I've gotten it. All my thanks to Dave Briand who taught me about .when and .then.
Following is the pseudo-code I came up with. It seems to be working! Sure there's a lot of clean-up to do, but all three of the pages are now being pulled-in! Whoot!
What do you think of my solution?
<script type="text/javascript">
$('XXLoginFormXX').submit(function () {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
beforeSend: function() {
$('<div class="loading">Loading...</div>').insertBefore('XXLoginFormXX').css('position','absolute');
},
success: function(data) {
// On successful login, draw page.
var Page01XHTML;
var Page02XHTML;
var Page03XHTML;
$.when(
$.get('XXPathToEditProfilePageXX', function(data1){
var Page02XHTML = $('div.content', data1);
}),
$.get('XXPathToAccountOrderListPageXX', function(data2){
var Page03XHTML = $('div.content',data2);
}),
$.get('XXPathToWishListsPageXX', function(data3){
var Page01XHTML = $('div.content',data3);
})
).then(function(Page02XHTML,Page03XHTML,Page01XHTML){
$('.loading').fadeOut('slow');
$('div.content').fadeOut(function(){
$(this).attr('id','MyAccount').html(' ' + Page01XHTML + Page03XHTML + Page02XHTML + ' ').parents('body').find('.content').each(function(){
dr_thisID = $(this).attr('id');
if (dr_thisID != 'MyAccount') {
$(this).appendTo($('div#MyAccount'));
}
}).parents('div#MyAccount').children().each(function(){
dr_thisClass = $(this).attr('class');
if (dr_thisClass != 'content') {
$(this).remove();
}
});
}).fadeIn();
});
}
});
return false;
});
</script>

Display loading as the page is redirecting in Django

I am not trying to ask for free ride, but I don't seem to know how to do this at all.
My recent posts are about running jobs in the background, but I have no luck in doing that.
So...
User clicks run inside a form and it fires a job.
It takes about 30 seconds to complete the job, returns, and tells Django view function to return HttpResponseRedirect(....).
So while the page is being redirect (it takes 30 seconds to signal "GO AHEAD").... I want to show user like an Ajax loading gif picture.
I don't have Ajax implemented and the system is way too complicated to hack on.
Can we actually do this with javascript? The problem is that it hasn't load any page yet because it needs heavy_work to finish.
result = heavy_work(....)
.... more code ....
return HttpResponseRedirect(go to this page...)
Thanks!
Why don't you use a regular ajax call?
javascript
function do_heavy_lifting(argument) {
$.ajax({
type: 'GET',
data: { argument: argument }, // if necesarry
url: '/heavy_lifting_django_view_url/',
beforeSend: function() {
$('#loading').show();
},
success: function(data) {
...redirect...
},
cache: false
});
}
html
<div id="loading" style="display:none">
<button onclick="do_heavy_lifting('argument');">
Using AJAX is simple: just show a 'loader' animated gif before the actual ajax call, and in 'on_success' response callback to hide the loader gif.
Bu without AJAX - the only solution so far is using iterators - look at this: How to stream an HttpResponse with Django

jQuery can't call plugins after appending Ajax data?

EDIT2: Nevermind, got it working. jQuery was included again in one of the scripts called with ajax. Thanks anyway.
EDIT: This is a rephrased question. Took my a while to find where the problem was.
Calls to plugin functions (including UI effect) aren't working after I load some content with ajax.
The original question had .effect("pulsate",{},1000) call, which explains sarcastyxs answer. Now I'm trying the same thing with the countdown plugin. The same problem appears.
Here is my code. Ignore that it doesn't do much sense, it is stripped down from a larger file. By itself the code is fine. For instance, if I call fadeOut() it works, but if I use .countdown or .effect the mentioned problem appears.
var getOrderDetails= function(id){
var that = this;
$.ajax({
type: "GET",
url: "orderDetails.php",
data: {id: id},
success: function(data){
//$("#orderDetails").html(data);
$("#orderDetails").unbind().click(function(){
var status = $("#orderDetails .orderStatus").text()
acceptOrder(id, status);
});
}
});
}
var acceptOrder = function(id, status){
var that = this;
$.ajax({
type: "GET",
url: "orderStatus.php",
data: {action: 'set', id: id, status: status},
success: function(data){
var nowTime = new Date();
var countdownTime = nowTime.setMinutes(nowTime.getMinutes() + 2);
$("#waitingOrders").countdown({until: countdownTime, compact:true, format: 'MS'});
}
});
}
$(document).ready(function(){
$(".order").unbind().click(function() {
var id = $(this).find(".orderId").text();
getOrderDetails(id);
});
});
When I comment the $("#orderDetails").html(data) line (like in code), the countdown timer appears inside the orderDetails div.
When I uncomment the line, I get an countdown is not a function error. Looked at the dom in firebug, and really in first case I can see that the selector has the .countdown function, and in the second scenario it does not.
What am I missing here?
Someone please help, I have been stuck on this for a few days.
Tried to wrap the ajax success functions with another function and pass it this as context, but it doesn't help. Same thing
You seem to be missing some core functions from jquery-ui. You can download a custom jquery-ui library from the jQuery site.
You basically want to select Effects core and whatever other effect you want to use on the site. The effects core is not part of the default jQuery ui library for some reason.

Categories

Resources