Ajax function, live call? - ajax

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.

Related

How to reload data in free jqgrid 4.15.4

I have a question regarding free jqgrid. My jqgrid is loading fine with all data. I have given one dropdown and search button explicitly. when I am trying to search by selecting the dropdown and clicking on search button, New data is not loading into existing grid.
Here is my fiddle: https://jsfiddle.net/x3fger4z/.
On page load, I am using this url: '/MajorsView/GetAllData', but after clicking on button I wanted to load from another url.
Below is my search button and actually I am getting data in success, but it is not reflecting on grid:
<input type="button" onclick="return myfunction();" id="btnFlagStatus" value="Search" class="btn btn-primary" />
function myfunction() {
var gendarVal = $("#gendarFlagsEnum option:selected").text();
var URL= "/MajorsView/GetFemaleData?searchKey=" + gendarVal;
$.ajax({
type: "GET",
url: URL,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(gendarVal),
datatype:"json",
success: function (data) {
//$("#grid").setGridParam({ url: URL })
$("#grid").trigger('reloadGrid');
},
error: function () {
alert("error");
}
})
}
I have tried to taken references from these but no avail
How to filter the jqGrid data NOT using the built in search/filter box
how to reload jqgrid in asp.net mvc when i change dropdownlist
jQuery button click refresh of jqGrid only firing once
If you use datatype: "json" with some url, then you can just change url to another value and to trigger reloadGrid. One don't need to make a manual Ajax request. If you use loadonce: true option additionally, then datatype of the grid will be changed to "local" to process sorting, paging and filtering locally. Every sorting, paging and filtering is nothing more as reloading the grid which has datatype: "local" with another parameters (like page, sortname, postData.filters). Thus to reload the data of the grid from the server one have to restore datatype to the initial value ("json" in your case). Thus you can use
var p = $("#grid").jqGrid("getGridParam"); // get reference to all parameters of jqGrid
p.url = "/MajorsView/GetFemaleData?searchKey=" + encodeURIComponent(gendarVal)
$("#grid").trigger("reloadGrid", { fromServer: true });
Alternatively ole can reset datatype directly (with p.datatype = "json";), but the usage of fromServer: true could be helpful in other scenarios and it makes the code more readable in my opinion. See UPDATED part of the old answer for additional information.

not able to pass the selected values through Ajax

This is the script i use for the drop down in the echo table
The echo table
Try passing your data object as text
JAVASCRIPT
$.ajax({
type: "POST",
url: "data.php",
data: JSON.stringify(data1) // use JSON.stringify();
});
Also a note is to make sure your html is echo'd or rendered out before you attempt to bind a javascript function to it. Other wise you will get an error indicating no such html element found.

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

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

CI + AJAX, Double posting + refreshing of page

So I have a normal form with 1 textarea and two hidden inputs, which I would like to post via AJAX to a CI controller I have that inserts the information into the database.
The problem I'm having is that a) the page action is still called and the output of the controller is displayed and b) because the initial AJAX request is still processed plus the extra loading of the action target the information gets inserted twice.
This is my javascript code:
$(document).ready(function() {
$("#submit-comment").click(function(){
var post_id = <?=$p->id?>;
var user_id = <?=$user->id?>;
var content = $("textarea#content").val();
if(content == '') {
alert('Not filled in content');
return false;
}
$.ajax({
type: "POST",
url: "<?=site_url('controller/comment')?>",
data: "post_id="+post_id+"&user_id="+user_id+"&content="+content,
success: function(msg){
alert(msg);
}
});
});
});
I have tried doing
...click(function(e)... ... e.preventDefault
with no luck.
What am I doing wrong? :P
Thanks
Ps. All the information is processed properly and accessed, it's just the preventing the form which is screwing it up..
Just realised I was using a input type="submit", rather than input type="button".
Doh!

Resources