Disabling a button based on an id clicked - php

I need a person who can help me solve this problem.The code below is working well with the post and the php code.
//Getting the id of a buyer and loop through
//sending a request to the seller
$(document).ready(function(){
$('.buyerRequest').click(function(){
var id=$(this).attr('id').replace('id_','');
$.post('SendingOffer.php',{id:id},function(data){
if(data=="true"){
$(this).html('<b>Offer Send</b>').css('background','#dce6f1');
$(this).attr("disabled","disabled");
}else if(data=="false"){
alert('You have reached the maximum number you can send todays');
}
});
});
});
I have tested the php code,that is,if data returned is true output alert box and is working.For instance
if(data=="true"){
alert(id);
}
However,on including this code
if(data=="true"){
$(this).html('<b>Offer Send</b>').css('background','#dce6f1');
$(this).attr("disabled","disabled");
}
and clicking the current id,i am unable to disable it and change it's attributes to offer send.
How can i deal with this problem
This is my div code
echo"<li id='td_request'><a id='id_".$fetch_num['order_id']."' class='buyerRequest' href='#".$fetch_num['order_id']."'>Send Offer</a></li>";

There were a few problems. I assume this is a button. I created a div to apply the styling to. The problem is that this is defined by scope. Inside of the post callback, this refers to the actual post object, not an html element.
<script>
$(document).ready(function() {
$('.buyerRequest').click(function() {
var id=$(this).attr('id').replace('id_','');
$.post('SendingOffer.php', {"id":id}, function(data) {
console.log(data);
if (data.length>0) {
$('#my_div').html('<b>Offer Send</b>').css('background','#dce6f1');
$('#id_my_button').prop("disabled",true);
}
else {
alert('You have reached the maximum number you can send todays');
}
});
});
});
</script>
<input type='button' class='buyerRequest' id='id_my_button' value='my_button'>
<br/>
<div id='my_div'></div>

$(this) might not be a very good idea to use inside a $.post. You better use a reference to the html object.
for example
$("#mydiv").html('Offer Send').css('background','#dce6f1');
$(this) usually refers to the current object in the context, in this case the ajax request if i am not mistaken. For example...
$(".mydiv").each(function(){
//using $(this) here refers to the current instance of .mydiv; not the DOM or the body
});
So, try this
$(document).ready(function(){
$('.buyerRequest').click(function(){
var id=$(this).attr('id').replace('id_','');
$.post('SendingOffer.php',{id:id},function(data){
if(data=="true"){
$("#**yourdivid**").html('<b>Offer Send</b>').css('background','#dce6f1');
$("#**yourdivid**").attr("disabled","disabled");
}else if(data=="false"){
alert('You have reached the maximum number you can send todays');
}
});
});
});
Working Code
<a id='id_0' class='buyerRequest' href='#0'>Send Offer</a>
<div id='responseDIV'></div>
<script>
$(document).ready(function(){
$('.buyerRequest').click(function(){
var id=$(this).attr('id').replace('id_','');
$.post('SendingOffer.php',{id:id},function(data){
if(data=="true"){
$("#responseDIV").html('<b>Offer Send</b>').css('background','#dce6f1');
$("#id_0").removeAttr("href");
}else if(data=="false"){
alert('You have reached the maximum number you can send todays');
}
});
});
});
</script>

Maybe "this" is ambiguous here, try to change into:
var currentBtn = $(this);
var id = currentBtn.attr('id').replace('id_','');
$.post('SendingOffer.php',{id:id},function(data){
if(data=="true"){
currentBtn.html('<b>Offer Send</b>').css('background','#dce6f1');
currentBtn.attr("disabled","disabled");
}else if(data=="false"){
alert('You have reached the maximum number you can send todays');
}
});
if disabled attribute does not work, you can try:
currentBtn.prop("disabled", true);
It belongs to your jQuery's version , reference: jQuery .attr("disabled", "disabled") not working in Chrome
Hope this help :)

Related

Refresh php embedded in html [duplicate]

