PHP / JQuery / AJAX for Updating Database if Div is not visible - php

I have a complex website setup so I'll just make an example a simple one.
Current Setup
I have two buttons.
<a id="one" href="#">Link 1</a>
<a id="two" href="#">Link 2</a>
And I have two divs
<div id="showOne" style="display:none">1</div>
<div id="showTwo" style="display:none">2</div>
This is my JQuery code
$('#one').click(function (e) {
$('#showOne').show();
});
$('#two').click(function (e) {
$('#showTwo').show();
});
What I'm Trying to Accomplish
Basically, I have a database table setup that has a row to count how many times was div(showOne) and div(showTwo) shown.
How would I work with AJAX to add one to the database row aka counter if display = block?
My Attempt
$('#one').is(":visible")
{
$.ajax({
type:"POST"
url: update.php
data: {type:link_one_shown}
success: function(data){
alert("Test");
}
})
When I do this, the rest of my JQuery code crashes. Not sure if this doesn't make sense or I just wrote something wrong.
Thank you in advance!

Three problems that I can see:
As Akam notes, you've mangled the if statement.
The data isn't correct -- link_one_shown should be either a variable (which you haven't defined?) or a string literal.
You're missing commas between the ajax function parameters.
Here's the modified code:
if ($('#showOne').is(":visible")) {
$.ajax({
type:"POST",
url: update.php,
data: { type: "link_one_shown" },
success: function(data){
alert("Test");
}
});
}

why not just move ajax call to function and invoke it when show the div, this avoids code repetition and makes it simpler.
$('#one').click(function (e) {
$('#showOne').show();
updateDB('link_one');
});
$('#two').click(function (e) {
$('#showTwo').show();
updateDB('link_two');
});
function updateDB(link)
{
$.ajax({
type:"POST"
url: update.php
data: {type:link}
success: function(data){
alert("Test");
}
});
}

Related

Where to put .fadein() in ajax pagination

I done ajax pagination (by watching tutorial) but now i need to add fadein effect and i cant figure how. I tried to add .fadeIn() probably everywhere but it wont work and i dont know where to put it. What i want to do is smooth page change.
Here is my script i think i dont need to add php.
And i have only back and next options. Not numbers of sites.
<script>
$(document).ready(function(){
//showing the data without refresh but on going to next pagination
setTimeout(function(){
load_fn_data();
}, 1000);
function load_fn_data(page){
$.ajax({
url:"data.php",
method:"POST",
data: {
page:page
},
success: function(data){
$('#load_data').html(data);
}
});
}
$(document).on('click','.pagination_link',function(){
var page = $(this).attr("id");
load_fn_data(page);
});
});
</script>
Hide before, than .html and afterwards .fadeIn() on success like:
function load_fn_data(page){
$('#load_data').hide()
$.ajax({
url:"data.php",
method:"POST",
data: {
page:page
},
success: function(data){
$('#load_data').html(data).fadeIn(800);
}
});
}

AJAX Load PHP Response

How can I load data from my PHP response via ajax into a panel?
My PHP outputs correctly and I can see a table in the response, but I can;t get it to build the data on my webpage.
Here is my jquery/ajax so far. It passed the value to PHP correctly and PHP builds the table via its echo, but what am I missing for AJAX to display the table?
PHP:
<?php
foreach ($lines as $value) {
echo "<input name='data[]' value='$value'><br/>";
}
?>
JQUERY:
$(function () {
$('#rotator').change(function (e) {
var rotator = $("#rotator").val();
$.ajax({
type: "POST",
url: "tmp/JFM/National/national.php",
data: {
rotator: rotator
},
success: function (result) {
$('#panel').load(result);
}
})
return false;
});
});
The answer to this was two fold.
I was attempting to append to my main div, which apparently can't happen. I created a new empty div and was able to load the results there.
Beyond that, the comments to change .load(results) to .html(results) were needed.
The correct jquery code is below.
$(function () {
$('#rotator').change(function (e) {
var rotator = $("#rotator").val();
$.ajax({
type: "POST",
url: "tmp/JFM/National/national.php",
data: {
rotator: rotator
},
success: function (result) {
console.log(result);
$('#test').html(result);
}
})
return false;
});
});
move your function from:
$.ajax({...,success: function(){...}});
to
$.ajax({..}).done(function(){...});
if it doesn't work, try to add async:false into the ajax object...
$.ajax({...,async:false}).done(function(){...});
Hope it helps... =}

