I am developing a custom emailing system for one of my clients as an add on for the CMS I built that I give to my clients. I am using jQuery Ajax to send all the information to a PHP file that formats the email, sends a query to MySQL to get all the email address from the database, and the sends the emails using the mail(). This takes some time to do, and I am wanting the jQuery ajax to display a progress bar for each time the PHP script sends an email. I have searched for something that is similar to success: function() that receives data from the PHP script through JSON allowing jquery to update the progress of the emailing.
Does anyone have a suggestion for this? Something like this is preferable:
$.ajax({
type: "POST",
url: "example.com",
data: {"test":"test","tester":"tester"},
PROGRESS: function(data){
$("div").html(data);
},
success: function(r){
alert(r);
}
});
});
You can use the xhr object and attach an event listener to the progress event
$.ajax({
//...
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.addEventListener("progress", function(e) {
var p = e.loaded / e.total;
// update your progress bar here..
});
return xhr;
}
})
You will need to wrap this inside of a setInterval() function. You can search for AJAX Polling. But the idea here is that you cannot send information back periodically from the same PHP script while it is running, the success callback is only triggered ONCE, after the script has finished.
Related
I am building a chat and all works fine.
When person A types a message in a textarea and clicks the SEND button of an HTML form, PHP sends it to the server.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect textarea content
// inserted (appended) to mySQL table.
// collect chat content in mySQL table
// display chat content in a <div>
}
?>
(I am not posting the PHP code because it's irrelevant to the problem)
Person B gets the message because of a javascript setInterval that triggers a function that grabs the chat content from the database via AJAX and then displays the chat content for person B in a div.
setInterval(refreshChat, 1000);
function refreshChat() {
$.ajax({
url: "http://eyesonpi.com/_/php/chat.php",
type: "post",
success: function(data) {
$("#chatWindow").html(data);
},
error: function() {
$("#chatWindow").prepend("Error");
}
});
}
When I tried it on my iPhone, running IOS 10, the AJAX call fails. IOS 10 has a problem with AJAX.
https://forums.developer.apple.com/thread/64526
I tried with plain Javascript (xmlHttpRequest) and with jQuery.
I tried the chat window of my hosting company from my iPhone and their chat works. I don't know where to begin with a workaround. How can person B get the message from person A without reloading the page? Any suggestions?
Thank you.
You can try to use websockets for the chat. Or long pooling technology which allows connection to be persistent between server and client(browser or mobile app).
if you choose websockets. Then you can try to use on server side:
Workerman or Ratchet.Both, perfect do their job. All modern browsers natively support websocket, or you can use popular libraries like sockJS for cross-browser support.
Try to replace setInterval to setTimeout behaviour, otherwise previous request will be killed if the next is submitted
setTimeout(refreshChat, 0);
function refreshChat() {
$.ajax({
url: "http://eyesonpi.com/_/php/chat.php",
type: "post",
success: function (data) {
$("#chatWindow").html(data);
},
error: function () {
$("#chatWindow").prepend("Error");
}
}).always(function () {
setTimeout(refreshChat, 1000);
});
}
I have a simple chat service. I store messages, login and time etc. in Mysql database. The chat messages are displayed below with the help of Ajax & PHP
<div id="messages"> </div><!--- chats are displayed here -->
I have following Ajax code which fetches datas from Mysql in every 2 seconds. Ofcourse, everyone recommends not to do this way. It might effect server performances negatively. And its unnecessary.
$(document).ready( function() {
var destination_hashed = $("#destination_hashed").val();
var interval = setInterval( function() {
$.ajax ({
type: "POST",
url: "chat.php",
data: { destination_hashed1: destination_hashed },
success: function(data) {
$("#messages").html(data);
}
});
}, 2000);
});
In nutshell, I have two chat clients A & B. When A sends message to B, there are new rows inserted in Mysql.
So, how can I write Ajax & PHP code to fetch only when there are new rows. Rather than fetching data from Mysql every 2 seconds whether new rows inserted or not
Recently I have worked on a chat module of this kind and I can say some correction in you code
First of all don't use setInterval in the way you are using ,
Why
because in your particular code the request is send to the server every 2 second , so if the network is slow your code will have the tendency to send to much request to the server and coordination between those request would be difficult.
So what you do is
function getNewMessage(){
$.ajax ({
type: "POST",
url: "chat.php",
data: { destination_hashed1: destination_hashed },
success: function(data) {
$("#messages").html(data);
},
complete : function(){ // this will be called even if our request fail, success etc
setTimeout(function(){ // send request after 2 second from the complition of the previous request
getNewMessage();
},2000);
}
});
}
There are two approach in parsing the chat result from the ajax call
a) get the html from the ajax call (this would be slow and inefficient in case you want to extend your module in the future)
You can simpley get the html content from the ajax call on succes parameter you can append that to the table
For example : -
if the response from the server on new message is
<div class="chat">
<lable>John</lable>
Hi there !!!
</div>
Then parsing the content will be something like this
success: function(data) {
// $("#messages").html(data); //this will change the content in every request
$("#messages").append(data); // this will append the new conent
},
b) Well the other approch would be to get data in json format(a lot better approch )
For example : -
if the response from the server on new message is
{
username : 'john',
message : 'Hi there !!!'
}
Then parsing the content will be something like this
success: function(data) {
// $("#messages").html(data); this will change the content in every request
$("#messages").append('<div class="chat">'+
'<lable>'+data.username+'</lable>'+
data.message +
'</div>'); this will append the new conent
},
I'm using a great plugin - dropzone.js (dropzonejs.com) to make my site a little more fancy when registering a new user.
Basically, the user fills out a form, drops a couple images into the "dropzone", and clicks "Submit", which fires an ajax call that posts the form to a php script.
I have dropzone parameters set to enqueForUpload:false, which keeps the files from auto-uploading, since I need them to upload into uploads/$userid, after the new user id has been created. I can give dropzone header params, which I'm assuming post to the url, similar to an ajax call, instead of data: {'userid': userid}, dropzone uses headers: {'userid': userid}... However, dropzone gets initialized on document.ready, and as the userid variable isn't declared yet, dropzone fails to initialize.
I'm guessing I'm going to need to initialize dropzone with document.ready, but not give it headers just yet. Then after the ajax form processing is successful and returns userid, call dropzone to upload and give it the headers at that point. Problem is, I don't know what code would need to be called to make that happen.
Initialize Dropzone on ready:
$(document).ready(function(){
$('#dropzone').dropzone({
url: 'dropzoneprocess.php',
maxFilesize: 1,
paramName: 'photos',
addRemoveLinks: true,
enqueueForUpload: false,
});
});
Then...
$('#submit').on('click', function(){
validation crap here
$.ajax({
type: 'post',
url: 'postform.php',
data: {'various': form, 'values': here}
datatype: 'json',
success: function(data){
var userid = data.userid;
/* (and this is what I can't figure out:)
tell dropzone to upload, and make it
post userid to 'dropzone.php' */
});
});
If you use the latest Dropzone version, the parameter enqueueForUpload has been removed, in favour of autoProcessQueue which makes the whole queuing easier.
So, just call myDropzone.processQueue() as soon as you want all files to be uploaded.
To add additional parameters to the XHR you can simply register to the sending event, which gets the xhr object as second and formData as third parameter, and add the data yourself. Something like this:
myDropzone.on("sending", function(file, xhr, formData) {
// add headers with xhr.setRequestHeader() or
// form data with formData.append(name, value);
});
I used enyo answer, but i used many dropzones with data-id attribute in my page so I used:
$('div.dropzone').dropzone({
url: 'img.php'
});
var sendingHandler = function(file, xhr, formData) {
formData.append('id', $(this.element).data('id'));
};
$('div.dropzone').each(function() {
Dropzone.forElement(this).on('sending', sendingHandler);
});
Ok guys im a bit stuck here. I usually use jquery to do this but i found out it cant be done with jquery so im doing it this way ok so this is my code
var url = ("upload.php?loc="+uplocation);
var xhr = new XMLHttpRequest();
if(xhr.upload){ // check if upload property exists
xhr.open("POST", url, true);
xhr.setRequestHeader("X_FILENAME", file.name);
xhr.send(file);
}
And all it does is sends a file to a php page, but the php page doesn't upload the image which isn't what i want, so is their anyway of returning all the contents thats displayed on the page
if it was jquery i would do something like this
$.ajax({
type: "POST",
url: 'json/submitsongs.php',
data: loca,
success: function(data){
alert(data);
}
});
so my question is how to do return what ever is echoed on the php page and alert it(for debugging reasons).
thanks for your help
You would add an event listener for whatever event you desired (load, error, progress, etc). So in your case you would use the 'load' event which signifies that the file has finished loading:
xhr.addEventListener('load', onComplete, false);
The onComplete is your callback function which has the event as a parameter. This event contains the response text:
function onComplete(event) {
alert(event.target.responseText);
}
As of today, u can not upload async using Ajax.
Either use Iframes (like Google) or some nifty Flash (or Java) upload app.
Not sure, but might be HTML5 has a solution for that, but it won't be cross browser.
Is there a way to make jQuery's post method wait for server side code to complete?
In my example below, post is not waiting for my php script to finish. Though php is calling sleep(10), post returns right away, resulting in javascript clearing out the value in #temsg and changing the text of $sendmsg too early.
$('#sendmsg').click(function() {
$("#sendmsg").html("sending....");
var msg = $("#temsg").val();
var to_id = 123;
$.post("http://localhost:8888/ci/index.php/members/addMessage",
{message: msg, tomember: to_id},
function(data){
$("#temsg").val('');
$("#sendmsg").html("Leave Message");
},'json');
$("#infomsg").show();
$("#infomsg").html("Message Sent!");
setTimeout(function() { $("#infomsg").hide('slow'); }, 3000);
});
Ajax is (supposed to be) asynchronous - that means that the $.post() method is non-blocking and returns immediately and the rest of your function continues executing, and then eventually when a response comes back the success handler is called.
You can make the JS code pause until the Ajax request returns by doing a synchronous (blocking) request, but given that (most) browsers run JavaScript on the same thread as the UI that means the browser will not respond to anything until the response comes back which is horrible for the user - essentially the browser would be locked up for the ten seconds that your server-side code is sleeping.
The solution is to stick with the default asynchronous request but move the code from after your $.post() call into the success handler:
$('#sendmsg').click(function() {
$("#sendmsg").html("sending....");
var msg = $("#temsg").val();
var to_id = 123;
$.post("http://localhost:8888/ci/index.php/members/addMessage",
{message: msg, tomember: to_id},
function(data){
$("#temsg").val('');
$("#sendmsg").html("Leave Message");
$("#infomsg").show();
$("#infomsg").html("Message Sent!");
setTimeout(function() { $("#infomsg").hide('slow'); }, 3000);
},'json');
});
Ajax is asynchronous. The fact the code keeps running doesn't mean the sleep didn't occur.
That thread on the server "sleeps" , while javascript continue executing the next lines.
Example how to use async:false:
$.ajax({
url: "http://localhost:8888/ci/index.php/members/addMessage",
async: false,
data: {message: msg, tomember: to_id},
dataType: 'json',
success: function(data){
$("#temsg").val('');
$("#sendmsg").html("Leave Message");
}
});
ajax docs