slow mysql queries - php javascript ajax - php

I am using AJAX to post (method: post) the details of a form (has 35 fields), to a PHP script that does an INSERT INTO and returns "Data Saved," to the javascript (not using jquery). The javascript pops up an alert() to display the message.
The AJAX part:
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
//alert("object found");
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
document.getElementById("loader_datasave").style.display='none';
alert(xhttp.responseText);
show_modal_writedb(false);
}
};
xhttp.open("POST", "writetodb.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(str);
Server: The server is installed on a laptop connected to the LAN. I am using USBWebserver as the server software on Windows 8.
Client: There are about 7 users using the form. It runs smoothly mostly and takes about half a seconds before the message pops up, however sometimes the form takes more than a minute to return the message. It would not even load other pages saved on the server while the user is waiting for the message from the PHP script. The delay affects everyone using the form.
I thought that, the session locking by PHP, could be the reason, so I used session_write_close(), right after a session_start(), since I don't write anything to the session variables.
I am not sure what is taking time. I have tried Google Chrome, Internet Explorer, Edge, and Firefox, however the results are the same.
Should I use other servers like Wamp, or Xampp? All your help is highly appreciated.

Related

Put process into background in php while sending a data

I've been creating a php script for downloading facebook user data. Because there are a lot of data, script works about 1- 1,5 minut, before it ends. Hovewer after couple of seconds my app on Facebook appears error, suppose because there are no response from my server.
But I want to proceed app, for ask some questions for user, so how can I put that downloading process into the background.
Some part of my app which is downloading the data from Facebook is located in different server, and I send them only access token and user ID, and after successful authorization it starts to download data.
For send data to the different server I used file_get_contents() method.
EDIT: I think about something like that: put process on the server into the background, and in the user-part script kill the method which began that downloading script.
So there is some answer which I discovered and you don't need to use cron. In my project I used AJAX like this:
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","[YOUR_PHP_FILE.php]",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("[REQUEST TO THE SERVER]");
}
So that request goes in to the "background" and even if client reload or change the page it still working and (in the case of my project) it analyzes data without interruption into the end.

web application does not run on IE

I am using AJAX in form of jQuery for my client side scripting and twitter bootstrap for the layout, also using php for my server side scripting.
But the problem is the application runs fine on all other web explorers apart from Internet Explorer, does anyone have an idea to why this is happening, I cant even open a drop down in IE and I've tried both version 8 and 9.
here is a basic example of my jquery call to the server
function check_module() {
var option = $('#modules option:selected').attr('value');
$.post('modulesDropDown_1.php', 'option='+option,
function(data){
var obj = jQuery.parseJSON(data);
console.log(obj);
var name = $("#modules option:selected").text();
$("#moduleCode").html(obj.allInfo.code);
});
return false;
}
i have a lot of these in my code, where the im calling to the server and returning it as json to the client... for instance i have a drop down which populates another drop down below soon as a value first drop down is chosen (AJAX), but the second drop down should then update the page based on the value but it just does not work in IE.
Older versions of IE use a different mechanism for creating AJAX requests. Try something like this:
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
although since it doesn't run on IE 8 and 9 that might not solve it.
It would help to see a snippet of code.
(Example from http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first)

Verifying XMLHttpRequest in php

I am sending data to a PHP site using the following code:
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp= new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","addEmail.php?email="+escape(email),true);
xmlhttp.send();
xmlhttp.close;
Is there any way of making sure that the addEmail.php is being run through the XMLHttpRequest so people cant simply go to www.domain.com/addEmail.php?email=some#thing.com to make the php site eat their email and run a thousand requests on the page? Thanks in advance
The users is always able to access the php script directly, but you can protect is a bit more by adding this check to the php script:
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest')
{
//CODE HERE
}
Additionally, like Eugen Rieck mentioned, you could send a token.
That is fundamentally impossible.
You need to limit the number of requests per IP address on the server.
The standard way to do this, is to send some sort of (time dependent) token with the page that contains the AJAX code, then send the token together with the AJAX call. Users who directly use the AJAX URL will not know the current token value.

Constructing a more efficient javascript user-based chat