Change PHP Function Argument with AJAX

I'm trying to update information from a PHP function on the fly. I use a PHP function on my page:
main();
main() works like:
function main() {
global $news;
$news = api($news);
}
When someone clicks a different 'News' topic on my menu, I want to refresh main() with AJAX to reflect the new news category request. Racking my brain and Stack, I'm not sure where the slip up is. The AJAX request originates from this list:
<div class="mainleft">
<ul>
<li>World News</li>
<li>Sports</li>
</ul>
</div>
My JS looks like the following (adding the alert at the end to try and debug the variable):
$(document).ready(function() {
$(".mainleft > ul > li").click(function(){
$.ajax({
type: "POST",
url: "/includes/ajax.php",
data: $(this).text(),
success: function(msg){
alert($(this).text()); // this alert fires but the result is blank
}
});
});
});
ajax.php looks like:
if ($_POST) {
$news = $_POST;
}
I've tried GET with the same results, so it's something fundamental I'm doing wrong.
UPDATE #1:
Somebody suggested a fix and then deleted the reply, but another member suggested the same fix in a comment. The fix didn't work but they clarified that I need a key/val pair for the POST which changed my javascript to:
data: { news: $(this).text() },
and then my ajax.php to:
if (isset($_POST['news'])) {
$news = $_POST['news'];
}
UPDATE #2:
Thanks to #Sean I understand that I was displaying my debug alert improperly, adding the following to the javascript corrected that and now alerts the proper list item:
context: this
But the PHP function still isn't updating.
Your $(this) in alert($(this).text()); inside your $.ajax is out of scope. You can either save to a var before your ajax call, and reference the var -
$(".mainleft > ul > li").click(function(){
var liText = $(this).text();
$.ajax({
type: "POST",
url: "/includes/ajax.php",
data: liText,
success: function(msg){
alert(liText);
}
});
});
or use context ajax option -
$(".mainleft > ul > li").click(function(){
$.ajax({
type: "POST",
url: "/includes/ajax.php",
context: this,
data: $(this).text(),
success: function(msg){
alert($(this).text());
}
});
});
Note: as #Mark B mentioned, your data should have a key to be able to access in php -
$(".mainleft > ul > li").click(function(){
$.ajax({
type: "POST",
url: "/includes/ajax.php",
context: this,
data: {key: $(this).text()},
success: function(msg){
alert($(this).text());
}
});
});
reference: https://stackoverflow.com/a/1570160/689579 https://stackoverflow.com/a/8070183/689579
jsFiddle: http://jsfiddle.net/h2FLg/ (examples of saving $(this) to var, context:, and out of scope)

Issue with using a value in JQuery/Javascript