What i want to do is, to show a message based on certain condition.
So, i will read the database after a given time continuously, and accordingly, show the message to the user.
But i want the message, to be updated only on a part of the page(lets say a DIV).
Any help would be appreciated !
Thanks !
This is possible using setInterval() and jQuery.load()
The below example will refresh a div with ID result with the content of another file every 5 seconds:
setInterval(function(){
$('#result').load('test.html');
}, 5000);
You need a ajax solution if you want to load data from your database and show it on your currently loaded page without page loading.
<script type="text/javascript" language="javascript" src=" JQUERY LIBRARY FILE PATH"></script>
<script type="text/javascript" language="javascript">
var init;
$(document).ready(function(){
init = window.setInterval('call()',5000);// 5000 is milisecond
});
function call(){
$.ajax({
url:'your server file name',
type:'post',
dataType:'html',
success:function(msg){
$('div#xyz').html(msg);// #xyz id of your div in which you want place result
},
error:function(){
alert('Error in loading...');
}
});
}
</script>
You can use setInterval if you want to make the request for content periodically and update the contents of your DIV with the AJAX response e.g.
setInterval(makeRequestAndPopulateDiv, "5000"); // 5 seconds
The setInterval() method will continue calling the function until clearInterval() is called.
If you are using a JS library you can update the DIV very easily e.g. in Prototype you can use replace on your div e.g.
$('yourDiv').replace('your new content');
I'm not suggesting that my method is the best, but what I generally do to deal with dynamic stuff that needs access to the database is the following method :
1- A server-side script that gets a message according to a given context, let's call it "contextmsg.php".
<?php
$ctx = intval($_POST["ctx"]);
$msg = getMessageFromDatabase($ctx); // get the message according to $ctx number
echo $msg;
?>
2- in your client-side page, with jquery :
var DIV_ID = "div-message";
var INTERVAL_IN_SECONDS = 5;
setInterval(function() {
updateMessage(currentContext)
}, INTERVAL_IN_SECONDS*1000);
function updateMessage(ctx) {
_e(DIV_ID).innerHTML = getMessage(ctx);
}
function getMessage(ctx) {
var msg = null;
$.ajax({
type: "post",
url: "contextmsg.php",
data: {
"ctx": ctx
},
success: function(data) {
msg = data.responseText;
},
dataType: "json"
});
return msg;
}
function _e(id) {
return document.getElementById(id);
}
Hope this helps :)

jquery post Showing loading message till success

I have following script which fetch data from server based on form parameters.
jQuery('#request_search').submit(function(e){
e.preventDefault();
var s_date=jQuery('#actualfrom').val();
var e_date=jQuery('#actualto').val();
var type=jQuery("#type").val();
var loc=jQuery("#loc").val();
jQuery.post("scripts/get_gamma_activity_type.php", {"loc":loc,"start_date":s_date, "end_date":e_date, "type":type}, function(data) {
jQuery('#report').html(data);});
});
});
This part is working and some times, based on search criteria , it takes a couple of seconds to get results. in the mean time I would like to show some GIF saying data loading. I have the GIF ready. How to implement it in the above script?
please try this.
jQuery('#request_search').submit(function(e){
$("#report").html("<div><img src='loading.gif' alt='Loading.. \n Please wait' title='Loading.. \n Please wait'` /></div>");
e.preventDefault();
var s_date=jQuery('#actualfrom').val();
var e_date=jQuery('#actualto').val();
var type=jQuery("#type").val();
var loc=jQuery("#loc").val();
jQuery.post("scripts/get_gamma_activity_type.php", {"loc":loc,"start_date":s_date, "end_date":e_date, "type":type}, function(data) {
jQuery('#report').html(data);});
});
});
Add Image with path in your html file with id attribute and then show/hide div
based on request and success.
Try below code:
Add html div in your html file :
<div id='loadingmessage' style='display:none'>
<img src='loadinggraphic.gif'/>
</div>
Try below code of jQuery:
jQuery('#request_search').submit(function(e){
$('#loadingmessage').show(); // show the loading message.
e.preventDefault();
var s_date=jQuery('#actualfrom').val();
var e_date=jQuery('#actualto').val();
var type=jQuery("#type").val();
var loc=jQuery("#loc").val();
jQuery.post("scripts/get_gamma_activity_type.php", {"loc":loc,"start_date":s_date, "end_date":e_date, "type":type}, function(data) {
jQuery('#report').html(data);});
$('#loadingmessage').hide(); // hide the loading message
});
});

jquery validation and changing of div content

I am having name, email in content of a html page. i have to validate it on clicking continue button. and also the content in the content div has to change. how can i do both on clicking the continue button. help me with some suggestions. thanks.
am using the following code for changing div content.
<script>
$(document).ready(function () {
$("#button").click(function () {
$("#content").load("<?php echo base_url().'survey/categories' ?>");
});
});
$(document).ready(function () {
$("#button1").click(function () {
$("#content").load("<?php echo base_url().'survey/budget_overview' ?>");
});
});
</script>
As i understand your question, i think what you want is to do the two tasks at the same time on click of the button. So here's some sample code assuming this is what you want. If you have any doubts just ask. And i have added just sample Email Validation Using RegExp in JavaSript at the end of the code as a function.. Get the idea, Hope this helped you,,
//
$(document).ready(function() {
//Button1 Click
$("button").click(function(){
//initialize inputs here
var email =$("#email").val;
var input1=$("#input1").val;
//Validate Inputs Here
if(IsEmail(email)==true && input1!=""){
return true
}
else{
return false;
}
//Loading the first content after validating inputs
$("#content").load("<?php echo base_url().'survey/categories' ?>");
//To Trigger the other button
$('#button1').trigger('click');
});
//Button1 Trigger Will fire Click event
$("#button1").click(function () {
$("#content").load("<?php echo base_url().'survey/budget_overview' ?>");
});
});
//Email Validation In JavaScript
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_\.\-\+])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
I think the problem is with your syntax. You have to specify a file URL in the load method like this:
$(document).ready(function(){
$("form").submit(function(){
$("#content").load("myfile.php");
return false;
});
});
You can have a look on the load documentation.

