I am new to Web Development. I'm creating a web application where I need to use ZMQ Library for receiving data continuously and update a html table in real-time.
I tried a lot and just succeeded in receiving a single data packet. Later I'm calling the function recursively to get all data packets. But, by the time I call the function, I already lost some packets in the gap.
Following is the javascript function I'm using in index.php and test.php for receiving data using ZMQ:
Javascript function inside index.php
function samp(result)
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var x=document.getElementById('PageTable');
var rowCount = document.getElementById("PageTable").rows.length;
for (var i = 0; i < rowCount; i++)
{
if(x.rows[i].cells[2].innerHTML == xmlhttp.responseText)
{
x.rows[i].cells[3].innerHTML=xmlhttp.responseText;
}
}
samp(result);
}
};
xmlhttp.open("GET","test.php?q="+result,true);
xmlhttp.send();
}
test.php for receiving data using ZMQ
<?php
$Params = $_REQUEST["q"];
$context = new ZMQContext();
$subscriber = new ZMQSocket($context, ZMQ::SOCKET_SUB);
$subscriber->connect("tcp://localhost:5000");
$mnemonic = explode(" ", $Params);
foreach ($mnemonic as $value)
{
if($value!="")
{
$subscriber->setSockOpt(ZMQ::SOCKOPT_SUBSCRIBE, $value);
}
}
$contents = $subscriber->recv();
echo $contents;
I even tried running the php script inside the javascript function but had no luck. I also tried using an infinite loop in test.php to receive data as following but now as the loop is not ended I stopped receiving even a single packet.
while(true)
{
$contents = $subscriber->recv();
echo $contents;
}
Any help to solve this problem or even suggestion to any different approach is highly appreciated. Thank you.
I develop a Validation Form with Javascript All think as right
but I want when Al think are accepted send the information to the php file
How I can make that ?
The HTML code :
<?php
if(isset($_GET['submit'])){
$message = '';
$email = '';
$name ='';
$message = $_GET['comment'];
$email = $_GET['commentMail'];
$name = $_GET['commentName'];
$to = "emailme";
$subject = 'New Message';
$message = " Le nom : ".$name."<br><br>".$message."<br><br> Email : ".$email;
$header = "$email";
if(mail($to, $subject, $message, $header)){
echo '<b style="color: green">Messange Send</b>';
}
else{
echo '<b style="color: red">Sommthing wrong</b>';
}}
?>
<html>
<head>
<title>Contact</title>
<meta charset="UTF-8">
</head>
<body onload="randNums()">
<form>
<input id="commentName" onkeyup="validateName()" name="name" type="text" placeholder="Name"><label id="commentNamePrompt"></label><br>
<input id="commentMail" onkeyup="validateMail()" name="mail" type="text" placeholder="Mail"><label id="commentMailPrompt"></label><br>
<input id="commentPhone" onkeyup="validatePhone()" name="phone" type="text" placeholder="Phone"><label id="commentPhonePrompt"></label><br>
<textarea id="comment" onkeyup="validateComment()" name="commente" placeholder="Message here"></textarea><label id="commentPrompt"></label><br>
<span id="digit1"></span> +
<span id="digit2"></span> =
<input id="captcha" size="2" onkeyup="validateCaptcha()"><label id="captchaPrompt"></label><br>
</form>
<button href="index.php" name="submit" onclick="validateCommentForm()" > Send</button><label id="commentFormPrompt"> </label>
<script type="text/javascript" src="javascript.js"></script>
</body>
</html>
js code
function randNums(){
var rand = Math.floor(Math.random() * 10) + 1;
var rand2 = Math.floor(Math.random() * 10) + 1;
document.getElementById("digit1").innerHTML = rand;
document.getElementById("digit2").innerHTML = rand2;
}
function validateName(){
var name = document.getElementById("commentName").value;
if (name.length == 0){
producePrompt("Name *", "commentNamePrompt", "red");
return false;
}
if(!name.match(/^[A-Za-z]*\s{1}[A-Za-z]*$/))
{
producePrompt("name wrong","commentNamePrompt","red");
return false;
}
producePrompt("accept", "commentNamePrompt", "green");
return true;
}
function validatePhone(){
var phone = document.getElementById("commentPhone").value;
if(phone.length == 0){
producePrompt("phone *", "commentPhonePrompt", "red");
return false;
}
if(phone.length != 10){
producePrompt("10 numbers", "commentPhonePrompt", "red");
return false;
}
if(!phone.match(/^[0-9]{10}$/))
{
producePrompt("phone wrong","commentPhonePrompt","red");
return false;
}
producePrompt("Accept", "commentPhonePrompt", "green");
return true;
}
function validateMail() {
var mail = document.getElementById("commentMail").value;
if(mail.length == 0){
producePrompt("mail *", "commentMailPrompt", "red");
return false;
}
if(!mail.match(/^[A-Za-z._\-0-9]*[#][A-Za-z]*[\.][a-z]{2,4}$/))
{
producePrompt("Wrong mail","commentMailPrompt","red");
return false;
}
producePrompt("accept", "commentMailPrompt", "green");
return true;
}
function validateComment(){
var comment = document.getElementById("comment").value;
var required = 30;
var left = required-comment.length;
if (left > 0){
producePrompt(left + " lettre" ,"commentPrompt","red" );
return false;
}
producePrompt("accept", "commentPrompt", "green");
return true;
}
function validateCaptcha(){
var captcha = document.getElementById("captcha").value;
var digit1 = parseInt(document.getElementById("digit1").innerHTML);
var digit2 = parseInt(document.getElementById("digit2").innerHTML);
var sum = digit1 + digit2;
if(captcha.length == 0){
producePrompt("captcha *", "captchaPrompt", "red");
return false;
}
if(!captcha.match(/^[0-9]{1,2}$/) || !captcha.match(sum)){
producePrompt("Captchas wrong","captchaPrompt","red");
return false;
}
producePrompt("Accept", "captchaPrompt", "green");
return true;
}
function submitForm(){
var server = 'http://localhost/test'; // Your PHP file
var commentName = $('#commentName').val(); // The values of your form
var commentMail = $('#commentMail').val(); // The values of your form
var commentPhone = $('#commentPhone').val(); // The values of your form
var comment = $('#comment').val(); // The values of your form
$.ajax({ // Here the magic starts
url: server+"/index.php", // Where this function will send the values
type:"get", // To get the status of your php file
data: "action=insertNews&commentName="+commentName+"&commentMail="+commentMail+"&commentPhone="+commentPhone+"&comment="+comment, // The values
success: function (data){ // After sending the values to your php file you will receive number 1 or 2, if you receives number 1 it means sucess, but if you receives number 2 it means fail.
if(data == 'Messange Send'){
//
}
else{
//
}
}
});
}
function validateCommentForm(){
if(!validateName() || !validateMail() || !validatePhone() || !validateComment()){
jsShow("commentFormPrompt");
producePrompt("Invalide form","commentFormPrompt","red");
setTimeout(function(){jsHide("commentFormPrompt")}, 2000);
}
else
submitForm();
}
function jsShow(id){
document.getElementById(id).style.display = "block";
}
function jsHide(id){
document.getElementById(id).style.display = "none";
}
function producePrompt(message, promptLocation, color){
document.getElementById(promptLocation).innerHTML = message;
document.getElementById(promptLocation).style.color = color;
}
that's is my code, the php code with HTML, And javascript with Ajax but when I click into submit button nothing happens, Any solution ?
function validateCommentForm(){
if(!validateName() || !validateMail() || !validatePhone() || !validateComment()){
jsShow("commentFormPrompt");
producePrompt("Invalide Form ","commentFormPrompt","red");
setTimeout(function(){jsHide("commentFormPrompt")}, 2000);
}
else
submitForm();
}
function submitForm(){
var server = 'url'; // Your PHP file
var commentName = $('#commentName').val(); // The values of your form
var commentMail = $('#commentMail').val(); // The values of your form
var commentPhone = $('#commentPhone').val(); // The values of your form
var comment = $('#comment').val(); // The values of your form
$.ajax({ // Here the magic starts
url: server+"/api.php", // Where this function will send the values
type:"get", // To get the status of your php file
data: "action=insertNews&commentName="+commentName+"&commentMail="+commentMail+"&commentPhone="+commentPhone+"&comment="+comment, // The values
success: function (data){ // After sending the values to your php file you will receive number 1 or 2, if you receives number 1 it means sucess, but if you receives number 2 it means fail.
if(data == 'Messange Send'){
// sucess code
}
else{
// fail code
}
}
});
}
Edit: You need to echo in your php echo a number 1 if sucess or a number 2 if fail.
PHP
$message = $_GET['comment'];
$email = $_GET['commentMail'];
$name = $_GET['commentName'];
$to = "$email";
$subject = 'New Message';
$message = " Le nom : ".$name."<br><br>".$message."<br><br> Email : ".$email;
$header = "$email";
if(mail($to, $subject, $message, $header)){
echo '<b style="color: green">Messange Send</b>';
}
else{
echo '<b style="color: red">Sommthing wrong</b>';
}
So AJAX is about creating more versatile and interactive web applications by enabling web pages to make asynchronous calls to the server transparently while the user is working. AJAX is a tool that web developers can use to create smarter web applications that behave better than traditional web applications when interacting with humans.
The technologies AJAX is made of are already implemented in all modern web browsers, such as Mozilla Firefox, Internet Explorer, or Opera, so the client doesn't need to install any extra modules to run an AJAX website. AJAX is made of the following:
JavaScript is the essential ingredient of AJAX, allowing you to
build the client-side functionality. In your JavaScript functions
you'll make heavy use of the Document Object Model (DOM) to
manipulate parts of the HTML page.
The XMLHttpRequest object enables JavaScript to access the server
asynchronously, so that the user can continue working, while
functionality is performed in the background. Accessing the server
simply means making a simple HTTP request for a file or script
located on the server. HTTP requests are easy to make and don't cause
any firewall-related problems.
A server-side technology is required to handle the requests that come
from the JavaScript client. In this book we'll use PHP to perform the
server-side part of the job.
For the client-server communication the parts need a way to pass data and understand that data. Passing the data is the simple part. The client script accessing the server (using the XMLHttpRequest object) can send name-value pairs using GET or POST. It's very simple to read these values with any server script.
The server script simply sends back the response via HTTP, but unlike a usual website, the response will be in a format that can be simply parsed by the JavaScript code on the client.
The suggested format is XML, which has the advantage of being widely supported, and there are many libraries that make it easy to manipulate XML documents. But you can choose another format if you want (you can even send plain text), a popular alternative to XML being JavaScript Object Notation (JSON).
Simple example with old school style:
The HTML
<html>
<head>
<title>AJAX with PHP: Quickstart</title>
</head>
<body onload='process()'>
Server wants to know your name:
<input type="text" id="myName" />
<div id="divMessage"></div>
</body>
</html>
The Magician
// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();
// retrieves the XMLHttpRequest object
function createXmlHttpRequestObject() {
// will store the reference to the XMLHttpRequest object
var xmlHttp;
// if running Internet Explorer
if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlHttp = false;
}
}
// if running Mozilla or other browsers
else {
try {
xmlHttp = new XMLHttpRequest();
}
catch (e) {
xmlHttp = false;
}
}
// return the created object or display an error message
if (!xmlHttp)
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}
// make asynchronous HTTP request using the XMLHttpRequest object
function process() {
// proceed only if the xmlHttp object isn't busy
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
// retrieve the name typed by the user on the form
name = encodeURIComponent(document.getElementById("myName").value);
// execute the quickstart.php page from the server
xmlHttp.open("GET", "**yourPHPfiletoretrievedata**.php?name=" + name, true);
// define the method to handle server responses
xmlHttp.onreadystatechange = handleServerResponse;
// make the server request
xmlHttp.send(null);
}
else
// if the connection is busy, try again after one second
setTimeout('process()', 1000);
}
// executed automatically when a message is received from the server
function handleServerResponse() {
// move forward only if the transaction has completed
if (xmlHttp.readyState == 4) {
// status of 200 indicates the transaction completed successfully
if (xmlHttp.status == 200) {
// extract the XML retrieved from the server
xmlResponse = xmlHttp.responseXML;
// obtain the document element (the root element) of the XML structure
xmlDocumentElement = xmlResponse.documentElement;
// get the text message, which is in the first child of
// the the document element
helloMessage = xmlDocumentElement.firstChild.data;
// update the client display using the data received from the server
document.getElementById("divMessage").innerHTML =
'<i>' + helloMessage + '</i>';
// restart sequence
setTimeout('process()', 1000);
}
// a HTTP status different than 200 signals an error
else {
alert("There was a problem accessing the server: " + xmlHttp.statusText);
}
}
}
I have to send a name and a link from client side to the server. I thought of using AJAX called by Javascript to do this.
This is what I mean. I wished to make an ajax request to a file called abc.php with parameters :-
1. http://thumbs2.ebaystatic.com/m/m7dFgOtLUUUSpktHRspjhXw/140.jpg
2. Apple iPod touch, 3rd generation, 32GB
To begin with, I encoded the URL and tried to send it. But the server says status Forbidden
Any solution to this ?
UPDATE ::
It end up calling to
http://abc.com/addToWishlist.php?rand=506075547542422&image=http://thumbs1.ebaystatic.com/m/mO64jQrMqam2jde9aKiXC9A/140.jpg&prod=Flat%20USB%20Data%20Sync%20Charging%20Charger%20Cable%20Apple%20iPhone%204G%204S%20iPod%20Touch%20Nano
Javascript Code ::
function addToWishlist(num) {
var myurl = "addToWishlist.php";
var myurl1 = myurl;
myRand = parseInt(Math.random()*999999999999999);
var rand = "?rand="+myRand ;
var modurl = myurl1+ rand + "&image=" + encodeURI(storeArray[num][1]) + "&prod=" + encodeURI(storeArray[num][0]);
httpq2.open("GET", modurl, true);
httpq2.onreadystatechange = useHttpResponseq2;
httpq2.send(null);
}
function useHttpResponseq2() {
if (httpq2.readyState == 4) {
if(httpq2.status == 200) {
var mytext = httpq2.responseText;
document.getElementById('wish' + num).innerHTML = "Added to your wishlist.";
}
}
}
Server Code
<?php
include('/home/ankit/public_html/connect_db.php');
$image = $_GET['image'];
$prod = $_GET['prod'];
$id = $_GET['id'];
echo $prod;
echo $image;
?>
As I mentioned, its pretty basics
More Updates :
On trying to send a POST request via AJAX to the server, it says :-
Refused to set unsafe header "Content-length"
Refused to set unsafe header "Connection"
2 things.
Use encodeURIComponent() instead of encodeURI().
Here is a detailed discussion on this: When are you supposed to use escape instead of encodeURI / encodeURIComponent?
If you are new to JavaScript, use some lib to help you do the AJAX work. Like mootools, jQuery, etc.
Using a POST request solved my issue :)
function addToWishlist(num) {
var url = "trial.php";
var parameters = "prod=" + encodeURIComponent(storeArray[num][0]) + "&image=" + encodeURIComponent(storeArray[num][1]);
httpq2.open("POST", url, true);
httpq2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpq2.onreadystatechange = function(){
if (httpq2.readyState == 4) {
if(httpq2.status == 200) {
var mytext = httpq2.responseText;
document.getElementById('wish' + num).innerHTML = "Added to your wishlist.";
}
}
};
httpq2.send(parameters);
}
From System.Shell.itemFromFileDrop I get System.Shell.Item object item. I've tried this:
var oStream = new ActiveXObject("ADODB.Stream");
oStream.Type = 1;
oStream.Open();
oStream.LoadFromFile(item.path);
content = oStream.Read();
var thisObj = this;
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://myUrl.com//");
xhr.send(content); //NOT WORKING
oStream.Close();
oStream = null;
but I really don't know what to pass in the xhr.send function.
The serverside PHP code is as simple as it could be:
if (file_exists($_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],$_FILES["file"]["name"]);
header("{$_SERVER['SERVER_PROTOCOL']} 200 OK");
header('Content-Type: text/plain');
echo "http://myUrl.com/" .$_FILES["file"]["name"];
}
any ideas what am I doing wrong ? Or any ideas about how to upload files from windows gadget at all?
I have a script (javascript) that works in firefox but not in chrome or IE. I opened chromes debug console to find the problem. No errors are reported and the code works perfectly. Running it again with the console closed does not work again.
I verified that the version of the script is correct (not old and cached). The console does not report any warnings or errors.
I tried putting in simple logging that writes to a div at the bottom of the page - no information.
(in the debug console it works - including logging info in the div).
The function is the callback after an XMLHttpRequest is made to the server.
I verified that the php script is called by including error_log calls. The error_log shows the return value correctly. A page refresh also show the row has been deleted.
It appears as if the function removeRow() is never called unless the console is open. (method or reserved words conflict??) Tried changing the function name to delRow (including callback) - still not working.
All other Ajax calls seem to work fine.
A Code snippet follows:
var pos = 0;
var xhr;
function eraseRow() {
var myImage = this;
var fullid = myImage.id;
// split row no and record id eg 5_1223 => row=5 and recordid=1223
var idComponents = fullid.split("_");
if (idComponents.length > 1) { // check if image has complete row info
rowid = idComponents[1]; // extract row number from id
pos = parseInt(idComponents[0]);
xhr = new XMLHttpRequest(); // only support IE8 or +
xhr.onreadystatechange = removeRow;
xhr.open("GET","valid_del.php$delrow="+rowid;
xhr.send(null);
}
}
function removeRow() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var err = document.getElementById("errormsg");
var str = xhr.responseText;
err.innerHTML = "Server returned "+str;
if (str === "go-ahead") {
var table = document.getElementById("tableid");
table.deleteRow(pos);
}
}
}
}
PHP (valid_del.php):
<?php
include(funclib.php);
if (isset($_GET['delrow']) && strlen($_GET['delrow'] > 0) {
$recid = $_GET['delrow'];
$db = createDbConn(); // function that connects to mysql server db
$result = $db->query("delete from doclibrary where doc_id='$recid'");
if ($result===true) {
echo 'go-ahead';
error_log('Script successful - returns go-ahead',0);
} else {
echo 'stop';
error_log('Script not successful - returns stop',0);
}
$db->close();
} else {
echo 'stop';
error_log('Script not given record id - returns stop',0);
}
?>
I think the DOM is not ready, try to add your code calls into window.onload, or in $(document).ready if you are using JQuery.