I have a list of results that are shown on a particular page and these are updated at regular intervals using a simple AJAX request. An input form allows me to filter these results, but as the data is updated every few seconds, the input form doesn't work properly as it refreshes all the data. Is there any way for the AJAX to not update when there is a value in the form input field?
Below is the HTML code:
<div id="my-query-results" class="visible">
<div>
<form class="searchboxInput" action="#">
<input id="kwd-my-query-results" type="text" value="">
</form>
</div>
<div id="my_recent_queries">
<span class="loading_placeholder">Loading ...</span><br />
<img src="../img/ajax-loader.gif" />
</div>
</div> <!-- my query results -->
Below is the AJAX request that I was using:
if( $("#kwd-my-query-results").val() != "") {
function updateMyQueries() {
$.ajax({
url: "/myrecentqueries",
cache: false,
success: function(html){
$("#my_recent_queries").html(html);
}
});
setTimeout("updateMyQueries()", 600000);
}
updateMyQueries();
} else {
function updateMyQueries() {
$.ajax({
url: "/myrecentqueries",
cache: false,
success: function(html){
$("#my_recent_queries").html(html);
}
});
setTimeout("updateMyQueries()", 4000);
}
updateMyQueries();
}
The above if else statement just didn't seem to work. It would evaluate to the else statement once a value was present in the input box. I think I also tried length(), but that didn't seem to work either. Any other way of approaching this?
Update
I tried the following given the suggestion below, and it works to some degree. It loads the results initially, allows me to search them without reloading the data, but then it doesn't reload the results at regular intervals, even when there is no text in the input field...
$(function(){
setTimeout(updateMyQueries(), 4000);
});
function updateMyQueries(){
if ($("#kwd-my-query-results").val() == "") {
// do ajax call
$.ajax({
url: "/myrecentqueries",
cache: false,
success: function(html){
$("#my_recent_queries").html(html);
}
});
}
}
I would start by moving the updateMyQueries function out of the if statement then maybe something like this.
$(function(){
SetInterval(updateMyQueries(), 4000):
})
function updateMyQueries(){
if($("#kwd-my-query-results").Val() == ""){
// do ajax call
}
}
EDIT - this will work
setInterval(function (){
if($("#search").val() == ""){
// Ajax call here
}
}, 4000);
Related
I have ajax request:
<script>
$("#abc_form_submit").click(function(e) {
e.preventDefault();
//........
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $("#abc_form").serialize(), // serializes the form's elements.
success: function(data)
{
if(data.success == 'false') {
// show errors
} else {
// SUBMIT NORMAL WAY. $("#abc_from").submit() doesnt work.
}
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
And php
.....
return $this->paypalController(params, etc...) // which should redirect to other page
.....
How should i make that ajax request if success, submit form normal way, because now if I redirect (at PHP) its only return response, but i need that this ajax request would handle php code as normal form submit (if success)
Dont suggest "window.location" please.
I would add a class to the form to test if your ajax has already occured. if it has just use the normal click funciton.
Something like:
$('form .submit').click(function(e) {
if (!$('form').hasClass('validated'))
{
e.preventDefault();
//Your code here
$.post(url, values, function(data) {
if (success)
{
$('form').addClass('validated');
$('form .submit').click();
}
});
}
}
Why don't you use a result variable that you update after a succesful AJAX request?
<script>
$("#abc_form_submit").click(function(e) {
e.preventDefault();
// avoid to execute the actual submit of the form if not succeded
var result = false;
//........
$.ajax({
type: "POST",
url: url,
dataType: 'json',
async: false,
data: $("#abc_form").serialize(), // serializes the form's elements.
success: function(data)
{
if(data.success == 'false') {
// show errors
} else {
// SUBMIT NORMAL WAY. $("#abc_from").submit() doesnt work.
result = true;
}
}
});
return result;
});
</script>
I've had this issue before where I needed the form to submit to two places, one for tracking and another to the actual form action.
It only worked by submitting it programatically when you put the form.submit() behind a setTimeout. 500ms seems to have done the trick for me. I'm not sure why browsers have trouble submitting the form programatically when they are attempting to submit them traditionally, but this seems to sort it out.
setTimeout(function(){ $("#abc_from").submit(); }, 500);
One thing to keep in mind though once it submits, that's it for the page, it's gone. If you still want whatever processes are running on the page to run, you will need to set the target of the form to _blank so that it will submit in a new tab.
I have a simple page that takes a form and makes a jsonp ajax request and formats the response and displays it on the page, this is all fine, but I wanted to add it so that if the form was populated (via php $_GET variables) then the form would auto-submit on page load but what happens instead is that the page constantly refreshes despite the submit function returning false.
Submit Button (just to show it doesn't have an id like submit or anything)
<button type="submit" id="check" class="btn btn-success">Check</button>
jQuery
$(document).ready(function() {
$('#my_form').on('submit', function() {
var valid = 1;
$('#my_form .required').each(function() {
if ($(this).val() == '') {
$(this).parents('.form-group').addClass('has-error');
valid = 0;
} else {
$(this).parents('.form-group').removeClass('has-error');
}
});
if (valid === 1) {
$.ajax({
url: '/some_url',
data: $('#my_form').serialize(),
type: 'GET',
cache: false,
dataType: 'jsonp',
success: function(data) {
var html = 'do something with data';
$('#results').html(html);
},
error: function() {
$('#results').html('An error occurred, please try again');
}
});
} else {
$('#results').html('Please fill in all required fields');
}
return false;
});
});
The part I added just after the $(document).ready(function(){ and before the submit was:
if ($('#input_1').val() != '' || $('#input_2').val() != '') {
// $('#check').trigger('click');
$('#my_form').submit();
}
Both those lines have the same effect but I am doing the same in another project and it works fine, as far as I can see, the only difference is the jQuery version, I'm using 1.11 for this page.
Update
Apologies, I seem to have answered my own question, I thought that since the programmatic submit was the first thing in $(document).ready(function(){ then maybe it was the case that the actual submit function wasn't being reached before the event was triggered so I simply moved that block after the submitfunction and it now works fine.
url: ''
it seems like you are sending your ajax request to nothing.
just an additional: if you want to submit your form through jquery without using AJAX, try
$("#myForm").submit();
it will send your form to the action attribute of the form, then redirect the page there.
I'm using jQuery and am preventing the submission of a form, then based on an ajax response will submit the form. The problem I'm finding is that I often have to submit the form twice. The first time, it shows the loader, but it doesn't get seem to call any actions within the ajax's success function. If I click it a second time, it submits (if it's been validated). It also seems to work the first time, after I go through this. So if I try again, it'll work the first time. So maybe it's a cache issue? Here's the javascript I have:
$('#submit_zipcode_frm').submit(function(event){
event.preventDefault();
var self = this;
$(".loader img").show();
z = $('#zipcode');
if(z.val() != '' && z.val().length == 5) {
var value = z.val().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
var intRegex = /^\d+$/;
if(!intRegex.test(value)) {
$(".loader img").hide();
error($(".zipcode_field"));
return false;
}
} else {
$(".loader img").hide();
error($(".zipcode_field"));
return false;
}
$.ajax({
url: "/ajax/save/zipcode",
type: 'GET',
async: false,
cache: false,
dataType: 'html',
data: {zipcode: $('.zipcode_field').val()},
success: function(data) {
if(data == 'false'){
$(".loader img").hide();
error($(".zipcode_field"));
return false;
}else{
self.submit();
getList();
}
}
});
});
and here's the markup:
<form id="submit_zipcode_frm" class="submit_zipcode" method="post" action="/go" target="_blank">
<div class="zipcode_container">
<span class="loader">
<img src="/assets/img/loader.gif" style="display: none;"/>
</span>
<input type="text" class="zip_input zipcode_field ghost" id="zipcode" name="zipcode" value="Enter your Zip"/>
<div class="start_btn">
<button type="submit">Submit</button>
</div>
<div class="clear"></div>
</div>
<div class="clear"></div>
</form>
Any suggestions or ideas would be really appreciated. Thank you!
EDIT:
Just to clarify the steps here:
User clicks the submit button
JavaScript show's the loader and validates the length and and type of the value entered
If that passes, an ajax lookup is used to truly validate it's a valid USPS zip code
If it is, the form is submitted and a function getList() is called
If it's not, error is thrown
Here is my html form
<div id=create>
<form action=index.php method=get id=createform>
<input type=text name=urlbox class=urlbox>
<input type=submit id=createurl class=button value=go>
</form>
</div>
<div id=box>
<input type=text id=generated value="your url will appear here">
</div>
Here is the javascript im trying to use to accomplish this;
$(function () {
$("#createurl").click(function () {
var urlbox = $(".urlbox").val();
var dataString = 'url=' + urlbox;
if (urlbox == '') {
alert('Must Enter a URL');
}else{
$("#generated").html('one moment...');
$.ajax({
type: "GET",
url: "api-create.php",
data: dataString,
cache: false,
success: function (html) {
$("#generated").prepend(html);
}
});
}return false;
});
});
when i click the submit button, nothing happens, no errors, and the return data from api-create.php isnt shown.
the idea is that the new data from that php file will replace the value of the textbox in the #box div.
i am using google's jquery, and the php file works when manually doing the get request, so ive narrowed it down to this
Because you're binding to the submit click instead of the form's submit.. try this instead:
$('#createForm').submit(function() {
// your function stuff...
return false; // don't submit the form
});
Dan's answer should fix it.
However, if #createurl is not a submit/input button, and is a link styled with css etc., you can do this:
$('#createurl').click(function () {
$('#createForm').submit();
});
$('#createForm').submit(function () {
// all your function calls upon submit
});
There is great jQuery plugin called jQuery Form Plugin. All you have to do is just:
$('#createform').ajaxForm(
target: '#generated'
});
I attempted to ask this question last week without a resolution. I am still unable to get this to work. What I would like to do is submit data entered through a WYSIWYG javascript editor to a JQuery script I have that will first tell the user if they are trying to submit an empty textbox The last thing I need it to do is tell the user if their data was entered successfully or not.
I am having a problem inside the JQuery script as nothing is being executed when I click the save button.
This editor uses javascript submit() that is tied to a small save icon on the editor. When the user presses the button on the editor, it fires the function I have in the form tag. That's about as far as I was able to get.
I think there is an issue with the form tag attributes because when I click anywhere on the editor, the editor jumps down off the bottom of the screen. I believe it has something to do with the onclick event I have in the form tag.
The first part of the JQuery script is supposed to handle form validation for the textarea. If that's going to be really difficult to get working, I'd be willing to let it go and just handle everything server side but I just need to get the data POSTed to the JQuery script so that I can send it to my php script.
Thanks for the help guys.
<form name="rpt" class="rpt" id="rpt" action="" onclick="doSave(); return false;">
function doSave()
{
$(function()
{
$('.error').hide();
$(".rpt").click(function()
{
$('.error').hide();
var textArea = $('#report');
if (textArea.val() == "")
{
textArea.show();
textArea.focus();
return false;
}
else
{
return true;
}
var dataString = '&report='+ report;
alert (dataString);return false;
$.ajax({
type: "POST",
url: "body.php?action=customer",
data: dataString,
dataType: 'json',
success: function(data){
$('#cust input[type=text]').val('');
var div = $('<div>').attr('id', 'message').html(data.message);
if(data.success == 0) {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-error');
} else {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-success');
}
$('body').append(div);
}
});
return false;
});
});
}
There are a few things you need to change. Firstly this:
<form name="rpt" class="rpt" id="rpt" action="" onclick="doSave(); return false;">
isn't the jQuery way. Plus its not the click() event you want. Do this:
<form name="rpt" class="rpt" id="rpt" action="">
<script type="text/javascript">
$(function() {
$("#rpt").submit(do_save);
});
</script>
The construction:
$(function() {
..
});
means "when the document is ready, execute this code". It is shorthand for and exactly equivalent to the slightly longer:
$(document).ready(function() {
..
});
This code:
$("#rpt").submit(doSave);
means "find the element with id 'rpt' and attach an event handler to it such that when the 'submit' event is executed on it, call the do_save() function".
And change doSave() to:
function doSave() {
$('.error').hide();
$(".rpt").click(function() {
$('.error').hide();
var textArea = $('#report');
if (textArea.val() == "") {
textArea.show();
textArea.focus();
return false;
} else {
return true;
}
var dataString = '&report='+ report;
alert (dataString);return false;
$.ajax({
type: "POST",
url: "body.php?action=customer",
data: dataString,
dataType: 'json',
success: function(data){
$('#cust input[type=text]').val('');
var div = $('<div>').attr('id', 'message').html(data.message);
if (data.success == 0) {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-error');
} else {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-success');
}
$('body').append(div);
}
});
});
return false;
}
Note: return false is in the correct place now so it actually prevents the form submitting back to the server. action="" just means the form will submit back to its current location so you have to prevent that.
function X() {
$(function() {
//... things you want to do at startup
});
};
Doesn't do what you want. Nothing is ever executed, because you never tell it to be executed.
You might want to try something like:
<script type="text/javascript">
jQuery(function($) {
//... things you want to do at startup
});
</script>
Also, you want the onsubmit event of the form. You can use
$('#theform').submit(function() {
//... perform the ajax save
});
In addition, you may want to look into the Form plugin.