Jquery ajax long polling error- Chrome - javascript

I am just trying ajax long polling for a simple chat application. Here is the js code. Its works well in Firefox, But when it comes to chrome, the appended text is repeated. I cant figure out what the error is.
$(document).ready(function(){
$('#chatText').keydown(function(event)
{
if (event.keyCode == 13) {
$.ajax({
type: "GET",
url: "http://example.com/Private.pl",
data: $('form#chatText').serialize(),
success: function(data) // same data posted by client to server
{
$('#chatText')[0].reset();
$("#chatLog").append(data);
$("#chatLog").scrollTop(999999)
poll();
}
})
event.preventDefault();
}
});
});
function poll() {
$.ajax({
type: 'GET',
url: 'http://example.com/Private.pl',
data: $('form#chatText2').serialize(),
success: function(msg) // other users message from server
{
$('#chatLog').append(msg);
$('#chatLog').scrollTop(999999);
},
complete: poll,
timeout: 500000
});
}
Here is the HTML snippet
<div id='chatLog' class='text-Area'></div>
<textarea name='message'></textarea>
<form id='chatText' method='post'>
<input type='submit' hidden>
</form>
<form id='chatText2' method='post'>
<input type='hidden' name='client' value='0'>
<input type='submit' hidden>
</form>

I found it. In firefox, whenever i type a new text and submit, former polling requests are aborted and a new polling is started. But in chrome, whenever i type a new message a new polling request is added with the old hanging requests. So server is responding every polling requests with same message at same time. The error is calling of poll() method everytime i send a new message..

Related

Calling same controller's method using ajax GET and POST type

Hi I am a newbie to Grails and Groovy. Please help me to solve the below issue related to calling controller's method using ajax call.
The scenario behind the code is to recover the password using the username whenever the user is unable to remember the password. I have explained the code flow in detail below.
Application begins with the below auth.gsp page:
<form action='${postUrl}' method='POST' id='loginForm' autocomplete='off'>
<input type='text' name='j_username' id='username'/>
<input type='password' name='j_password' id='password'/>
<input type='submit' id="submit" value='${message(code: "default.button.login")}'/>
<g:message code="etranscripts.forgotPassword"/>
</form>
When I click on the Forgot password link of the anchor tag, it will call the below ajax method:
<script>
$(document).ready(function () {
$('#recovery-link').click(function () {
var url = $(this).attr('recovery-url')
$.ajax({
url: url,
dataType: "html"
}).done(function (html) {
$('#loginForm').replaceWith(html)
$('#sign-in-instruct').text('<g:message code="js.resetEnterName"/>')
}).fail(function (jqXHR, textStatus) {
console.log("Request for url failed: " + url)
})
event.preventDefault()
return false
});
});
The controller method for the above call is as below.
def recoverPassword = {
println "RecoverPassword method of ctrl....."
if (!request.post) {
// show the form
render(template: "recoverPassword" )
return
}
//some other stuff based on the input conditions.
The successful output template for the above ajax call is:
<div id="recover-password" >
<ul>
<li>
<span><g:textField name="username" id="username" value="" /></span>
<input type='submit' id="submit-username-link" recovery-url="<g:createLink controller='recoverPassword' action="recoverPassword"/>" value='Submit'/>
</li>
</ul>
Till here my code works perfect. But the issue begins from here.
i.e When I enter some value in the username field of the template and click on submit, it should call the below ajax method.
$(document).on('click', '#submit-username-link', function (event) {
var url = $(this).attr('recovery-url')
var username = $('input#username').val();
$.ajax({
url: url,
type: "POST",
data: {username:username},
dataType: "json"
}).done(function (responseJson) {
$('#sign-in-instruct').text(responseJson.message)
$('div.copyright').css('margin','74px 0px 0px 140px')
$('#home-link').show()
if ( responseJson.status == 'success') {
$('#recover-password').remove()
}
}).fail(function (jqXHR, textStatus) {
$('#recover-password').remove()
$('#sign-in-instruct').text(textStatus)
console.log("Failed to send the email " + textStatus)
})
event.preventDefault()
return false
});
The thing is, url refers to the same method of the controller but the only change is POST type is used and that will be taken into consideration inside the method using if conditions.(i.e some other stuff of the controller)
These GET and POST type of method calls are configured as shown below in the URLMappings.groovy file.
"/recoverPassword/recoverPassword"(controller: 'recoverPassword') {
action = [GET: "recoverPassword", POST: "recoverPassword"]
}
The whole summary of this question is, for the same method of controller, GET request is working but POST type of ajax call is not able to reach the controller's method.
Am I doing anything wrong over here? Please help me to solve this issue. Thanks in advance :-)
Overcomplicated. Why don't you use separate function in controller for GET (rendering the form) and separate function for POST (for handling the recovering the password)?
Check out also https://en.wikipedia.org/wiki/KISS_principle
Change input Type submit to button
<input type='button' id="submit-username-link" recovery-url="<g:createLink controller='recoverPassword' action="recoverPassword"/>" value='Submit'/>

