Jquery .post then use .show and .hide - php

So I'm learning JQuery and I'm stuck on this:
I have a page that displays a HTML table and inside that table I want to have a cell that can be updated via a dropdown menu, so you click on edit, the current value disappears and dropdown menu appears, and when the value is changed the database is updated and the new value is displayed. (with the menu disappearing)
The problem seem to be putting the .text and .show inside the data callback function - if I alert the data it is returning the correct data from the PHP file, and if I comment out the .post line and replace the (data) with ("test_text") it replaces the menu as I want it to.
Hopefully my question is well enough written to make sense, thanks.
Here's the code
$('.cat_color_hide_rep').hide();
$('.act_status_dropD').click(function () {
var record_id = $(this).parents('tr').find('.record_id').text()
$(this).parents('tr').find('.cat_color_hide_rep').show();
$(this).parents('tr').find('.cat_color_show_rep').hide();
});
$('.cat_color_hide_rep').change(function () {
var record_id = $(this).parents('tr').find('.record_id').text()
$(this).parents('tr').find('.cat_color_hide_rep').hide();
$.post('TEST_ajax_rep_list_status.php', {
ID: record_id
}, function (data) {
$(this).parents('tr').find('.cat_color_show_rep').text(data);
$(this).parents('tr').find('.cat_color_show_rep').show();
alert(data); // for testing
});
});

You can not access the $(this) inside the $.post function.
You can do this before the $.post:
var that = this;
And inside the post, do this:
$(that).parents('tr').find('.cat_color_show_rep').text(data);
$(that).parents('tr').find('.cat_color_show_rep').show();
This would be your resulting code:
$('.cat_color_hide_rep').hide();
$('.act_status_dropD').click(function () {
var record_id = $(this).parents('tr').find('.record_id').text()
$(this).parents('tr').find('.cat_color_hide_rep').show();
$(this).parents('tr').find('.cat_color_show_rep').hide();
});
$('.cat_color_hide_rep').change(function () {
var record_id = $(this).parents('tr').find('.record_id').text()
$(this).parents('tr').find('.cat_color_hide_rep').hide();
/** ADDED LINE **/
var that = this;
$.post('TEST_ajax_rep_list_status.php', {
ID: record_id
}, function (data) {
/** CHANGED LINES **/
$(that).parents('tr').find('.cat_color_show_rep').text(data);
$(that).parents('tr').find('.cat_color_show_rep').show();
alert(data); // for testing
});
});

In the callback function, this has been changed to refer to the XHR Object, you need to backup an reference of this from outside the function if you want to access it from the callback
var $this = $(this);
$.post('TEST_ajax_rep_list_status.php', {
ID: record_id
}, function (data) {
$this.parents('tr').find('.cat_color_show_rep').text(data);
$this.parents('tr').find('.cat_color_show_rep').show();
alert(data); // for testing
});

//Cache your selectors!
var catColorHide = $('.cat_color_hide_rep');
catColorHide.hide();
$('.act_status_dropD').on('click', function () { //Use the .on() method and save a function call. The .click() simply calls the .on() and passes in the callback.
var this = $(this), //If you use a selection more than once, you should cache it.
record_id = this.parents('tr').find('.record_id').text();
this.parents('tr').find('.cat_color_hide_rep').show();
this.parents('tr').find('.cat_color_show_rep').hide();
});
catColorHide.on('change', function () {
var this = $(this),
record_id = this.parents('tr').find('.record_id').text();
this.parents('tr').find('.cat_color_hide_rep').hide();
$.post('TEST_ajax_rep_list_status.php', {
ID: record_id
}, function (data) {
// I don't do the 'var this = $(this)' in here to fix your problem. The 'this' you see me using here refers to the element from the callback.
this.parents('tr').find('.cat_color_show_rep').text(data);
this.parents('tr').find('.cat_color_show_rep').show();
console.log(data); // Use this for testing instead.
});
});

Related

Can i add CSS style to a echo script alert message? [duplicate]