AJAX post function not working properly after first call to the function

I'm totally new to jquery and AJAX, After trying hard for 5-6 hours and searching the solution I'm asking for the help.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit").live('click',(function() {
var data = $("this").serialize();
var arr = $("input[name='productinfo[]']:checked").map(function() {
return this.value;
}).get();
if(arr=='')
{
$('.success').hide();
$('.error').show();
}
else
{
$.ajax({
data: $.post('install_product.php', {productvars: arr}),
type: "POST",
success: function(){
$(".productinfo").attr('checked', false);
$('.success').show();
$('.error').hide();
}
});
}
return false;
}));
});
</script>
and HTML+PHP code is,
$json = file_get_contents(feed address);
$products = json_decode($json);
foreach(products as product){
// define various $productvars as a string
<input type="checkbox" class="productvars" name="productinfo[]" value="<?php echo $productvars; ?>" />
}
<input type="submit" class="submit" value="Install Product" />
<span class="error" style="display:none"><font color="red">No product selected.</font></span>
<span class="success" style="display:none"><font color="green">product successfully added to database.</font></span>
As I'm pulling the product information from feed, I don't want to refresh the page, that's why I'm using AJAX post method. Using above code "install_product.php" page is handling the string properly and doing its job properly.
The problem I'm facing is, when first time I check the check box and install the product it works absolutely fine, but after first post "Sometimes it work and sometimes it won't work". As new list is pulled from feed every first post is perfect after that I need to click install button again and again to do so.
I tested the code on different browsers, but same problem. What may be the problem?
(I'm testing the code on live host not localhost)
$.live is deprecated, consider using $.on() instead.
Which function is not executing after it executes once? $.live?
Also, it should be:
var data = $(this).serialize();
not
var data = $("this").serialize();
In your example, you are looking for an explicit tag called 'this', not a scope.
UPDATE
$(function () {
$(".submit")
.live('click', function(event) {
var data = $(this).serialize();
var arr = $("input[name='productinfo[]']:checked")
.map(function () {
return this.value;
})
.get();
if (arr == '') {
$('.success')
.hide();
$('.error')
.show();
} else {
$.ajax({
data: $.post('install_product.php', {
productvars: arr
}),
type: "POST",
success: function () {
$(".productinfo")
.attr('checked', false);
$('.success')
.show();
$('.error')
.hide();
}
});
}
event.preventDefault();
});
});
Is it possible, it is missing the value at arr and showing up the error or is it like it is making call but not returning or it is not reaching the call at all?
Do a console.log to deal with debuging and check things out in firefox / chrome and see what and where is the issue.

.click() doesn't work a second time

As a beginner in jQuery I'm trying to understand how to handle .click().
My event click function :
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('.del').click(function() {
var lien = $(this).attr("title");
$.post(lien, function(data) {
$('#result').empty();
$('#result').append(data);
})
});
</script>
The span :
<span title="<?php echo base_url().'del/cat/'.$cat->idcategories ?>"class="del alignright">supprimer</span>
This works the first time but not after that. Is this happening because I'm using attr()?
Any explanation of the expected behavior would be very much appreciated.
First of all, it looks like you're missing the last bracket-parens, to close document.ready. This could (should) be causing an error. Your code should be like this:
$(document).ready(function() {
$('.del').click(function() {
var lien = $(this).attr("title");
$.post(lien, function(data) {
$('#result').empty();
$('#result').append(data);
});
});
});
For good measure, also add a space before class in your span:
<span title="<?php echo base_url().'del/cat/'.$cat->idcategories ?>" class="del alignright">supprimer</span>
Then consider the other answers of changing click to live in the event that you're somehow replacing or unbinding .del elsewhere.
By the looks of it you sending a request to delete something... If your sending the request twice it's only going to delete once..
However Try
$('.del').live('click',function(){
var lien = $(this).attr("title");
$.post(lien, function(data) {
$('#result').empty();
$('#result').append(data);
}
});

Categories