Convert xhr ajax call to xdr for IE8

I have asp web page responsible of uploading file using ajax.
the html code of the form is:
<form method="post" action="ajax/firmwareUpload" enctype="multipart/form-data" id="uploadform" name="uploadform">
<div class="left">
<span id="lang502009" title="502009">Firmware File</span>:
<input name="download image file" id="uploadfilename" type="file">
</div>
<div class="right">
<div class="upload" id="uploadManual">
<input type="submit" class="button button-blank" value="Upload"/>
</div>
</div>
</form>
the ajax code is :
$("#uploadform").submit(function(e) {
$.ajax({
url: 'ajax/firmwareUpload',
type: 'POST',
data: new FormData(this),
processData: false,
contentType: false,
enctype: 'multipart/form-data',
success: function(data) {
if (data.error) {
$("body").load("subpage/upgradefail.asp");
setTimeout(backToIndex, 5*1000);
}
else {
var time = data.return;
$("body").load("subpage/upgradewait.asp");
setTimeout(backToIndex, time*1000);
}
},
error: function(data) {
alert("Operation could not be completed");
}
});
e.preventDefault();
});
This code works well as wanted for different browsers like firefox, chrome, safari, Opera. but I got problems with IE8 in the ajax response.
But the request works fine and can receive from the browser and send to the browser the response. But when IE8 receives the response it can't access to the success or error functions.
After a lot of searches I found in the internet that the problem is because IE8 have some problems with xhr communication. And the ajax code can be better with xdr.
My problem here is how I can convert my ajax code to xdr?
The problem especially is with processData, enctypes attributes and "new new FormData(this)". and is there modification that should be done in the tag form attributes?

Run JS after div contents loaded from AJAX

There are a ton of proposed answers to my question, but even with all the answers I have found, I can not seem to get any to work. I can make the JS work by adding a delay in execution of the code, but I can't rely on a delay to execute the JS after div has finished loading it's HTML.
I'm creating a page where users can search for an item, and the results are displayed in a div using AJAX. I need some JS to run after the div's html has finished loading. Some of the results data will be hidden until a user clicks on it. The JS code to accomplish this is what I am trying to run once the div finishes loading.
I have tried the following extensively with no luck anywhere:
.load
.ajaxComplete
.complete
.success
.done
Document.ready
I'm sure there are a few others as well, but my brain is just too beat up from dealing with this to remember everything I've tried so far.
My HTML:
<form name ="CardName" method="post" action="">
<div "class="w2ui-field">
<div> <input type="list" Name="CardName" id="CardName" style="width: 80%;"></div>
</div>
<div class="w2ui-buttons">
<input type="submit" name="search" style="clear: both; width:80%" value="Search" class="btn">
</div>
</form>
<div class="Results" id="Results" name="Results"></div>
My JS:
$(function() {
$("#CardSearch").bind('submit',function() {
var value = $('#CardName').val();
$.ajax({
method: "POST",
url: "synergies.php",
data: {value}
})
.success(function(data) {
$("#Results").html(data);
})
.complete(function() {
alert("div updated!"); //Trying to run JS code AFTER div finishes loading
});
return false;
});
});
If there is anything else that could help with this request just let me know!
Thanks in advance!
Note that success and failure are options that you should provide to the $.ajax call, not the returned promise. Also, bind is deprecated in favour of on since jQuery 1.7. Finally, you need to give the value that you're posting to your PHP page a key so that it can be retrieved via $_POST. Try this:
$("#CardSearch").on('submit', function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: "synergies.php",
data: {
CardName: $('#CardName').val()
},
success: function(data) {
$("#Results").html(data);
},
complete: function() {
alert("div updated!"); //Trying to run JS code AFTER div finishes loading
}
})
});
You can then retrieve the value sent in your synergies.php file using $_POST['CardName'].
If you prefer to use the method provided by the returned promise, you can do that like the below, although the result is identical.
$("#CardSearch").on('submit', function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: "synergies.php",
data: {
CardName: $('#CardName').val()
}
}).done(function(data) {
$("#Results").html(data);
}).always(function() {
alert("div updated!");
})
});
you can try Synchronous Ajax request, demo code is given below:
$(function() {
$("#CardSearch").bind('submit',function() {
e.preventDefault();
sendData = $('#CardName').val();
reqUrl = "synergies.php";
// this will wait until server request complete
var ajaxOpt = AjaxSyncRequest(reqUrl, sendData);
// after complete server request
ajaxOpt.done(function(data) {
$("#Results").html(data);
});
});
});
function AjaxSyncRequest(reqUrl, sendData) {
var ajaxData = $.ajax({
method: "POST",
url: reqUrl,
data: {
data: sendData
}
});
return ajaxData;
}

How to test for success and redirect web page after product added in opencart?

