AJAX is not correctly sending POST variables - javascript

I'm writing a basic application in AJAX that need to send some data over POST to a php page.
The problem I'm getting here is that the php page is not correctly receiving data in the $_POST: if I try to print its content I get an empty array.
Can you help me point out the problem?
// global variables
var sendReq = getXmlHttpRequestObject();
// get the browser dependent XMLHttpRequest object
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
else {
document.getElementById('status').innerHTML =
'Status: Error while creating XmlHttpRequest Object.';
}
}
// send a new message to the server
function sendMessage() {
if ( receiveReq.readyState == 0 || receiveReq.readyState == 4 ) {
sendReq.open("POST", 'chatServer.php', true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
// bind function call when state change
sendReq.onreadystatechange = messageSent;
var param = "message=ciao";
sendReq.send(param);
// reset the content of input
document.getElementById("message").value = "";
}
}
chatServer.php
<?php session_start();
// send headers to prevent caching
header("Expires: Mon, 1 Jul 2000 08:00:00 GMT" );
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" );
header("Cache-Control: no-cache, must-revalidate" );
header("Pragma: no-cache" );
// open database
$file_db = new PDO('sqlite:chatdb.sqlite') or die("cannot open database");
if ($file_db) {
print_r($_POST); // this prints an empty array!!!
// check if a message was sent to the server
if (isset($_POST["message"]) && $_POST["message"] != '') {
$message = $_POST["message"];
// do stuff
}
}
?>
EDIT:
Updated function, still not working
function sendMessage() {
if( sendReq ){
/* set the listener now for the response */
sendReq.onreadystatechange=function(){
/* Check for the request Object's status */
if( sendReq.readyState==4 ) {
if( sendReq.status==200 ){
/* Process response here */
clearInterval(timer);
getUnreadMessages();
}
}
};
/* Open & send request, outwith the listener */
sendReq.open( "POST", 'chatServer.php', true );
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
var param = 'message=ciao';
sendReq.send( param );
document.getElementById("message").value = "";
// relocate to php page for debugging purposes
window.location.replace("chatServer.php");
}
}

Your sendMessage function is not quite right - have a look at this to see if it helps.
In the original the function checked for the status of receiveReq which does not refer to the instantiated XMLHttpRequest Object sendReq - also, the request would never get sent even if it had used sendReq because the open and send call was within the code block that checked the response...
var sendReq = getXmlHttpRequestObject();
function messageSent( response ){
console.info(response);
}
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
document.getElementById('status').innerHTML = 'Status: Error while creating XmlHttpRequest Object.';
}
}
/*
Set the `param` as a parameter to the function, can reuse it more easily.
*/
function sendMessage( param ) {
if( sendReq ){
/* set the listener now for the response */
sendReq.onreadystatechange=function(){
/* Check for the request Object's status */
if( sendReq.readyState==4 ) {
if( sendReq.status==200 ){
/* Process response here */
messageSent.call( this, sendReq.response );
} else {
/* there was an error */
}
}
};
/* Open & send request, outwith the listener */
sendReq.open( "POST", 'chatServer.php', true );
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.send( param );
document.getElementById("message").value = "";
}
}
/* send some messages */
sendMessage('message=ciao');
sendMessage('message=ajax...sent via POST');
Originally missed the param var declaration so corrected that.
update
chatserver.php (example)
------------------------
<?php
/*
demo_chatserver.php
*/
session_start();
if( $_SERVER['REQUEST_METHOD']=='POST' ){
/*
include your db connection
set your headers
*/
if( isset( $_POST['message'] ) && !empty( $_POST['message'] ) ){
#ob_clean();
/* Create the db conn && test that it is OK */
/* for the purposes of the tests only */
$_POST['date']=date( DATE_COOKIE );
echo json_encode( $_POST, JSON_FORCE_OBJECT );
exit();
}
}
?>
html / php page
---------------
<!doctype html>
<html>
<head>
<title>ajax tests</title>
<script type='text/javascript'>
var sendReq = getXmlHttpRequestObject();
function messageSent( response ){
console.info( 'This is the response from your PHP script: %s',response );
if( document.getElementById("message") ) document.getElementById("message").innerHTML=response;
}
function getXmlHttpRequestObject() {
if ( window.XMLHttpRequest ) {
return new XMLHttpRequest();
} else if( window.ActiveXObject ) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
document.getElementById('status').innerHTML = 'Status: Error while creating XmlHttpRequest Object.';
}
}
/*
Set the `param` as a parameter to the function, can reuse it more easily.
*/
function sendMessage( param ) {
if( sendReq ){
/* set the listener now for the response */
sendReq.onreadystatechange=function(){
/* Check for the request Object's status */
if( sendReq.readyState==4 ) {
if( sendReq.status==200 ){
/* Process response here */
messageSent.call( this, sendReq.response );
} else {
/* there was an error */
}
}
};
/* Open & send request, outwith the listener */
/*NOTE: I have this in a folder called `test`, hence the path below!! */
sendReq.open( "POST", '/test/demo_chatserver.php', true );
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.send( param );
if( document.getElementById("message") ) document.getElementById("message").innerHTML = "";
}
}
/* send some data - including original 'message=ciao' but other junk too */
window.onload=function(event){
sendMessage('message=ciao&id=23&banana=yellow&php=fun&method=post&evt='+event);
}
</script>
</head>
<body>
<output id='message' style='display:block;width:80%;float:none;margin:5rem auto;padding:1rem;box-sizing:content-box;border:1px solid black;'>
<!--
Expect to see content appear here....
-->
</output>
</body>
</html>
Should output something like:-
------------------------------
{"message":"ciao","id":"23","banana":"yellow","php":"fun","method":"post","evt":"[object Event]","time":1446730182,"date":"Thursday, 05-Nov-15 13:29:42 GMT"}

