ajax call only works first time - php

I have a method in my controller that lets users check something called "POE Status".
This returns a string that i display in a div tag on my view. I also provide 2 buttons. one to enable POE and the other to disable. Both the enable and disable commands will return the POE status as a result.
So I'm trying to use ajax to update the page with the new status once either one of the two buttons are clicked.
What I'm noticing is that both buttons will work the first time the page is loaded. But after the initial ajax call is made and the view updated, if i try to use the buttons again, nothing happens.
I have the following HTML: (i'm not including all the html, just the parts that I think matter....)
<div class="span6" id="clientajaxcontainer">
<h2>Port POE Status: Port <?php echo $portname;?></h2>
<p><p>
<?php echo $poeStatus;?>
<button class="btn" id="enable">Enable POE</button>
<button class="btn" id="disable">Disable POE</button>
</div>
Then I have the following javascript:
<script>
//Enable POE button
$('#enable').click(function() {
alert('in POEOn');
console.log('On');
//disbled button until ajax request is done.
$(this).attr("disabled","disabled");
$('#disable').attr("disabled","disabled");
var htmlstring;
$.ajax({
url:"<?php echo site_url('controller/poeOn);?>",
type:'POST',
dataType:'text',
success: function(returnDataFromController) {
htmlstring = "<h2>Port POE Status: Port " + $('#port').val() + "</h2><p><p>" + returnDataFromController + "<button class='btn' name='enable' id='enable'>Enable POE</button> <button class='btn' name='disable' id='disable'>Disable POE</button>";
alert(htmlstring);
$('#clientajaxcontainer').html(htmlstring);
console.log(htmlstring);
}
});
//re-enable the buttons.
$(this).removeAttr("disabled");
$('#disable').removeAttr("disabled");
});
//Disable POE button
$('#disable').click(function() {
alert('in POEoff');
console.log('Off');
//disbled button until ajax request is done.
$(this).attr("disabled","disabled");
$('#enable').attr("disabled","disabled");
$.ajax({
url:"<?php echo site_url('controller/poeOff);?>",
type:'POST',
dataType:'text',
success: function(returnDataFromController) {
htmlstring = "<h2>Port POE Status: Port " + $('#port').val() + "</h2><p><p>" + returnDataFromController + "<button class='btn' name='enable' id='enable'>Enable POE</button> <button class='btn' name='disable' id='disable'>Disable POE</button>";
alert(htmlstring);
$('#clientajaxcontainer').html(htmlstring);
console.log(htmlstring);
}
});
//re-enable the buttons.
$(this).removeAttr("disabled");
$('#enable').removeAttr("disabled");
});
</script>
Can you tell me where I'm going wrong?
Thanks.

The problem is that you are not creating a "live" binding for your buttons and once you call $('#clientajaxcontainer').html(htmlstring); you replace the buttons with new elements which do not have a click binding. Try this instead:
$('#enable').live('click', function() {
//...
}
$('#disable').live('click', function() {
//...
}
If you're using jQuery 1.8 you can use the on() method instead of live(). That would look like this:
$(document).on('click', '#enable', function() {
//...
}
$(document).on('click', '#disable', function() {
//...
}
Here's the relevant documentation:
http://api.jquery.com/live/
http://api.jquery.com/on/

Related

PHP not echoing back data from form submit

My page has an html form to collect email, first name, last name and a checkbox. The form begins with this header:
<form action="echo_test.php" method="post" name='register' id='register'>
I submit the form with this button:
<div class="EMail_Pwd_JoinPage"><button class="btn_joinnow" style="color:rgb(255,255,255);" id="btn_submit" onclick="GetDate(); GetCkBx();">Submit data</button></div>
That calls this jquery function:
<script type="text/javascript">
$("#btn_submit").on("click", function (event) {
event.preventDefault();
form_data = $('form').serialize()
console.log("Okay, I'm starting");
console.log(form_data);
console.log("More Info");
GetDate();
return $.ajax({
type: "POST",
url: "echo_test.php",
data: form_data,
success: function (responseText) {
console.log("Server Reply " + responseText);
},
error: function (error) {
console.log("Okay, I failed" + error);
}
});
});
</script>
It submits to echo_test.php on my server:
<?php
echo 'Hello ' . htmlspecialchars($_POST["firstname"]) . '!';
?>
In the onclick event submit code above it should reply from the server:
success: function (responseText) {
console.log("Server Reply " + responseText);
},
But the Chrome dev console does not show any reply. The other console.log messages above do appear correctly (including the serialized form data).
I asked a similar question back in May, but the situation is different here.
Why doesn't this code echo back from the server?
Idk what does onclick attribute mean,
onclick="GetDate(); GetCkBx();"
So i think just remove onclick attribute. And here new code,
<div class="EMail_Pwd_JoinPage"><button type="submit" class="btn_joinnow" style="color:rgb(255,255,255);" id="btn_submit">Submit data</button></div>
Also update your button action jQuery code,
$("#btn_submit").on("submit",
As per my comment, remove onclick="GetDate(); GetCkBx();" from the button tag and call those two functions in the click event handler you created.
New Button Tag:
<button class="btn_joinnow" style="color:rgb(255,255,255);" id="btn_submit">Submit data</button>
in echo_test.php return the echo statement or use die().
<?php
echo 'Hello ' . htmlspecialchars($_POST["firstname"]) . '!';
return;
?>

How to send jquery post request using button

I am trying to send post request using jquery. This is the request i am trying to send
$.post("https://api.steampowered.com/IEconService/DeclineTradeOffer/v1/", {
key: "1234567891011121314151617181920",
tradeofferid: "$offerid"
}).done(function(data) {
alert("Data Loaded: " + data);
});
Inside my php i have $offerid , and key is always the same .
I want to send it on button click so i created button inside my php
$offerid = $value2['tradeofferid'];
echo '<button id="cancel-offer"> Cancel offer </button>';
how i can connect button with jquery request and send $offerid to the request ?
You just need to select the button by its id attribute, then add a click handler:
$('#cancel-offer').click(function() {
$.post("https://api.steampowered.com/IEconService/DeclineTradeOffer/v1/", {
key: "1234567891011121314151617181920",
tradeofferid: "<?= $offerid ?>"
}).done(function(data) {
alert("Data Loaded: " + data);
});
});
I would suggest you have a quick read through the jQuery documentation. It makes a great reference, and also gives you an idea of what jQuery is and is not capable of.
Modify your code like this:
php:
echo '<button id="cancel-offer" data-id="'.$offerid.'"> Cancel offer </button>';
js:
$('#cancel-offer').click(function(){
$.post( "https://api.steampowered.com/IEconService/DeclineTradeOffer/v1/", { key: "1234567891011121314151617181920", tradeofferid: $(this).attr('data-id') },function( data ) {
alert( "Data Loaded: " + data );
});
});

Jquery Ajax NyroModal Page Reload after Succes

I have site running Jquery, Ajax, PHP, and an HTML form. It uses two pages.
Pages...
Example.php & Processexample.php
When you click the edit button on example.php a form pops up in the NyroModal window posting to Processexample.php and allows you to edit customer data that's posted using Ajax.
After user clicks save on Porcessexample.php a SQL update is made and a success message is posted back to the Modal Box (end-user).
Here are the issues...
I can't get the NyroModal window to close after (data) success is called on processexample.php. I tried setting the Timeout in JQ/Javascript below but error occurs.
setTimeout("$.nyroModal.close()", 4000);
How do i get example.php page to display updated data automatically, or have the page reload after #send button is clicked and success is displayed in modal window.
HTML Form Code on processexample.php
<form id="AjaxForm" name="AjaxForm" action="#" method="post">
<input name="submitform" type="hidden" value="1"
<button id="send">Save Client</button>
JS Code on processexample.php --> See bold text in code where issue is.
$(document).ready(function() {
$("#AjaxForm").submit(function() { return false; });
$("#send").on("click", function(e){
var idval = $("#client").val();
var calval = $("#view").val();
var emailval = $("#customer_email").val();
var nameval = $("#customer_name").val();
var phoneval = $("#customer_phone").val();
var msgval = $("#customer_note").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
if(mailvalid == true && msglen >= 4) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
$.ajax({
type: 'POST',
url: 'saveclient.php',
data: $("#AjaxForm").serialize(),
success: function(data) {
if(data == "true") {
$("#AjaxForm").fadeOut("fast", function(){
$(this).before("<p><strong>Success! Your information has been updated.</strong></p>");
**setTimeout("$.nyroModal.close()", 4000);**
});
}
}
});
}
});
});
</script>
I was able to work this out myself. Use location.reload(); after the success call.

ajax inject html into a div but keep the html elements including their ids

I am using some ajax to call a php file that returns some html (an image and couple of buttons) and then place the contents of this into a div. The trouble is that I want to be able to use the id of one of the buttons that is returned from the php to hook up an event handler. The output of the source if I do view source in browser simply shows the div that the html is injected into and not the html:
<div class="displaysomething"></div>
My AJAX is as follows:
$(document).ready(function () {
getServiceDisplay();
$('#stop-service').click(function(e)
{
e.preventDefault();
runHDIMService();
});
}
function getServiceDisplay(){
$.ajax(
{
url: 'includes/dosomething.php',
type: 'POST',
success: function(strOutput)
{
$(".displaysomething").html(strOutput);
}
});
};
PHP - Ultimately returns a button amongst other stuff. This is what I need to hook up to the event handler, based on its id.
echo '<input id="stop-service" type="button" value="Run" class="'.$strRunActionButtonClass.'"/>';
If I simply put a button on the page without injecting it using AJAX into the div my button hookup code works great.
Does anybody have any ideas?
Thanks
In jQuery, the .click(... method of adding an event handler will only add the event to existing elements. New elements added later are no included.
You can use the jQuery on method of event binding to include elements added later.
$("body").on("click", "#stop-service", function(e){
e.preventDefault();
runHDIMService();
});
I have created a simple example on JSFiddle.
The problem is that
$(document).ready(function () {
getServiceDisplay();
$('#stop-service').click(function(e) // this doesn't exists yet
{
e.preventDefault();
runHDIMService();
});
This should work:
function getServiceDisplay(){
$.ajax(
{
url: 'includes/dosomething.php',
type: 'POST',
success: function(strOutput)
{
$(".displaysomething").html(strOutput);
// so after you attached the div from ajax call just register your event
$('#stop-service').click(function(e)
{
e.preventDefault();
runHDIMService();
});
});
};

How to assign the value passed to a bootstrap modal dialogue to php variable?

I am passing value to a bootstarp modal form like this -
echo '<a data-toggle="modal" data-id="ISBN564541" data-toggle="modal" title="Add this item" class="open-AddBookDialog" href="#addBookDialog">';
javascript:
<script>
$(document).on("click", ".open-AddBookDialog", function () {
var myBookId = $(this).data('id');
$(".modal-body #bookId").val( myBookId );
$('#addBookDialog').modal('show');
});
</script>
And receiving it in a text area like this -
echo '<textarea name="bookId" id="bookId"></textarea>';
Now my question is how to get this value into a php variable say $receivedValue?
You have to POST it to your PHP script using AJAX-request or plain form submission.
The only way that I can think about is to use post or get method threw the '$.ajax' method.
Here is the code that you need:
.ajax({
url : "URL of the php script", 
type: "POST",
data : //The data that you want to pass
success: function(res)
{
//code if everything passed fine
}
});
    

Categories