I have a PHP populated table from Mysql and I am using JQuery to listen if a button is clicked and if clicked it will grab notes on the associated name that they clicked. It all works wonderful, there is just one problem. Sometimes when you click it and the dialog(JQuery UI) window opens, there in the text area there is nothing. If you are to click it again it will pop back up. So it seems sometimes, maybe the value is getting thrown out? I am not to sure and could use a hand.
Code:
$(document).ready(function () {
$(".NotesAccessor").click(function () {
notes_name = $(this).parent().parent().find(".user_table");
run();
});
});
function run(){
var url = '/pcg/popups/grabnotes.php';
showUrlInDialog(url);
sendUserfNotes();
}
function showUrlInDialog(url)
{
var tag = $("#dialog-container");
$.ajax({
url: url,
success: function(data) {
tag.html(data).dialog
({
width: '100%',
modal: true
}).dialog('open');
}
});
}
function sendUserfNotes()
{
$.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data:
{
'nameNotes': notes_name.text()
},
success: function(response) {
$('#notes_msg').text(response.the_notes)
}
});
}
function getNewnotes(){
new_notes = $('#notes_msg').val();
update(new_notes);
}
// if user updates notes
function update(new_notes)
{
$.ajax({
type: "POST",
//dataType: "json",
url: '/pcg/popups/updateNotes.php',
data:
{
'nameNotes': notes_name.text(),
'newNotes': new_notes
},
success: function(response) {
alert("Notes Updated.");
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
});
}
/******is user closes notes ******/
function closeNotes()
{
var i;
$("#dialog-container").effect( 'fade', 500 );
i = setInterval(function(){
$("#dialog-container").dialog( 'close' );
clearInterval(i);
}, 500);
}
Let me know if you need anything else!
UPDATE:
The basic layout is
<div>
<div>
other stuff...
the table
</div>
</div>
Assuming that #notes_msg is located in #dialog-container, you would have to make sure that the actions happen in the correct order.
The best way to do that, is to wait for both ajax calls to finish and continue then. You can do that using the promises / jqXHR objects that the ajax calls return, see this section of the manual.
You code would look something like (you'd have to test it...):
function run(){
var url = '/pcg/popups/grabnotes.php';
var tag = $("#dialog-container");
var promise1 = showUrlInDialog(url);
var promise2 = sendUserfNotes();
$.when(promise1, promise2).done(function(data1, data2) {
// do something with the data returned from both functions:
// check to see what data1 and data2 contain, possibly the content is found
// in data1[2].responseText and data2[2].responseText
// stuff from first ajax call
tag.html(data1).dialog({
width: '100%',
modal: true
}).dialog('open');
// stuff from second ajax call, will not fail because we just added the correct html
$('#notes_msg').text(data2.the_notes)
});
}
The functions you are calling, should just return the result of the ajax call and do not do anything else:
function showUrlInDialog(url)
{
return $.ajax({
url: url
});
}
function sendUserfNotes()
{
return $.ajax({
type: "POST",
dataType: "json",
url: '/pcg/popups/getNotes.php',
data: {
'nameNotes': notes_name.text()
}
});
}
It's hard to tell from this, especially without the mark up, but both showUrlInDialog and sendUserfNotes are asynchronous actions. If showUrlInDialog finished after sendUserfNotes, then showUrlInDialog overwrites the contents of the dialog container with the data returned. This may or may not overwrite what sendUserfNotes put inside #notes_msg - depending on how the markup is laid out. If that is the case, then it would explains why the notes sometimes do not appear, seemingly randomly. It's a race condition.
There are several ways you can chain your ajax calls to keep sendUserOfNotes() from completing before ShowUrlInDialog(). Try using .ajaxComplete()
jQuery.ajaxComplete
Another ajax chaining technique you can use is to put the next call in the return of the first. The following snippet should get you on track:
function ShowUrlInDialog(url){
$.get(url,function(data){
tag.html(data).dialog({width: '100%',modal: true}).dialog('open');
sendUserOfNotes();
});
}
function sendUserOfNotes(){
$.post('/pcg/popups/getNotes.php',{'nameNotes': notes_name.text()},function(response){
$('#notes_msg').text(response.the_notes)
},"json");
}
James has it right. ShowUrlInDialog() sets the dialog's html and sendUserOfNotes() changes an element's content within the dialog. Everytime sendUserOfNotes() comes back first ShowUrlInDialog() wipes out the notes. The promise example by jeroen should work too.

Get only part of the message and reload only one div

this is an ajax method that inserts the data into a db and should supposedly display the new content.
<script type = "text/javascript">
$(document).ready(function() {
$('#submit').live('click', function(eve) {
eve.preventDefault() ;
var form_data = {
title: $('#title').val()
};
$.ajax({
url: "http://localhost/ci/index.php/chat/comment",
type: 'POST',
data: form_data,
success: function(msg) {
alert(msg);
}
});
});
});
</script>
However in my /chat/comment, i am loading the view again, i.e, user submits a comment, load the view again and the comment should be there. My response from server is the view's HTML. However the view comes with all the divs and there are many of them. I need to retrieve only part of the div, say, #commentspace from the ajax on success.
Look at the jQuery $.load() function?
Example
Inside "firstpage.html"
$('#content').load('secondpage.html #content');

Categories