Here I will show how I send/receive Ajax requests for basic CRUD (Create, Read, Delete, Update) applications and you can implement it in your code.
First of all simple form with input elements in HTML
<form action="controller.php" method="POST">
<input type="text" class="form-control" name="userName"/>
<input type="text" class="form-control" name="password"/>
<input type="Submit" value="Log In" onclick="logIn(); return false;"/>
</form>
After that we write JavaScript function that uses formData object and with AJax technique sends request:
function logIn()
{
//Creating formData object
var formData = new FormData();
//Getting input elements by their classNames
var formElements = document.getElementsByClassName("form-control");
//Append form elements to formData object
for(var i = 0; i < formElements.length; i++)
formData.append(formElements[i].name, formElements[i].value)
//Creating XMLHttpRequest Object
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
alert(xmlHttp.responseText);
}
}
xmlHttp.open("POST", "controller.php");
xmlHttp.send(formData);
}

Related

Validation Form and send data to the php file

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);
}
}
}

How to retrieve a php form with AJAX at specific time spans

I want to display a form with a script I adapted from this question. The script is in a file I wrote called queries.js, and its purpose is to print the content of a php form called "dbMinAlert.php" in a div like this <div id="recentExits" name="recentExits"></div> located in my project's index, I tried invoking getNewData(); in my index.php file using this tag <body onLoad="getNewData()"> but it doesn't seem to do anything at all.
var data_array = ''; // this is a global variable
function getNewData() {
$.ajax({
url: "dbMinAlert.php",
})
.done(function(res) {
data_array = res; // the global variable is updated here and accessible elsewhere
getNewDataSuccess();
})
.fail(function() {
// handle errors here
})
.always(function() {
// we've completed the call and updated the global variable, so set a timeout to make the call again
setTimeout(getNewData, 2000);
});
}
function getNewDataSuccess() {
//console.log(data_array);
document.getElementById("recentExits").innerHTML=data_array;
}
getNewData();`
---This php code works and it actually does what I expect it to do. The real problem is the javascript, for all I care the next php form could print a "Hello world" message, but I want it displayed inside the div I placed in my index, without having to post a thing to dbMinAlert.php.
define("HOST", "localhost");
define("DBUSER", "root");
define("PASS", "password");
define("DB", "mydb");
// Database Error - User Message
define("DB_MSG_ERROR", 'Could not connect!<br />Please contact the site\'s administrator.');
$conn = mysql_connect(HOST, DBUSER, PASS) or die(DB_MSG_ERROR);
$db = mysql_select_db(DB) or die(DB_MSG_ERROR);
$query = mysql_query("
SELECT *
FROM outputs, products
WHERE products.idProduct=outputs.idProduct
ORDER BY Date DESC, Time DESC limit 5
");
echo '<ul class="news">';
while ($data = mysql_fetch_array($query)) {
$date = date_create($data['Date']);
$time = date_create($data['Time']);
echo '<li><figure><strong>'.date_format($date,'d').'</strong>'.date_format($date,'M').date_format($date,'Y').'</figure>'.$data["idProduct"]." ".$data['prodName'].'</li>';
}
echo '</ul>';
You have to execute the function for the first time.
getNewData();
It could be the way you are returning the result from php. Instead of doing multiple echo, could you first assign your result in single php variable and finally do single echo.
$result = '<ul class="news">';
while ($data = mysql_fetch_array($query)) {
$date = date_create($data['Date']);
$time = date_create($data['Time']);
$result = $result + '<li><figure><strong>'.date_format($date,'d').'</strong>'.date_format($date,'M').date_format($date,'Y').'</figure>'.$data["idProduct"]." ".$data['prodName'].'</li>';}
$result = $result + '</ul>';
echo $result;
I found a solution in this question and my code ended up Like this.
I just had to invoke the function in my index by typing <body onload="return getOutput();">
JavaScript
//Min-Max Alerts
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'dbMinAlert.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('recentExits');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('recentExits');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}

AJAX without jQuery is not sending POST data to PHP file

I've been trying to get an ajax alert layer to work with a POST method for several days and I can't come up with a reason for it not working. I use the same basic code to send form data through ajax with POST on other admin pages without trouble but when I try to send data that does not come from a form nothing gets to the server in $_POST.
Here's the flow of the code...
I use variables on a page like these:
$alertLayer = 1;
$autoCloseAlertLayer = 1;
$addAlertLayerCloseButton = 1;
$alertLayerMessage = $alertLayerMessage . '<h1>Test</h1><p>3rd test of the alert layer module.</p>';
$redirect = 0;
$redirectTo = 0;
and I include a script that calls a function at the bottom of the page like this:
if ($alertLayer == true)
{
echo "<script type='text/javascript' id='alertLayerScript'>Lib.ajaxAlertFunction('/Modules/AlertLayer', $autoCloseAlertLayer, $addAlertLayerCloseButton, '$alertLayerMessage', $redirect, '$redirectTo');</script>";
}
Here's the script that gets called:
Lib.ajaxAlertFunction = function (senturl, autoClose, closeButton, message, redirect, redirectTo)
{
var ajaxRequest;
try
{
ajaxRequest = new XMLHttpRequest();
}
catch (e)
{
try
{
ajaxRequest = new ActiveXObjext("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
ajaxRequest = new ActiveXObjext("Microsoft.XMLHTTP");
}
catch (e)
{
alert ("Your browser can't handle the truth!");
return false;
}
}
}
if (!senturl)
{
return false;
}
else
{
// var data = "autoClose=" + encodeURIComponent(autoClose) + "&closeButton=" + encodeURIComponent(closeButton) + "&message=" + encodeURIComponent(message) + "&redirect=" + encodeURIComponent(redirect) + "&redirectTo=" + encodeURIComponent(redirectTo);
// var data = encodeURIComponent("autoClose=" + autoClose + "&closeButton=" + closeButton + "&message=" + message + "&redirect=" + redirect + "&redirectTo=" + redirectTo);
var data = "autoClose=" + autoClose + "&closeButton=" + closeButton + "&message=" + message + "&redirect=" + redirect + "&redirectTo=" + redirectTo;
}
ajaxRequest.onreadystatechange = function()
{
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200)
{
document.getElementById('outerFrame').innerHTML += ajaxRequest.responseText;
newAlertLayer = document.getElementById('alertLayer');
var arr = newAlertLayer.getElementsByTagName('script')
for (var n = 0; n < arr.length; n++)
{
eval(arr[n].innerHTML)
}
}
}
ajaxRequest.open('POST', senturl, true);
ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajaxRequest.send(data);
}
NOTE: I have no problem sending this data with a 'GET' method but then a long message gets cut off. I have also tried to set up the 'data' variable in several different methods that I've searched over the past 3 days with no success.
The code that expects $_POST data goes as follows:
<?php
$ROOT = $_SERVER['DOCUMENT_ROOT'];
?>
<div id="alertLayer">
<link rel="stylesheet" href="<?php $ROOT ?>/Modules/AlertLayer/alertLayer.css">
<script src="/Modules/AlertLayer/alertLayer.js"></script>
<div id="alertBlock">
<?php
foreach ($_POST as $key => $value)
{
echo "<p>" . $key . " = " . $value . "</p>";
}
foreach ($_GET as $key => $value)
{
echo "<p>" . $key . " = " . $value . "</p>";
}
?>
</div>
</div>
What am I missing? What is different from sending form data with POST and sending variables concatenated the same way?
Again, GET is working when I add the data to the url string but not sufficient, POST = no data at all received on the other end of the ajaxRequest but the rest of the request returns exactly what is expected. The $_POST data missing from the server request is currently the only problem that I cannot solve with this code.
It's looking like the request is not being sent properly but I'm unable to determine the reason. Here's a screenshot of what NETWORK tab in chrome:
Problem was a redirection (301) issued by nginx due to a missing slash at the end of the URL. This caused the POST request to be changed to GET.
Technical Details: https://softwareengineering.stackexchange.com/questions/99894/why-doesnt-http-have-post-redirect
Old approach that started the discussion:
Your Problem seems to be the encodeURIComponent() function that you're wrapping around the whole data string. This replaces the & signs with & values. If you debug this in the browsers developer console you'll see that it is not recognized as form data in the request. You should only escape the variables you're filling in.
Btw: This should also be problematic when you use GET.
This is more or less what I tried and it was sending data via POST.
window.onload=function(){
Lib.ajaxAlertFunction( '/test/target.php', 0, 0, 'Fantastic - data is being sent via POST! Amazeballs!', 0, 0 );
};
var Lib={}; /* Because I don't have the rest of `Lib` at my disposal */
Lib.ajaxAlertFunction = function ( senturl, autoClose, closeButton, message, redirect, redirectTo ) {
var ajax;/* renamed only for brevity */
try {
ajax = new XMLHttpRequest();
} catch (e) {
try {
ajax = new ActiveXObjext("Msxml2.XMLHTTP");
} catch (e) {
try {
ajax = new ActiveXObjext("Microsoft.XMLHTTP");
} catch (e) {
alert ("Your browser can't handle the truth!");
return false;
}
}
}
if ( !senturl ) return false;
else {
var data = "autoClose=" + autoClose + "&closeButton=" + closeButton + "&message=" + message + "&redirect=" + redirect + "&redirectTo=" + redirectTo;
}
ajax.onreadystatechange = function() {
if( ajax.readyState == 4 && ajax.status == 200 ) {
/*
document.getElementById('outerFrame').innerHTML += ajax.responseText;
newAlertLayer = document.getElementById('alertLayer');
var arr = newAlertLayer.getElementsByTagName('script')
for ( var n = 0; n < arr.length; n++ ) {
eval( arr[n].innerHTML );
}
*/
console.log( ajax.responseText );
}
}
ajax.open( 'POST', senturl, true );
ajax.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
ajax.send( data );
}
For the sake of the test, /test/target.php was simply:
<?php
exit( print_r($_POST,true) );
?>
and the response:
Array
(
[autoClose] => 0
[closeButton] => 0
[message] => Fantastic - data is being sent via POST! Amazeballs!
[redirect] => 0
[redirectTo] => 0
)
If it helps any, here is a basic ajax function I use in tests, perhaps something in there might be of use?
function _ajax( url, options ){
var factories=[
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject('Msxml2.XMLHTTP'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.3.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.4.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.5.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.6.0'); },
function() { return new ActiveXObject('Microsoft.XMLHTTP'); }
];
/* Try each factory until we have a winner */
for( var i=0; i < factories.length; i++ ) {
try { var req = factories[ i ](); if( req!=null ) { break; } }
catch( err ) { continue; }
};
var method=options.hasOwnProperty('method') ? options.method.toUpperCase() : 'POST';
var callback=options.hasOwnProperty('callback') ? options.callback :false;
if( !callback ){
alert( 'No callback function assigned - a callback is required to handle the response data' );
return false;
}
var headers={
'Accept': "text/html, application/xml, application/json, text/javascript, "+"*"+"/"+"*"+"; charset=utf-8",
'Content-type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
};
/* The main parameters of the request */
var params=[];
if( options.hasOwnProperty('params') && typeof( options.params )=='object' ){
for( var n in options.params ) params.push( n + '=' + options.params[n] );
}
/* Additional arguments that can be passed to the callback function */
var args=options.hasOwnProperty('args') ? options.args : options;
/* Assign callback to handle response */
req.onreadystatechange=function(){
if( req.readyState==4 ) {
if( req.status==200 ) options.callback.call( this, req.response, args );
else console.warn( 'Error: '+req.status+' status code returned' );
}
}
/* Execute the request according to desired method */
switch( method ){
case 'POST':
req.open( method, url, true );
for( header in headers ) req.setRequestHeader( header, headers[ header ] );
req.send( params.join('&') );
break;
case 'GET':
req.open( method, url+'?'+params.join('&'), true );
for( header in headers ) req.setRequestHeader( header, headers[ header ] );
req.send( null );
break;
}
}
/* to use */
_ajax.call( this, '/test/target.php',{ callback:console.info, method:'post',params:{'field':'value','field2':'value2'} } );
When calling the ajaxRequest the url MUST have a "/" at the end of the url (if you're not specifying an /index.php file for example).
I was using '/Modules/AlertLayer' and changing to '/Modules/AlertLayer/' has fixed the problem!

AJAX not responding correctly

I have made an AJAX code for an on-line food store but when i am running it, it is not showing the correct output i.e. a pop up saying something went wrong always pops up. I want to know what is the problem in my code, is it something to do with the connection handlers or the JS script
Here is my index.php code
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE>AJAX</TITLE>
<SCRIPT type = "text/javascript" src = "JS/store.js"></SCRIPT>
</HEAD>
<BODY onload = "process()">
<H3>Foodstore</H3>
Enter the food you would like to order:
<INPUT type = "text" id = "user_input" placeholder = "Food Item" />
<DIV id = "output_area" />
</BODY>
</HTML>
Here is my JS code that I am using
var XML_HTTP = create_XML_HTTP_request_object();
function create_XML_HTTP_request_object() {
var XML_HTTP;
if(window.ActiveXObject) {
try {
XML_HTTP = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
XML_HTTP = false;
}
} else {
try {
XML_HTTP = new XMLHttpRequest();
} catch(e) {
XML_HTTP = false;
}
}
if (! XML_HTTP) {
alert('Cant create the object!!');
} else {
return XML_HTTP;
}
}
function process() {
if((XML_HTTP.readyState == 0) || (XML_HTTP.readyState == 4)) {
food = encodeURIComponent(document.getElementById("user_input").value);
url = "process.php?food=" + food;
XML_HTTP.open("GET", url, true);
XML_HTTP.onreadystatechange = handle_server_response;
XML_HTTP.send(null);
} else {
setTimeout('process()', 1000) ;
}
}
function handle_server_response() {
if(XML_HTTP.readyState == 4) {
if(XML_HTTP.status == 200) {
XML_response = XML_HTTP.responseXML;
XML_document_element = XML_response.documentElement;
message = XML_document_element.firstChild.data;
document.getElementById("output_area").innerHTML = '<SPAN style = "color:blue">' + message + '</SPAN>';
} else {
alert('Something went wrong!!');
}
}
}
Here is my PHP code that i am using
<?php
header('Content-Type: text/xml');
echo '<?XML version = "1.0" encoding = "UTF-8" standalone = "yes" ?>';
echo '<response>';
$food = $_GET['food'];
$food_array = array('tuna' , 'bacon' , 'loaf' , 'cheese' , 'pizza') ;
if(in_array($food , $food_array)) {
echo 'We do have ' . $food . ' !!';
} elseif($food == '') {
echo 'Enter a food item';
} else {
echo 'Sorry we don\'t sell ' . $food . ' !!';
}
echo '</response>';
?>
Firefox at least does NOT like the Processing Instruction
<?XML ... ?>
issues error not well-formed ... works fine with
<?xml ... ?>
However, while your code wont work, it WONT result in the alert ... the fact that your getting the alert suggests your browser can't find process.php (it should be in the same folder as your HTML file)
and an added note ... Edge doesn't like upper case HTML tags, it doesn't break, but it has a sook about them
As an alternative to the ajax functions you posted, consider the following:
function _ajax( url, options ){
var factories=[
function() { return new XMLHttpRequest(); },
function() { return new ActiveXObject('Msxml2.XMLHTTP'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.3.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.4.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.5.0'); },
function() { return new ActiveXObject('MSXML2.XMLHTTP.6.0'); },
function() { return new ActiveXObject('Microsoft.XMLHTTP'); }
];
/* Try each factory until we havea winner */
for( var i=0; i < factories.length; i++ ) {
try { var req = factories[ i ](); if( req!=null ) { break; } }
catch( err ) { continue; }
};
var method=options.hasOwnProperty('method') ? options.method.toUpperCase() : 'POST';
var callback=options.hasOwnProperty('callback') ? options.callback :false;
if( !callback ){
alert( 'No callback function assigned' );
return false;
}
var headers={
'Accept': "text/html, application/xml, application/json, text/javascript, "+"*"+"/"+"*"+"; charset=utf-8",
'Content-type': 'application/x-www-form-urlencoded',
'X-Requested-With': 'XMLHttpRequest'
};
/* The main parameters of the request */
var params=[];
if( options.hasOwnProperty('params') && typeof( options.params )=='object' ){
for( var n in options.params ) params.push( n + '=' + options.params[n] );
}
/* Additional arguments that can be passed to the callback function */
var args=options.hasOwnProperty('args') ? options.args : {};
/* Assign callback to handle response */
req.onreadystatechange=function(){
if( req.readyState ) {
if( req.status==200 ) options.callback.call( this, req.response, args );
else console.warn( 'Error: '+req.status+' status code returned' );
}
}
/* Execute the request according to desired method */
switch( method ){
case 'POST':
req.open( method, url, true );
for( header in headers ) req.setRequestHeader( header, headers[ header ] );
req.send( params.join('&') );
break;
case 'GET':
req.open( method, url+'?'+params.join('&'), true );
for( header in headers ) req.setRequestHeader( header, headers[ header ] );
req.send( null );
break;
}
}
You could then use it like this:
function process(){
call _ajax( this, 'process.php', { 'method':'get', 'callback':handle_server_response, params:{ 'food':food } } );
}
function handle_server_response(response){
try{/* this is not tested! */
var XML_document_element = response.documentElement ;
var message = XML_document_element.firstChild.data ;
document.getElementById("output_area").innerHTML = '<SPAN style = "color:blue">' + message + '</SPAN>' ;
}catch(err){
console.warn('oops, an error occurred: %s',err);
}
}
For future ajax requests you would only have to supply different arguments to the _ajax function rather than rewrite each time. Also, rather than popup a warning message that the user might not understand the errors get logged to the console.
Personally however I'd recommend using JSON rather than XML if there is no specific need to use XML. It's much easier to read and write programatically, requires fewer bytes to transmit and is less prone to anomolies with odd characters.

How to read db value in js

How do I read db value from my js script?
1)
I have the following line of codes i want to modify to read value from db table
var admin_status=document.form1.admin_status.value;
if(admin_status == 0 && document.form1.ecurr_amount.value>20)
{
document.getElementById('msg').innerHTML='Please Verify Your Account to process.';
return false;
}
and this :
<input type="hidden" name="admin_status" id="admin_status"
value="<?php echo $obj_db->
fetch_field("select status from tbl_verification_docs where
userid = '".$_SESSION['user_user']['id']."'")?>" />
I use these lines to validate a form -- > to fix a minimum value
a) i want the validation to be from a value hosted in a data (because i want to control that value from admin panel not from script)
right now i have
"if(admin_status == 0 && document.form1.ecurr_amount.value>20)"
if i want o change that value i need to change the script --> how i want it now is to read that "20" from the entry in a data base
if($data_logged_user['admin_status']=='0' && $data_nbtrans_user['COUNT(*)'] > 5 )
{
if($data_nbtrans_user['COUNT(*)'] > 5)
{
echo "Sorry you have reach your max number of transaction for the day,
come back tomorrow or <a href='http://e-dollar.ng/new-portal/members/accountverification'>
Click here</a> to Verify your Account Now.";
}
}
else
{
my form goes here..
}
b) here i control the number of transactions (it is set to >5)
i want that "5" to be read from a data value instead
i have my db table "tbl_settings"
That's my tbl_settings how it looks like (from the my db)
Setting Value type
SITE_STATUS | 1 | enum
MAX_AMOUNT | 20 | integer
MAX_TRANSACTION | 5 | integer
This is the bare bones of a AJAX call but I suggest looking into it a bit more thoroughly.
So in the myAjax function you set ajaxURL to the PHP file that is going to make the database call. Values are passed to the PHP file in the URL, notice value1 is passed to the myAjax function? Well you can add all the values you need this way.
The PHP file should output via an echo a text result based on the database call.
This echo is accessible via http.responseText in Javascript.
function myAjax(value1) {
var http = getHTTPObject();
var ajaxUrl ="theUrl.php?";
http.open("GET", ajaxUrl + "value1=" + value1, false);
http.send(null);
alert(http.responseText);
}
function getHTTPObject() {
var xmlhttp;
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end #*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try
{
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}

Categories