Multiple AJAX onclick call works on only one item - ajax

So here is my HTML:
<div class='delete-item' name='filetest' ></div>
<div class='delete-item' name='anothertest' ></div>
<div class='delete-item' name='coolfile' ></div>
And my JavaScript
$(".delete-item").click(function() {
$.ajax({
type: "GET",
url: "delete_item.php",
data: "name="+$(this).attr("name")+"&dir=<?php echo $encodedDirectory; ?>",
success: function(data) {
refreshItemList();
}
});
});
So the code works but only for one item. Whichever one I click first works and the ajax call is completed succesfully. However clicking on another does not even call the function (I tried by logging it to the console and it wasn't even logging anything except for the first item.)

Try using jQuery.live instead of bind:
$(".delete-item").live('click', function() {
When you do $(".delete-item").click(...) jquery attaches an event to all .delete-item elements on the page. But in refreshItemList(); you replace them with new ones, and no event handler is attached to the new ones.
jQuery.live() attaches events on all elements matching .delete-item at the time you call it, and also .delete-item created after you call it.

Related

Form post but do not reload the page

I am stuck in this like I have never before.
My situation : I am making a shopping cart. When user click "Add" button, it posts the form and in the server side i.e inside if(IsPost){....}, corresponding item gets added to the the the cart table in my database.
Everything is fine, except it reloads the page and scrolls back to top. With a little research, I got to know that may be Ajax could help. Then I created a new .cshtml page add-to-cart.cshtnl. Now my current page doesn't reload but it opens add-to-cart.cshtml which is not how I wanted. Now I even tried to learn AJAX and try doing things looking at examples. Nothing helps. Please help!
Here is what my code looks like : P.S I am using razor in webmatrix.
<form method="post" id="productForm" action="~/add-to-cart.cshtml">
<input ............"Input Something.............../>
<button type="submit" id="add-button" >ADD</button>
</form>
At my add-to-cart.cshtml, I don't have anything on the UI. It just processes data.I don't want that page to ever load. It looks something like this:
ifIsPost(){
............ADD item to the cart table of database..............
}
Now I am convinced, AJAX is my solution but how????
Please don't give me incomplete answers. I have already wasted 3 days in it :/
Try this
$('#productForm').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data : $(this).serialize(),
success : function(response) {
//write your code here
},
error : fucntion(response) {
//write your code here
}
});
});
Put this script into <script> tag.
Note: Don't forgot to include jquery in your page.
Here is the complete working solution :
$(function () {
$('#productForm').submit(function (ev) {
var frm = $(this);
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
//Do What Ever You Wanna Do
}
});
ev.preventDefault();
});
});

URL navigation for ajax content

I have a page that gets content from other file through ajax, it works perfect, but when navigated through address bar, it s not working as the event is triggered only on click. I ve searched, but i couldnt find a solution that fits my need. I ve given my code. Somebody help.
Profile
<div id="home-content" class="container-fluid"></div>
<script>
function profile(){
$.ajax({
type: "POST",
url: "functions.php",
data: {action:profile},
success: function(response)
{
$('#home-content').html(response);
}
});
}
</script>
All i want is when i enter address like home/#profile , profile page has to be loaded and it also should be navigatable, with history entry for 'profile' page
Please Use this function
<body onload="profile()">
and remove in Onclick funtion

Render different Zend forms based on Ajax post request