I am going to bed soon, so I will not be on until the morning, but I have been struggling with trying to find a javascript/jquery method that solves my problem. I am trying to make a chat box feature where once a post is submitting it is then echoed back out and users on both ends can see it. I know that I need to use javascript and or jquery. Right now I am using a very inefficiency system:
<script language='javascript' type='text/javascript'>
setInterval( function() {
$('#responsechat').load('echogetconversation.php?username=<?php echo $username; ?>&otherchatuser=<?php echo $otherchatuser; ?>');
}, 100);
</script>
The only reason that I am using it is because it is the only way I know how to project new posts to both users. I was wondering if someone knew a way to do this. Once a post is submitted, it fades into a div and both users can see it, not only the user who submitted it, so it is like a facebook chat in a way. I have no idea about any possible solutions, and have done research, but I could not find any that i could get to work. Any help and/or insight to what I should do next would be appreciated.
What you are looking for is ajax long pulling, also called Comet (it's a silly pun). The basic idea is simple--instead of polling the server, you send your ajax request and the server blocks on it until it gets a new message.
"Blocking" here simply means it does not send a response. You get your request then first up a thread (is that what you would do in PHP? I've only ever used node.js for this) and wait until something changes before sending the response back to the client.
Once the client has a response, it sends another request immediately.
There is one other trick: requests can time out. This means that the server should send a response back after a certain time even if nothing has updated.
This methodology is good if you have to support older browsers; if you can ignore those and stick to newer ones, you can use "websockets".
There are libraries that help you use websockets or fall back on Comet. I think the most popular one is socket.io.
Coincidentally, if you're not tied to PHP, I really suggest using a different server. node.js is a great option--it is a natural fit for this sort of problem and you can write the server-side code in JavaScript, which you already know. Even Facebook--the bastion of PHP--used a different language (Erlang) for their chat backend.
So, in summary: use socket.io. If you can, try using a different backend, although PHP is fine too.
If you don't want to use another language you can simply do it by AJAX..
Just set an interval and update the PHP-generated div's html.. and when you send a message then the reply would be the updated div -html so that both you and the user can assure that their message is posted successfully.. There's a snippet of my own chat system code : look:
function updMsg() {
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
var objDiv = document.getElementById('chatwid');
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("chatwid").innerHTML=xmlhttp.responseText;}
}
xmlhttp.open("GET","Msg.php?pg=1",true);
xmlhttp.send();
}
function sendMsg()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
msg=document.getElementById('msgfrm').value;
sender='<?php echo $name;?>';
xmlhttp.open("GET","Msg.php?msg="+msg+"&sender="+sender+"<?php if(isset($_GET['a']) && $_GET['a'] = 1) { echo "&a=1"; } ?>" ,true);
xmlhttp.send();
document.getElementById('msgfrm').value="";
xmlhttp.onreadystatechange=function()
{
var objDiv = document.getElementById('chatwid');
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("chatwid").innerHTML=xmlhttp.responseText;}
}
}
function interval() {
updMsg();
t=setTimeout(interval(),500);}
interval();
This code is actually only PHP and Javascript. It's not sufficient to include the whole jQuery Library just for using the AJAX capability. right?

Website. AJAX and FIREFOX problems. I dont think Firefox likes ajax..?

Working on an AJAX website (HTML,CSS,JavaScript, AJAX, PHP, MySQL).
I have multiple javascript functions which take rows from mysql, wrap them in html tags, and embed them in the HTML (the usual usage of AJAX).
THE PROBLEM:
Everything is working perfect, except when I run the site with Firefox (for once its not InternetExplorer causing the trouble).
The site is currently in the developmental stage, so its offline, but running on the localhost (WampServer, apache, Windows XP SP3,VISTA,7).
All other cross-browser conflicts have been removed, and works perfectly on all major browsers including IE, Chrome, Opera and Safari, but I get absolutely nothing from the HTTPRequest (AJAX) if the browser is Firefox.
All browsers have the latest versions.
THE CODE:
I have a series of javascript functions, all of which are structured as follows:
function getDatay(){
var a = document.getElementById( 'item' ).innerHTML;
var ajaxRequest;
try{//Browser Support Code:
// code for IE7+, Firefox, Chrome, Opera, Safari:
ajaxRequest = new XMLHttpRequest();
} catch (e){
// code for IE6, IE5:
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser is not compatible - Browser Incompatibility Issue.");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState < 4){
document.getElementById( 'theDiv' ).innerHTML = 'LOADING...';
}
if(ajaxRequest.readyState == 4){
document.getElementById( 'theDiv' ).innerHTML = ajaxRequest.responseText;
}
}
//Post vars to PHP Script and wait for response:
var url="01_retrieve_data_7.php";
url=url+"?a="+a;
ajaxRequest.open("POST", url, false);//must be false here to wait for ajaxRequest to complete.
ajaxRequest.send(null);
}
My money is on the final five lines of code being the cause of the problem.
Any suggestions how to get Firefox and AJAX working together are most welcome...
Had to post the jquery one-liner that bunch of code translates into!
$("#theDiv").text("LOADING...").load("01_retrieve_data_7.php?a="+$("#item").text());
Look at that : http://translate.google.fr/translate?js=y&prev=_t&hl=fr&ie=UTF-8&layout=1&eotf=1&u=http://www.siteduzero.com/tutoriel-3-100294-l-objet-xmlhttprequest.html&sl=fr&tl=en
Google messes up the codes so take a look at the french version for codes : http://www.siteduzero.com/tutoriel-3-100294-l-objet-xmlhttprequest.html
Before investigating your code, make sure to disable any firefox addons you've got installed.
Both ABP and Firebug are known to interfere under certain circumstances when FF tries to execute js

Categories