Getting instant ajax responce - ajax

I think there is a way to do this in ajax. But if you have a better way please let me know.
I have this code:
$interactionBox= '<input type="button" value="Pending Friend Requests('.$num_rows.')" onclick="return false" onmousedown="javascript:toggleInteractContainers(\'friend_requests\');"/>';
This code opens up a togle box where user can accept friends if there is a pending request.
So if button looks like this:
Pending Friend Request(1)
And user accepts that request user has to refresh the page for this to show as:
Pending Friend Request(0)
Is there a way to do this without refreshing the page using ajax or any other way?
Here is HTML for above code:
<div class="interactContainers" id="add_friend">
<div align="right">cancel </div>
Add <?php echo $username; ?> as a friend?
Yes

You can just get the value between brackets with JavaScript and then reduce by 1,
You can get that value (if it isn't a variable get via regexpresion:
var button = document.getElementById('buttonid'); // fill in the id
button.value = "Pending Friend Requests("+ (parseInt(button.value.match(/\d{1,10}/)) - 1) + ')';
just excute that after each accept (or not-accept)
note you should just use the function in onclick, it's not a link so it will only excute the javacript bit: so no onmousedown just onclick="javascript:toggleInteractContainers(\'friend_requests\');"
look ma: no jQuery!

Related

Showing notification with AJAX

I have a navbar on my users' panel. A part of the navbar indicates if the user has a new unread message. In this case a badge will appear next to an icon. I've simplified the codes here to make them easier to understand and read.
So this is the simplified HTML code:
<div class="btn-group msg-box">
<i class="fa fa-envelope"></i>
// this is the default state, no badge is shown
</div>
Here is the AJAX request which calls a custom function every 10 seconds:
<script type='text/javascript'>
$(document).ready(function(){
setInterval(checkMsg,10000);
});
function checkMsg(){
$.get('ajax.php',{user_id : <?php echo $user_id; ?>},function(data){
$('.msg-box').html(data);
});
}
</script>
And this is the ajax.php file content:
if(isset($_GET['user_id']){
// a few lines of code here to check if that particular user has any unread message.
// In such case a variable name $newMessage is set to 1. Now ... :
if($newMessage>0){
$data='
<i class="fa fa-envelope"></i>
<span class="badge"><i class="fa fa-info"></i></span>
';
}else{
$data='
<i class="fa fa-envelope"></i>
';
}
echo $data;
}
First of all, I know the way I've written this AJAX request is very rookie, but it works fine anyway, up to one point!
In case the user has a new message, and if they stay on a page, the code runs perfectly and shows the badge. But when the user refreshes the page or goes to another page, even-though they have a new message, that default state is shown again where there's no badge. And I know it's of course because I have specified a default state via HTML codes.
I need to know how I can keep the result of the AJAX request regardless of how many times the user refreshes the page or goes to another page.
UPDATE
I tried storing the query result in a SESSION in my ajax.php file. So instead of $data I wrote $_SESSION['data'].
Back on my HTML I made the following change:
<div class="btn-group msg-box">
<?php
if(!isset($_SESSION['data'])){
?>
<i class="fa fa-envelope"></i>
<?php
}else{
echo $_SESSION['data'];
}
?>
</div>
I made this change because I considered the fact that SESSIONS, by definition, are created and accessed globally within the domain. So once it's set, it can be checked and used on all other pages.
So that only if that SESSION isn't set, the default state should be displayed. But that as well doesn't seem to have my desired result. Still the same thing happens.
Ok, answering my own question now. :)
My UPDATE seemed to be a good idea which I tried.
The problem there was that I had written session_start(); on my main PHP file which was included in all other PHP files of the project.
So I basically thought that when the ajax.php file is called, there's no need to write session_start(); again. Because ajax.php was called inside a PHP file that had session_start(); in it already. So, I was wrong!
Adding session_start(); to the beginning of my code in ajax.php simply fixed the issue.

Bootstrap Dynamic Modals With AJAX Calling

I'm using codeigniter v3 and bootstrap v3.
I've a table for messages and for every message in table, when click on details button, a bootstrap modal show the details.
In a for loop, I print table rows and for every row (at end of the loop), I put whole bootstrap modal structure.
My question is: how could do this with ajax calling? I mean, I don't put all modal code for every table row (every message) and every time that details button clicked, I handle showing modal with ajax.
thanks for attention.
SOLVED:
I find an easy and I think better way in the bootstrap official website: Using data- attribute.
I show it with an working example for who that could not achieve better solution:
Suppose we want to fill a table body with some data (as my problem):
//just table body code
<tbody>
<?php foreach($fields as $field): ?>
<tr>
<td><?php $field->some_field; ?></td>
//other <td> elements
<td>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal"
data-time="<?php echo $field->time; ?>">Show Details</button>
</td>
</tr>
<?php endforeach; ?>
</tbody>
So in a loop, I read data (that in controller, get with model's method, and pass to view with $data['fields']). Now for showing some details in modal, I use HTML5 data attribute. Suppose, I want to show time in the modal. As you see in above code, I put time field in data-time:
data-time="<?php echo $field->time; ?>"
Now I create a modal as template (you could see whole modal structure in bootstrap official website) and put it out of loop (one modal for all table rows; dynamic data). in the following code, I put an element in the modal body (as a placeholder):
//... in the modal body section
<h4 id="time"></h4>
This element have no content, because I want to retrieve every row time filed and put it in this element. Note this will be practical with defining an id. Now some script:
//first load jquery
<script type="text/javascript">
$(document).ready(function(){
$('#myModal').on('show.bs.modal', function(event){
var btn = $(event.relatedTarget); // find which button is clicked
var time = btn.data('time'); //get the time data attribute
$('#time').text(time); //put the data value in the element which set in the modal with an id
});
});
</script>
You could define more data attribute and retrieve in this way.
I will not write the code for you, but show you the way:
You just need one modal for the whole page and it works like a template.
You need same data/informations to be displayed in the modal. This data you can pick up via Javascript/jQuery from your HTML. I prefer data attributes for that. Something like:
data-modal-title="My Title" data-modal-content="My Content"
Now you inject this data in your modal template and open the modal via Javascript.

Onclick Magento PHP

I need to click on a button and change an order state. So far I've done this:
<?php $_order = $this->getOrder() ?>
<div class="buttons-set">
<p class="btn">Button</p>
</div>
In my php I have:
public function saveState($order)
{
return $order->setState(Mage_Sales_Model_Order::STATE_NEW, true);
}
The problem is that every time the phtml loads it executes the saveState function, changing the order state everytime, dont know why. I need to execute the saveState function just where the button is clicked. Please help me with this one, i'm really stuck!
Thanks
Button doesn't link to a saveState() method. It just executes the saveState() method immediately, and links to the return value of saveState(), in this case I'm guessing that would just be the string representation of a sales/order object.
What you need to do is create a Controller whose action you can link to, via something like
<a href="<?php
echo Mage::getUrl('YourModule/YourController/YourAction')
?>">Button</a>
Please note as well that having an "action" in a simple link is generally considered bad practice: it is not RESTful.

Magento OnePageCheckout Redirect After "Place Order" Click

can anyone help with the following issue.
Once a customer in onepagecheckout clicks the „order now“ button I would like to show a custom page for 2-3seconds and the forward to either payment provider or thankyou page.
Currently I have an observer on
"checkout_type_onepage_save_order_after"
calling my custom model/method.
In this model/method I do a...
$this->_forward($url); //with $url being a custom controller/method
$res->sendResponse();
exit;
In this custom controller/method I load and render my layout the show my *.phtml – file and then...
$url = Mage::getUrl("???");
$this->_forward($url);<
$res = Mage::app()->getResponse();
$res->sendResponse();
And this is where I am lost (or maybe I am totally wrong on the whole thing).
First of all, the controller does not forward at all (whatever url or controller is given).
Second how do I know where to redirect to (if its payment provider or thank you page)
Is there a better way to „simply“ load a *.phtml after user clicks „order now“ and before he is redirected to either thank-you-page or payment-provider.
The phtml is user to load tracking code which must be placed and loaded in html.
I suggest instead that you consider doing the following:
Adding a javascript action to the place order button in the order review which will effectively issue an in-screen modal or popup
The click issuing the modal will set a timeout of 3000ms (3 seconds) which will then fire the order submit Ajax that Magento uses. This is important as the order submit and the redirect are dependent on AJAX.
This example jQuery script (requires adding jQuery to your Magento site, which is not standard) would set the timeout, issue the modal / popup I would add this code to the following file:
/app/design/frontend/[your theme]/template/checkout/onepage/review/button.phtml
Add a class to this line and remove the onclick event so you can capture the click and interject your timeout:
<button type="submit" title="<?php echo $this->__('Place Order') ?>" class="btn-place-order button btn-checkout"><span><span><?php echo $this->__('Place Order') ?></span></span></button>
<script>
$('#myform').submit(function(event) {
event.preventDefault();
//issue the popup - put your html in here:
var html = '<div style="position:absolute; top:0; left:0; min-height: 100%; width: 100%; background-color:white;"><h1>I am a popup</h1></div>';
$('body').append(html);
var self = this;
window.setTimeout(function() {
review.save();
}, 3000);
});
</script>

How can I stop a form from processing/submitting that is using jquery AJAX submission?

I have a form with two buttons, a submit button and a cancel/close button. When the user clicks submit, the entered data is validated using http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/. If everything validates, the form is submitted with jQuery/AJAX. That all works fine and dandy. I run into problems with the cancel button though. I want the cancel button to require confirmation. If the user chooses to proceed, they are taken to a page of my choosing. If they decide they don't want to cancel, then they are simply left on the page. It's the last part that isn't working.
My form code looks like this:
<form name="createPage" id="createPage" method="post" action="pager.php" class="ajax updateForm">
<input name="whatever" type="text" />
<button type="submit" id="submitQuickSave" class="submitSave"><span>save</span></button>
<button type="submit" id="submitCancel" class="submitClose" onclick='confirm_close()'><span>close</span></button>
</form>
My current cancel script looks like the following. If the user does indeed want to cancel, I unbind the form submit so that validation isn't executed. The form then proceeds to submit and includes cancel as a parameter in the action attribute. I handle the cancellation server side and direct the user to a new page.
function confirm_close()
{
var r=confirm("All changes since your last save operation will be discarded.");
if (r==true)
{
$(".ajax").unbind("submit");
}
else
{
}
}
I cannot figure out what to put in the 'else' argument. What happens is that if the users cancels the cancellation (i.e., return false), then the form still tries to submit. I cannot make it stop. I've tried several things from this site and others without success:
event.stopImmediatePropogation
.abort()
Any ideas? Basically, how can I get the cancel/close button work properly?
Consider separating your JavaScript from your HTML. With this in mind, you could write the handler for your the click event you're trying to intercept like this:
$("button#cancel").click(function($event) {
var r = confirm("All changes since your last save operation will be discarded.");
if (r) {
$(".ajax").unbind("submit");
}
else {
$event.preventDefault();
}
});
You would have to tweak your HTML and add an id attribute to the cancel button:
<button id="cancel" type="submit" value="cancel">Cancel</button>
Example here: http://jsfiddle.net/wvFDy/
Hope that helps!
I believe you just
return false;
Let me know if this works.

Resources