how can I change content in span after ajax success in MVC 4 - ajax

<div>
<span class="label">1</span>
up
</div>
Javascript
$('.click').click(function(){
//$(this).parent().find('.label').html(2);
$.ajax({
....
success: function(result){
$(this).parent().find('.label').html(2);
}
});
});
if i don't use ajax.post, value in change.. and when i use, it doesn't change.
I don't know what happen? and how can i fix it.
Give me some advices please.

$(this) is not referring to your link (its inside the $.ajax() function). Assign the label element to a javascript variable before you make the ajax call so it can be accessed inside the ajax function.
$('.click').click(function(){
var label = $(this).parent().find('.label');
// or $(this).prev('.label');
$.ajax({
....
success: function(result){
label.html(2);
}
});

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();
});
});

KNP Paginator and sortable with ajax

Is it possible to simply run the knp paginator with ajax? Is it possible at all and what is the best way to do it ?
Greetings Michael
Not sure if this is best solution, but I did it this way:
$(function(){ $('#dish-select-component-canvas').on('click', "ul.pagination a" , function(e){
$.ajax({
type: "GET",
url: $(this).attr('href'),
})
.done(function( msg ) {
$('#dish-select-component-items').html(msg);
});
e.preventDefault();
});
});
#dish-select-component-canvas is container for page. When somebody click on this canvas on link in ul.pagination (pagination is class used by knpPaginator by default as wrapper for pagination), I take href attribute of that link, and send it with ajax GET request.
Result of that request goes to appropriate div (here to #dish-select-component-items). Of course you must remember to add e.preventDefault() to prevent browser from reloading the page.

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.

jQuery(document).ready() won't work on AJAX loaded jQuery-UI widgets

I am loading some code with the jQuery.ajax() method. In this code I want to have some jQuery-UI Widgets (sliders and calenders) but they won't appear in IE.
Here some example code where you maybe can help me to understand where I am going wrong.
The Code which will load the jQuery-UI Widgets
<script>
jQuery(document).ready(function(){
jQuery.ajax({
type:'post',
url: 'file.php',
success: function (data) {
jQuery('.somediv').empty().html(data);
}
});
});
</script>
The Code which is loaded and SHOULD initialize the jQuery-UI Widgets
<script>
jQuery(document).ready(function(){
jQuery('.datepicker-div').datepicker(someoptions);
jQuery('.slider-div').slider(someoptions);
});
</script>
<div class="datepicker-div">
<div class="slider-div">
You can see that it should be very simple. For FF it works fine but not for IE.
Maybe it has nothing to do with the document-ready statement?
Just call the initializers in the success event:
<script>
jQuery(document).ready(function(){
jQuery.ajax({
type:'post',
url: 'file.php',
success: function (data) {
jQuery('.somediv').empty().html(data);
jQuery('.datepicker-div').datepicker(someoptions);
jQuery('.slider-div').slider(someoptions);
}
});
});
</script>
Of course, you should refactor that by having a function for initializations:
function Initialize(){
jQuery('.datepicker-div').datepicker(someoptions);
jQuery('.slider-div').slider(someoptions);
}
Then have your success call it, as well as the ready() ebent:
<script>
jQuery(document).ready(function(){
jQuery.ajax({
type:'post',
url: 'file.php',
success: function (data) {
jQuery('.somediv').empty().html(data);
Initialize();
}
});
});
</script>
Update
I have read your question more carefully and now I fully understand it. Your ready() is in the loaded code. Then you should be using jQuery's load():
Script Execution
When calling .load() using a URL without a suffixed selector
expression, the content is passed to .html() prior to scripts being
removed. This executes the script blocks before they are discarded. If
.load() is called with a selector expression appended to the URL,
however, the scripts are stripped out prior to the DOM being updated,
and thus are not executed. An example of both cases can be seen below:
Here, any JavaScript loaded into #a as a part of the document will
successfully execute.
$('#a').load('article.html');
Try removing the scripts prior to appending the html, then adding them back.
var outHTML = data.replace(/<script>/ig,"<div class='script'>").replace(/<\/script>/ig,"</div>");
outHTML = $(outHTML);
var script = outHTML.find("div.script").detach();
$(".somediv").html(outHTML);
var s = document.createElement("script");
s.textContent = script.text();
document.body.appendChild(s);
Edit:
.find("div.script") may need to be changed to .filter("div.script") based on what your ajax request is returning.
Ok, I didn't found out how i can solve the Problem, but i found a work around.
The work around is very simple. Because in every browser except for the IE the loading of the script via ajax works fine, we have to identify the IE and change the behaviour to not loading the script but redirect to the site I wanted to load. I am doing this all in Joomla 2.5, so there was a bit work to do but basically it was the following code wich solved the problem.
// preparing the url
// check for ie
if (jQuery.browser.msie) {
window.location(url);
} else {
// do the ajax
}

Ajax to refresh a partial view using express and JQuery?

I would like to refresh a partial view using ajax.
I kwow how to append the new data to the HTML, but I would like to know if there is a simpler way to do it.
I have partial view that does this
each x in data
li x.name
I pass the data using !=partial('test',{data:data})
I want to call a function to render the partial view again without reloading the page..
and without doing append( ... );
Any Idea??
Or other way to do it...
First, add a route for just the partial like
app.get('/mypartial', function (req, res) {
//compute data here
res.render('mypartial', {layout: false, data: data});
});
Then load the new HTML with a jQuery .get or .ajax call to /mypartial.
Then use jQuery to replace the HTML of the parent element by doing
$('#idofparentelementofyourpartial').html(responseHTML);
See also my answer to this similar question.
Use it You may get good solution
function ajaxRequest(url, succesCallBck, completeCallBck, errorCallBck)<br>
{
$.ajax({url: url
type: "POST",
dataType: "json",
complete: completeCallBck,
success: succesCallBck,
error: errorCallBck
});
}

Resources