i am using smoke.js which allows to style the classic alert javascript windows.
All you have to do is place .smoke before the alert ie. smoke.confirm()
The issue I am having is with the ok/cancel callback, it isnt working for me.
This is the example the website shows.
`You can implement these the same way you'd use the js alert()...just put "smoke." in front of it.
The confirm() replacement, however, needs to be used just a little differently:
smoke.confirm('You are about to destroy everything. Are you sure?',function(e){
if (e){
smoke.alert('OK pressed');
}else{
smoke.alert('CANCEL pressed');
}
});
and the code I have is;
$(".upb_del_bookmark").click( function() {
if(smoke.confirm(delete_message)) {
var post_id = $(this).attr('rel');
var data = {
action: 'del_bookmark',
del_post_id: post_id
};
$.post(upb_vars.ajaxurl, data, function(response) {
$('.bookmark-'+post_id).fadeOut();
$('.upb_bookmark_control_'+post_id).toggle();
});
It shows the style button and everything but when i click on OK it doesnt perform the function above, nothing happens.
So i rewrote it to
$(".upb_del_bookmark").click( function() {
if(smoke.confirm(delete_message, function(e))) {
if(e){
var post_id = $(this).attr('rel');
var data = {
action: 'del_bookmark',
del_post_id: post_id
};
$.post(upb_vars.ajaxurl, data, function(response) {
$('.bookmark-'+post_id).fadeOut();
$('.upb_bookmark_control_'+post_id).toggle();
});
}}
But now when i click it doesnt even show anything
I am not a programmer, Help!!!!!
If you want to try it go to latinunit.org login with david:123321 and then go to a post and try to add it to your favourites
Update
I tried the following, it shows the window but it doesnt perform the function;
$(".upb_del_bookmark").click( function() {
smoke.confirm(delete_message, function(e) {
if(e){
var post_id = $(this).attr('rel');
var data = {
action: 'del_bookmark',
del_post_id: post_id
};
$.post(upb_vars.ajaxurl, data, function(response) {
$('.bookmark-'+post_id).fadeOut();
$('.upb_bookmark_control_'+post_id).toggle();
});
}})
return false;
});
Here is the js file of the smoke script Link
When i click on cancel the following shows;
Uncaught TypeError: Property 'callback' of object # is not a
function Line:198
Uncaught TypeError: Property 'callback' of object # is not a
function Line:208
The following is what's on those linesof the smoke script;
finishbuildConfirm: function (e, f, box)
{
smoke.listen(
document.getElementById('confirm-cancel-' + f.newid),
"click",
function ()
{
smoke.destroy(f.type, f.newid);
f.callback(false);
}
);
smoke.listen(
document.getElementById('confirm-ok-' + f.newid),
"click",
function ()
{
smoke.destroy(f.type, f.newid);
f.callback(true);
}
);
The builtin javascript alert/confirm functions are synchronous, this is not. You need to handle the result of the confirm using the javascript callback pattern. You pass a function to the smoke.confirm() function which called when you need to respond to an action.
See the following code. The if around the smoke.confirm() has been removed and the handling code is wrapped in the function passed to the smoke.confirm() function.
$(".upb_del_bookmark").click( function() {
smoke.confirm(delete_message, function(e) {
if(e){
var post_id = $(this).attr('rel');
var data = {
action: 'del_bookmark',
del_post_id: post_id
};
$.post(upb_vars.ajaxurl, data, function(response) {
$('.bookmark-'+post_id).fadeOut();
$('.upb_bookmark_control_'+post_id).toggle();
});
}
});
}
I highly recommend reading a little about the callback pattern in javascript. It's very common and understanding it will help you use this plugin and many others.

Pass jquery - generated variable to php in same page

I have a script that gets tha data on the row of a button when that button is clicked. The id of the button is id='show-button'. This is the script:
<script>
$(document).ready(function(){
$(".show-button").click(function() {
var $row = $(this).closest("tr"); // Find the row
var names = $row.find(".name").text(); // Find the name
var surname = $row.find(".surname").text(); // Find the surname
var lecturer_id = names."_".surname;
$("#show_dialog").dialog({autoOpen: false});
$(".show-button").on("click", function() {$("#show_dialog").dialog("open");});
});
});
</script>
The last two significant lines open a jquery dialog box.
With that, i mean these lines:
$("#show_dialog").dialog({autoOpen: false});
$(".show-button").on("click", function() {$("#show_dialog").dialog("open");});
Now, I need to pass the value of var lecturer_id to a php script outside this code, but inside the same document. This php code will generate the content of the dialog crated by these two lines. Lets assume that I just want to echo the variable passed inside the dialog box (with the php).
Any idea on how to make it work?
Your question is not 100% clear, but, just an idea, if I got you right:
<script>
$(document).ready(function(){
$(".show-button").click(function() {
var $row = $(this).closest("tr"); // Find the row
var names = $row.find(".name").text(); // Find the name
var surname = $row.find(".surname").text(); // Find the surname
var lecturer_id = names."_".surname;
$.post( "test.php", { names: names, surname: surname; lecturer_id: lecturer_id })
.done(function( data ) {
$("#show_dialog")[0].innerHTML = data ;
$("#show_dialog").dialog({autoOpen: false});
$(".show-button").on("click", function() {$("#show_dialog").dialog("open");});
});
});
});
</script>
And I agree with #JayBlanchard you don't even need any ajax call here, just generate your html like:
$(document).ready(function(){
$(".show-button").click(function() {
var $row = $(this).closest("tr"); // Find the row
var names = $row.find(".name").text(); // Find the name
var surname = $row.find(".surname").text(); // Find the surname
var lecturer_id = names."_".surname;
$("#show_dialog")[0].innerHTML = ' Name = '+names +'; Surname = '+surname ;
$("#show_dialog").dialog({autoOpen: false});
$(".show-button").on("click", function() {$("#show_dialog").dialog("open");});
});
});
You can use jQuery post or ajax.
$.post( "test.php", { name: "John", time: "2pm" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
test.php will be the reciving end of php, where it expects data sent by jquery.
{ name: "John", time: "2pm" } will be the data you are wishing to send off to php.
data will be the the data output by php.
refer to http://api.jquery.com/jquery.post/ for more information

How to get full url from <a> tag using jquery

I have a notification div. When someone clicks one of the links, the number of notification will be changed and after that the user will be redirected to the link that he clicked. Here is the php script inside the div.
<?php
while($row = stmt->fetch(PDO::FETCH_OBJ))
{
echo "<p><a href='http://example.com/blog/index.php?t_id=".$t_id."&c_id=".$c_id."'>".$title."</a></p>";
}
?>
I am using the following Jquery inside the div:
<script>
$('p').click(function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "http://www.example.com/change_notification.php"
})
.done(function( msg ) {
$("#changed_notification_value").text( msg );
var n_url = $('a', this).attr('href');
window.location.href = n_url;
});
});
</script>
Number of the notification changes successfully but when trying to redirect, the value of n_url shows undefined.
I think you have a problem of scope when using this. You can do something like this to fix the problem. Get the n_url before making the ajax request.
$('p').click(function (event) {
event.preventDefault();
var n_url = $('a', this).attr('href');
$.ajax({
type: "POST",
url: "http://www.example.com/change_notification.php"
}).done(function (msg) {
$("#changed_notification_value").text(msg);
window.location.href = n_url;
});
});
try this
var n_url = $(this).find('a').attr('href');
Try this:
var n_url = $(this).find("a").attr('href');
window.location.href = n_url;
this does not work like it does in other languages. When not inside a function (think global space) this refers to the Window object of the current browser. By default, new functions are created as children of Window.
For example;
function foo() {
return this;
}
Is actually the same as Window.foo = function() { return this; } (unless browser is in strict mode).
So when you call foo() the following is true.
foo() === window; // True, because foo() returns this which is window.
Since by default this refers to the object the function is bound to. You can change the default value of this by binding the function to a different object.
var o = {
x: 99,
foo: function() {
return this.x;
}
};
console.log(o.foo()); // will output 99
It doesn't matter when you bind the function to an object. As in this example.
var a = {
x: 99
};
var b = {
x: 77
};
function foo() {
return this.x;
}
a.f = foo;
b.f = foo;
console.log(a.f()); // will output 99
console.log(b.f()); // will output 77
In the above example the function foo is the same, but this changes depending on which bound object reference was used to call it.
So what is going on with DOM events?
The function is bound to the DOM element, and that's a Javascript object. So this refers to the object that triggers the event. Even if the same function is bound to multiple elements. this always refers to the one that triggered the function.
So now back your source code and problem. Your using this inside the .done(function(msg){....}) function. jQuery has bound the ajax object to the function so that this refers to that object.
You can change what this refers too by using the bind() function. bind lets you change what object is bound to the function so that this refers to that object instead.
$('p').click(function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "http://www.example.com/change_notification.php"
}).done(function( msg ) {
$("#changed_notification_value").text( msg );
var n_url = $('a', this).attr('href');
window.location.href = n_url;
}.bind(this));
});
Above, I didn't change your source code but just added .bind(this) to the end of your function(msg){...}.bind(this). The object this refers to outside the function is the DOM element that triggered the event, and by binding it to your callback function for done your source code should now work.

How to tell Jquery not to remove all content when using the load function?

I have a jquery function loading a php file which will output some data into a div.
The code:
function add(){
$("#div").load("add.php");
}
Now the problem is, I need to be able to use the function several times without my content in #div being overwritten. So now each time I use the function the text inside the div is deleted and the new content is inserted.
How could I fix this problem?
Try this:
function add () {
$( div ).append( $( '<div>' ).load( 'add.php' ) );
}
where div is a reference to your DIV element. (You want to have a reference of course, instead of querying for the DIV on each invokation of add().)
Update:
So, the data returned from the server is a '<li>...</li>' string, which means that you want to append it directly to the UL element:
$.get( 'addday.php', function ( data ) {
$( ul ).append( data );
});
If you plan to use the function to add the content to different </div> You can pass the function the target instead of using a static selector like this:
// Add Function //
function add($target){
$target.load('add.php');
}
// Call Function and Pass jQuery Object of Target //
add($('#firstDiv'));
add($('#someOtherDiv'));
If you plan to use the function to add to the same div you can modify the above function like this:
function add($target){
$target.append($('<span>').load('add.php'));
}
I hope this helps!
using $.ajax() you can get the response and append it to your div:
$.ajax({
url: 'add.php',
type: 'GET',
success: function(response) {
var html = $("#div").html();
$("#div").html(html + response);
// or jQuery(response).wrap('<p />').appendTo('#div');
});
$.get("add.php", function (data) {
$("#div").append(data);
});
You may use the .get() function with a specific success handler instead:
$.get('add.php', function(data) {
$('#div').append(data);
});
Try:
$.get('add.php', function(data) {
$('#div').append(data);
});

Showing and hiding buttons per ajax request in jquery

I've coded up a sort of inventory managing system and I'm adding a shipping cart so to speak to it. I'm trying to make the interface easier to use and navigate through jquery. The 'cart' is stored via sessions in php. I have a page that outputs all the inventory and I am adding buttons that allow the user to add or remove each specific item from the 'cart', but only one button should be shown based on cart status (i.e. if the item is in cart, show the remove button).
Ive got a mess of jquery code as I'm trying all sorts of approaches
heres some php:
if(isset($_SESSION['cart'][$row['bbn']])) {
echo "REMOVE FROM CART\n";
echo "ADD TO CART\n";
} else {
echo "ADD TO CART\n";
echo "REMOVE FROM CART\n";
}
here's some jquery:
$(".addtocart").each(function (i) {
if($(this).hasClass('active')){
$(this).siblings('.removefromcart').hide();
}
});
$(".removefromcart").each(function (i) {
if($(this).hasClass('active')){
$(this).siblings('.addtocart').hide();
}
});
// View_inventory add button
$(".addtocart").click(function(){
var $bbn = $(this).parent().attr("id");
var $object = this;
$.ajax({
url: "queue.php?action=add",
data: { bbn: $bbn },
type: 'GET',
success: function(){
$($object).hide();
$($object).siblings('.removefromcart').show('highlight');
}
});
});
$(".removefromcart").click(function(){
var $bbn = $(this).parent().attr("id");
var $object = this;
$.ajax({
url: "queue.php?action=remove",
data: { bbn: $bbn },
type: 'GET',
success: function(){
$($object).hide();
$($object).siblings('.addtocart').show('highlight');
}
});
});
Any suggestions as to how I should make this simpler? Ive got it working now.
first in php:
$cart = '';
$noCart = '';
if ( ! isset($_SESSION['cart'][$row['bbn']]) ) $cart = 'inactive';
else $noCart = 'inactive';
echo 'REMOVE FROM CART\n';
echo 'ADD TO CART\n';
now I present two method, the first one will execute slightly faster as it only switch classes in css, but you don't get your fancy effect. you get it in the second method.
first method
add to your css:
.inactive {display: none;}
and in js:
$(".addtocart, .removefromcart").click(function(){
var $object = $(this);
var bbn = $object.parent().attr("id");
var action = $object.find('.addtocart').length ? 'add' : 'remove';
$.get("queue.php", {"action": action, "bbn": bbn}, function (data) {
$object.addClass('inactive').siblings().removeClass('inactive');
});
});
Second method, no need for a CSS entry.
$(function () { // equivalent to $(document).ready(function () {
$('.inactive').hide();
$(".addtocart, removefromcart").click(function(){
var $object = $(this);
var bbn = $object.parent().attr("id");
var action = $object.find('.addtocart').length ? 'add' : 'remove';
var params = {action: action, bbn: bbn};
// $('#someSpinnigLoadingImage').show();
$.get("queue.php", params, function (data) {
// $('#someSpinnigLoadingImage').hide();
$object.hide().siblings().show('highlight');
});
});
});
hope this help. note: I didn't test the code, some nasty typo might have slipped through.
Additionnal note, you might want some visual effect right before the ajax call (like in the comment in version 2, or hide $object, so that the user can't multiclick it.
$object.hide()
$.get("queue.php", params, function (data) {
$object.siblings().show('highlight');
});

Categories