I'm using the following form to add a product to the opencart shopping cart. The problem I'm having is that after the product adds it doesn't redirect to the shopping cart but just shows a page with a product successfully added notification.
here's the form:
<form action="purchase/?route=checkout/cart/add" id="addToCartForm" method="post">
<input type="hidden" name="product_id" value="40">
<input type="hidden" name="quantity" id="quantity_field" value="">
<input type="hidden" name="price" value=>
<input type="submit" alt="Order Now" title="order now" value="Order Now test">
</form>
and the javascript code:
<script>
$(document).ready(function() {
$('form#addToCartForm input[type="submit"]').click(function(e) {
e.preventDefault(); // prevent the form from submitting
$.ajax({
type: 'POST',
dataType: 'json',
url: 'purchase/index.php?route=checkout/cart/add'
data: 'product_id=' + $('form#addToCartForm input[name="product_id"]').val() + '&quantity=' + $('form#addToCartForm input[name="quantity"]').val(),
success: function(json) {
window.location = 'purchase/index.php?route=checkout/cart';
console.log('add success');
}
});
});
});
</script>
after the form is clicked the page redirects to http://*****/purchase/?route=checkout/cart/add and the page message reads "{"success":"Success: You have added Product Name</a> to your shopping cart</a>!","total":"4 item(s) - \u00a64.40"}"
So, it does add a product, but the redirect upon 'success' doesn't seem to do anything.
the javascript console doesn't output anything with console.log('add success'); (or it moves to the shopping cart add page too quickly to see)
thanks for any help
First remove action attribute from form, its not required (and may cause confusion in debugging)
and then use following javascript
$('form#addToCartForm').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'purchase/index.php?route=checkout/cart/add'
data: 'product_id=' + $('form#addToCartForm input[name="product_id"]').val() + '&quantity=' + $('form#addToCartForm input[name="quantity"]').val(),
success: function (json) {
window.location = 'purchase/index.php?route=checkout/cart';
console.log('add success');
}
});
});
in your question part of your ajax requested is commented out, is it really the case or it just got commented while posting to SO ?
I'm not sure where the element with ID 'personalVirtualPrivateServerForm' is from, but clicking a button doesn't necessarily allow you to perform the e.preventDefault() you are attempting.
In your case, you are essentially saying, on click of the button perform an action, but you want to say something like:
$('form#addToCartForm').submit(function(e) {
e.preventDefault();
.... (rest of code here) ....
});
Basically, your form is submitting before you have a chance to redirect, when you want to stop the form submission and then send it via your $.ajax submit. That should allow your success callback to execute.

post method not working

I want to submit form data using post using ajax because in form post after submit it is redirected to a new page.
<form id="myContactForm">
<p>
<label for="byour_name">Your name</label><input type="text" name="byour_name" value="" id="byour_name">
</p>
<p>
<label for="byour_email_address">Your email address</label><input type="text" name="byour_email_address" value="" id="byour_email_address">
</p>
<p>
What's on your mind?<br>
<textarea name="Message" rows="10" cols="25"></textarea>
</p>
<p>
<input type="submit" value="Send it!" onClick="sendMail()">
</p>
</form>
function sendMail() {
$.ajax( {
url: "/email",
type: "POST",
data: $("#myContactForm").serialize(),
success: function( response) {
alert(response);
},
error: function() {
alert('failure');
}
});
}
Every time I make request error function is executing.I am writing app on google app engine. I am keep getting this error:
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
My post request handler is:
def post(self):
Content = self.request.get("Message")
byName = self.request.get("byour_name")
byEmailAddress = self.request.get("byour_email_address")
gmailUser = 'id#gmail.com'
gmailPassword = 'password'
dataSend = byName
mail.send_mail(sender = gmailUser,
to = gmailUser,
subject ="Email Sent By : "+ byName + "#" + byEmailAddress,
body = Content)
self.response.out.write(byEmailAddress)
And after I click submit button URl changes to:
http://localhost:8080/?byour_name=username&byour_email_address=userEmail#gmail.com%40gmail.com&Message=mlm%0D%0A#contact
as I am making a get request can someone help me..But how post request changes to get request.
You're not preventing the default submit. Either return false from your sendMail function, or take the event as a parameter and call preventDefault() on it.
Please remove form tag and the get the desired values by id and then use ajax method. Because may be ajax post and form request method are conflicting. I think form has default get method as you said earlier may be that's the reason whenever you click on submit first ajax post make request soon after form get method and may be that's the reason the error is thrown by your server.
I think I know what your trying to do , to fix this you can do the following:
remove onclick="sendMail()"
and change your JavaScript function to something like:
$('#myContactForm').submit(function () {
$.ajax( {
url: "/email",
type: "POST",
data: $("#myContactForm").serialize(),success:
function( response) {
alert(response);
},
error: function(){
alert('failure');
}
});
});

Categories

Resources