I am trying to display different forms based on user type using Ajax post request. The request response works fine but I don't know how to display the form. For example, if the user selects parent then I want the parent form to be displayed and so on. I'm using ZF 1.12.
public function init() {
$contextSwitch = $this->_helper->getHelper('AjaxContext');
$contextSwitch =$this->_helper->contextSwitch();
$contextSwitch->addActionContext('index', 'json')
->setAutoJsonSerialization(false)
->initContext();
}
public function indexAction() {
$this->view->user = $this->_userModel->loadUser($userId);
//if($this->_request->isXmlHttpRequest()) {
//$this->_helper->layout->disableLayout();
//$this->_helper->viewRenderer->setNoRender(true);
if ($this->getRequest()->isPost()){
$type = $_POST['type'];
$this->view->userForm = $this->getUserForm($type)->populate(
$this->view->user
);
}
}
And here's what I have on the client side. What do I need to write in the success section?
<script type="text/javascript">
$(document).ready(function(){
$('#userType').on('change', function(){
var type = $(this).val();
select(type);
});
});
function select(type) {
$.ajax({
type: "POST",
url: "admin/index/",
//Context: document.body,
data: {'type':type},
data: 'format=json',
//dataType: "html",
success: function(data){
// what to do here?
},
error: function(XMLHttpRequest, textStatus, errorThrown) {}
});
}
</script>
<form id="type" name="type" method="post" action="admin/index">
<select name='userType' id='userType' size='30'>
<option>admin</option>
<option>parent</option>
<option>teacher</option>
</select>
</form>
<div id="show">
<?php //echo $this->userForm;?>
</div>
If your ajax request form returns you the HTML from the Zend_Form, you could simply write the HTML in the #show div.
In you view you will need to do this :
echo $this->userForm;
This way, all the required HTML will be written on the server side, before sending the response to the HTML page. In the HTML page you then just have to write the response in the right location with the method $('#show').html(data). You also have to make sure that each of your forms has the right action when you render them.
The other option would be to have all three forms hidden in your page (through Javascript) upon loading and based on the select (Generated with JS), display the right form. This way you don't have to load data from an external source and if someone have JS disabled, he still can use the application. On the other hand, this method will have each page load about 1/2 a KB more of data.

HTML form Ajax post on Success

As below, I am using a 'Form' and 'AJAX' to post the content of a text area to a URL within my site. I see the POST does work and posts the conetn to the server and on success I have tried to find the element on the page to append it, though it is not working.
Can you please advise?. The function success part of the call should be where I specificy the destination, though how do I append this data, put some ajax in the destination page html, on load etc?
<form id="test" onclick="submitForm();">{% csrf_token %}
<textarea id="red_content" name="content"></textarea>
<p>
<input type="submit" value="Publish" name="send">
</p>
</form>
function submitForm()
{
$.ajax({
url: "http://127.0.0.1:8000/Test/Trial",
data: $('#test'),
type: 'POST',
dataType: 'html',
success: function(data)
{
//$('.content-container5').setFocus();
$('.content-container5').html(data);
}
});
Many Thanks,
Tom
I'm not very familiar with submitting a single field via ajax (or in your case jQuery's ajax function). I did however have to do a similar function in a project I recently had.
I found this plugin:
jQuery Ajax Form Submit
It seemed to work really well. You may want to look into this for your project as well. In this case, instead of submitting your one field, the form will be submitted. This may be easier since you won't have to map the fields yourself. You can post the form to the same page and process it or post it to a given url.
Hope this helps.

Ajax function, live call?

I have a little box in my sidebar populated by ajax. I have 2 ajax function: one adds items to the list and the second deletes them if the user clicks on the delete button. My html is a simple unordered list like so:
<ul id="listaruta" class="lista">
<li>Item</li>
<li>Item</li>
</ul>
Everytime I call any of the two functions they will replace the ul list with an updated one (selecting the items from the database after inserting or deleting). They work fine until I want to delete right after I inserted an item to the list.
My ajax function for inserting (the other one is very similar):
var valor=$("#alcrearuta").attr('class');
$("#alcrearuta").click(function(){
$.ajax({
type: "GET",
url: "../ajax/ruta.php",
data: "url=" + valor,
dataType: 'html',
success: function(data) {
$("#listaruta").html(data);
}
});
});
My ruta.php file gives me another ul list with the same structure as the original, just with the items updated.
As far as I understand this, since I update the ul via my ajax function, the other function doesn't know that the list was updated, it only "remembers" the older list so it does nothing. If I refresh the page, it wil delete with no problem. I'm guessing this would be solved by using live()? But I have no clue...
EDIT: Ok so now I can get my ajax call to work, except that when I delete right after I update, the value that I'm passing to the ruta.php file (the variable that will help me find the field I need to delete from database) will be set to 'undefined' giving me a query like so: Select id from poi where url='undefined'
Again, if I reload, it will work. The change I did to the ajax function was:
$("#alcrearuta").live('click',function(){
$.ajax({
....
});
});
The problem is that you are saving the value of the attribute at the beginning of the request, you should save it in the click event:
$("#alcrearuta").click(function(){
var valor=$(this).attr('class');
$.ajax({
type: "GET",
url: "../ajax/ruta.php",
data: "url=" + valor,
dataType: 'html',
success: function(data) {
$("#listaruta").html(data);
}
});
});
Hope that helps.

Resources