AJAX unsubmit form - ajax

I've made an ajax search filter which loads when a certain input has a value (this is the search query box):
$("#filter").keyup(function(event){
var query = document.getElementById('query').value;
if(query!=""){
$("#filter").submit();
}
else{
}
});
$("#filter").submit(function(event) {
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
$.ajax({
url: "filter_content.php",
type: "get",
data: values,
success: function(data){
$('#result').html(data);
},
});
});
Is there a way to "unsubmit" the form when there is no value? So the ajax loaded content will disapeare instead of showing the content related to the last value (that wasn't blank)?
Thanks in advance!

If you want to make the content disappear why don't you just change $('#result').html() to an empty or a default value. This could be done in the 'else' part of query check. There is nothing called unsubmit form. Hope that makes sense

Related

Kendo Tooltip is empty

dI use a kendo tooltip on cells of a column of a kendo grid but the content of the tooltip is empty.
When I use the chrome debugger, values are correctly set but there is nothing in my tooltip.
$("#gri").kendoTooltip({
filter: "span.tooltip",
position: "right",
content: function (e) {
var tooltipHtml;
$.ajax({
url: ".." + appBaseUrl + "api/Infobulle?id=" + $(e.target[0]).attr("id"),
contentType: "application/json",
dataType: "json",
data: {},
type: "GET",
async: false
}).done(function (data) { // data.Result is a JSON object from the server with details for the row
if (!data.HasErrors) {
var result = data.Data;
tooltipHtml = "Identifiant : " + result.identifiant;
} else {
tooltipHtml = "Une erreur est survenue";
}
// set tooltip content here (done callback of the ajax req)
e.sender.content.html(tooltipHtml);
});
}
Any idea ? Why it is empty ?
After looking at the dev's answer on telerik forums, i found out that you need to do something like
content: function(){
var result = "";
$.ajax({url: "https://jsonplaceholder.typicode.com/todos/1", async:false , success: function(response){
result = response.title
}});
return result;
}
changing directly with e.sender.content.html() won't work, instead we have to return the value. And i tried several approach :
i tried mimick ajax call with setTimeOut, returning string inside it or using e.sender.content.html() wont work
i tried to use content.url ( the only minus i still don't know how to modify the response, i display the whole response)
the third one i tried to use the dev's answer from here
AND check my example in dojo for working example, hover over the third try

Why does an ajax form inside of an if statement submit twice if it is submitted after first failing the condition?

Consider the code below. If myField1 does NOT equal myField2, then the alert appears. When I click okay on the alert pop up my form is still there, with all of the fields still populated with the data I had previously entered. However, when I modify the fields so that myField1 DOES equal myField2, and then submit the form it is actually submitted TWICE! Why is this?
$(document).ready(function(){
$("#myForm").submit(function() {
var myField1 = $('#myID1).val();
var myField2 = $('#myID2).val();
if(myField1 == myField2)
{
$.ajax({
type: "POST",
url: 'myFile.php',
dataType: 'html',
data: {myData:myField1,
myData2:myField2},
success: function(data){
alert(data);
}
});
return false;
}
else
{
alert('These two fields are not equal!)
}
});
});
Okay, so I found this on another question and it solves the problem:
$('#myForm').unbind('submit').bind('submit',function() {
// do stuff here...
});
By unbinding the event, then re-binding it, the form no longer submits twice.
Your submit event is going to fire the submit action of the form unless you prevent it from doing so. Running an AJAX call in does not prevent this from happening. You need to stop this yourself.
You need:
$("#myForm").submit(function(event) {
event.preventDefault()
...

datatables fnRowCallback: binding click to an event handler

Using datatables and fnRowCallback.
I am trying to bind click to each row on the 2nd column.
The table is returning the correct anchor in the 2nd column with the correct variables, but when I click on the link, ajax is sending each one as the same userid.
I think i need to use .each().click but every thing I try doesn't work.
Anybody know what im doing wrong.....
"fnRowCallback": function( nRow, aData, iDisplayIndex ) {
$('td:eq(1)', nRow).html(''+ aData[3] +'').click(function() {
var url = $('.view_log').attr("id");
var timestamp = (new Date()).getTime();
$("#table_container").hide();
$(".themenu").hide();
$("#log").show();
$.ajax({
type: "GET",
url: ''+url+'&x='+timestamp,
dataType: "html",
success: function(data) {
$("#log").html(data);
}
});
});
}
$('.view_log').attr("id"); will get only the first occurrence.
In this SO page try this in the console:
$('.post-tag') //returns all the tags element
$('.post-tag').attr('href') //returns only the href value of the first occurrance
In the handler, specify the event parameter and then use $(e.target) instead.
So $(e.target).attr('id') should do the job.
... .click(function(e){
var url = $(e.target).attr('id');
});
Demo

jQuery AJAX data to HTML

EDIT: Ok, so the solution i came up with, is basically count the characters and see the difference between the numbers. One headache i had was related with the fact that the .html() didn't showed me the with the slash, instead, . Annoying....
function verifica(){
$.ajax({
type: "GET",
datatype: "html",
url: 'icallverifica.php',
data: "valor=0",
success: function(data) {
var verificando = $('#results').html();
var verificandox = (verificando.length);
var verificador = data.length;
if(verificandox != verificador){
$('#results').html(data);
}
}
});
}
I'm creating a little script using AJAX that retrieves data from a database. The problem is that I've used setInterval and it's refreshing all the time.
I don't have a problem with too many accesses to the database, my problem is that I want the content as static as possible until there are new entries on the database:
function verifica() {
$.ajax({
type: "GET",
datatype: "html",
url: 'icallverifica.php',
data: "valor=0",
success: function(data) {
var verificando = $('#results').html();
if (verificando != "<html>"+data+"</html>") {
$('#results').html(data);}
}
});
}
The function changes the #results div introducing the database information, the thing is that I don't want to change the div content unless there are any new entries.
What I did was check on the database and compare the previous content on the div, if it's the same, it will not overwrite.
BUT, i can't put data in html format...
Try changing the success handler to:
success: function(data) {
var verificando = $('#results').html();
if (verificando != data) {
$('#results').html(data);}
}
}
Did you try this instead ?
if ( verificando != data ){
$('#results').html(data);
}
You shouldn't need to concatenate <html> to the data while comparing it.
Such comparison is a overkill. You can basically check the ids associated to each result and then just refresh only the part which is new.
May be you can send the ids along with the ajax request itself and then filter out the response and send only which are the new results.

jQuery filtering AJAX data and then replaceWith data

I am calling pages via AJAX in jQuery.
The content of these pages needs to be filtered so that i only grab a certain DIV class. In this instance 'Section1'.
This filtered data needs to replace the same data on the current page in the DIV of the same class.
I currently have this but it is not really working for me:
$("#dialog_select").live('change', function() {
//set the select value
var $optionVal = $(this).val();
//$(this).log($optionVal);
$.ajax({
type: "GET",
url: $optionVal,
dataType: "html",
cache: false,
success: function(data) {
var $filteredData = $(data).filter('.Section1');
$('.Section1').replaceWith($filteredData);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
I think your problem is likely here:
var $filteredData = $(data).find('.Section1');
$('.Section1').replaceWith($filteredData);
.filter() would only find top level elements in the response (if it's a page, that's <html>, and wouldn't have any results). .find() looks for decendant elements. Also keep in mind that if you have multiple .Section1 elements, this won't behave as expected and will have some duplication going on.
This is a tricky thing to do and I would recommend placing the data into something like a DOMParser or document.implementation.createDocument or MSXML.
if (window.DOMParser) {
parser=new DOMParser();
xmlDoc=parser.parseFromString(text,"text/xml");
}
else {
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(text);
}
is a basic code example. jQuery itself can filter on a selector with the load function. http://api.jquery.com/load/ This however has several limitations such as not being able to filter on html, head, or body tags. This is why the above method is safer.

Resources