Ajax not working with javascript. What am I supposed to do? - javascript

This is my code where I call the Request for Ajax, than a simple input button which on onClick event send some data to a function called setValue();
This is the code (JS):
//request for ajax XML
<script type='text/javascript'>
function callAjax(){
var XMLObj = false;
if(window.XMLHttpRequest)
XMLObj = new XMLHttpRequest();
else if(window.ActiveXObject)
XMLObj = new ActiveXObject('Microsoft.XMLHTTP');
if(!XMLObj)
return false;
return XMLObj;
}
//var for ajaxobject handle;
var objAjax = callAjax();
function setValue(value, id, num, item){
if(objAjax){
if(objAjax.readyState == 4 || objAjax.readyState == 0){
objAjax.open('POST', 'addview.php', true);
objAjax.send('value=' + val + '&id='+id+'&num='+num+'&item='+item);
}
}
}
//input for sending value to function setValue();
<input type='button' onClick='setValue(1, 2, 3, 4)' />
//and this is where I handle the sent data via php
<?php
if(!$_POST['value'] || !$_POST['id'] || !$_POST['num'] || !$_POST['item'])
exit();
include('config.php');
$value = mysql_real_escape_string($_POST['value']);
$id = mysql_real_escape_string($_POST['id']);
$num = mysql_real_escape_string($_POST['num']);
$item = mysql_real_escape_string($_POST['item']);
mysql_query("UPDATE `window` SET window_val = window_val + ".$value." WHERE window_id = '".$id."' AND window_num = '".$num."' AND window_item = '".$item."' ") or die(mysql_error() );
mysql_close($con);
?>
The php script is working, I tried it with sending data manually ($_GET['']) and it's working. Also I checked the URL with alert('value='+value+'&id='+id...) and all variables are Ok, but the database won't be queried.
If you see, I don't add any function for response, reply from the server. I just only want to send those data and query the data base.
Thank you !

You may be missing
objAjax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
Consider improving your function names: callAjax doesn't call Ajax, it returns a reference to the XHR object. Call it getXhr or something more like what it's actually doing.
If you're ok with jQuery, just call
function setValue(value, id, num, item){
$.post('addview.php', 'value=' + val + '&id='+id+'&num='+num+'&item='+item);
// or the cleaner version
$.post('addview.php', {value: val, id: id, num: num, item:item});
}

Related

xmlhttp.open not sending $_GET values to the php file

On click button, it suppose to execute a query in the php file either update or delete depending on the button clicked. But I think there's no value passed to the variable $status inside php file when buttons are clicked, thus not executing sql queries.
PHP
<?php
$status = $_GET["status"];
if ($status == "update") {
$conn = mysqli_connect('localhost', 'root','root', 'realestate');
$id=$_GET["id"];
$first=$_GET["firstname"];
$mid=$_GET["middlename"];
$last=$_GET["lastname"];
$add=$_GET["address"];
$gend=$_GET["gender"];
$cont=$_GET["contact"];
$first=trim($first);
$mid=trim($mid);
$last=trim($last);
$add=trim($add);
$gend=trim($gend);
$cont=trim($cont);
$result=mysqli_query($conn, "UPDATE agents SET firstname='$first', middlename='$mid', lastname='$last', address='$add', gender='$gend', contact='$cont' WHERE id=$id");
}
if ($status == "delete") {
$conn = mysqli_connect('localhost', 'root','root', 'realestate');
$id=$_GET["id"];
$result=mysqli_query($conn, "DELETE FROM agents WHERE id=$id");
}
?>
JavaScript
<script type="text/javascript">
data();
function data() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","update.php?status=disp", false);
xmlhttp.send(null);
document.getElementById("data").innerHTML = xmlhttp.responseText;
}
function bb(b) {
var firstid="txtfirst"+b;
var firstname = document.getElementById(firstid).value;
var midid="txtmid"+b;
var middlename = document.getElementById(midid).value;
var lastid="txtlast"+b;
var lastname = document.getElementById(lastid).value;
var addid="txtadd"+b;
var address = document.getElementById(addid).value;
var gendid="txtgend"+b;
var gender = document.getElementById(gendid).value;
var contid="txtcont"+b;
var contact = document.getElementById(contid).value;
update_value(b,firstname,middlename,lastname,address,gender,contact);
document.getElementById(b).style.visibility="visible";
document.getElementById("update"+b).style.visibility="hidden";
document.getElementById("firstname"+b).innerHTML=firstname;
document.getElementById("middlename"+b).innerHTML=middlename;
document.getElementById("lastname"+b).innerHTML=lastname;
document.getElementById("address"+b).innerHTML=address;
document.getElementById("gender"+b).innerHTML=gender;
document.getElementById("contact"+b).innerHTML=contact;
}
function update_value(id,firstname,middlename,lastname,address,gender,contact) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","update.php?id="+id+"&firstname="+firstname+"&middlename="+middlename+"&lastname="+lastname+"&address="+address+"&gender="+gender+"&contact="+contact+"&status=update",false);
xmlhttp.send(null);
}
function delete1(id) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","update.php?id="+id+"&status=delete", false);
xmlhttp.send(null);
data();
}
</script>
You have a few issues here. First, I would advise you look into the DRY principle to help you avoid easy to miss problems like not including a status variable in your request.
If you look at your JavaScript you will notice that you are making several requests to the same page, and using copy-paste code to do so. This is a great place to further abstract your code. I would probably use something similar to the following.
Secondly, your PHP script is vulnerable to SQL Injection. How to combat this is well explained here. I can't say for sure that this is your problem, but if you are using a name like O'Reilly it would prevent your script from working. I don't see any other obvious place where your script would go wrong. If anything shows up in your PHP error log, I might be able to help more.
<script>
//Type isn't needed, browsers assume javascript
function httpRequest(method, url, parameters) {
// Build a query string, this could be improved but it works for your current use case.
// It assumes that parameters is an object and does not work for arrays
var query = "";
Object.keys(parameters).forEach(function(key) {
query += encodeURIComponent(key) + '=' + encodeURIComponent(parameters[key]) + "&";
});
var xmlhttp = new XMLHttpRequest();
//If possible you should switch to async requests as well.
xmlhttp.open(method, url + "?" + query, false);
xmlhttp.send(); //No need to pass null
return xmlhttp.responseText;
}
function updateRequest(parameters) {
return httpRequest("GET", "update.php", parameters);
}
function data() {
document.getElementById("data").innerHTML = updateRequest({status: "disp"});
}
//bb function removed as it isn't relevant to my point here
function update_value(id,firstname,middlename,lastname,address,gender,contact) {
updateRequest({
status: "update",
id: id, //If you are using a recent browser this can be changed to just id, firstname, ...
firstname: firstname,
middlename: middlename,
lastname: lastname,
address: address,
gender: gender,
contact: contact,
});
}
function delete1(id) {
updateRequest({
status: "delete",
id: id,
});
data();
}
</script>

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

Return value from php to javascript

I writing a registration/login form, I am sending user info via POST to a PHP that is looking in a DB. I would like that the PHP returns an ok or wrong value to the js and I don't now how to do it.
Here my js:
ui.onClick_regsubmit=function()
{
var fname=document.getElementById('fname').value;
var lname=document.getElementById('lname').value;
var password=document.getElementById('password').value;
var mail=document.getElementById('mail').value;
var affiliation=document.getElementById('affiliation').value;
var data = new FormData();
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
data.append("fname",fname);
data.append("lname",lname);
data.append("password",password);
data.append("mail",mail);
data.append("affiliation",affiliation);
xhr.open( 'post', 'PHP/registration.php', false );
xhr.send(data);
window.alert(affiliation);
}
And the php:
<?php
mysql_connect('localhost','root','') or die('Cannot connect mysql server');
mysql_select_db('ChemAlive_login') or die('cannot connect database');
$lname=$_POST['lname'];
$fname=$_POST['fname'];
$password=$_POST['password'];
$mail=$_POST['mail'];
$affiliation=$_POST['affiliation'];
$q=mysql_query("select * from login where mail='".$mail."' ") or die(mysql_error());
$n=mysql_fetch_row($q);
if($n>0)
{
$q=mysql_query("select password from login where mail='".$mail."' ");
$pp=mysql_fetch_row($q);
if($pp[0]=$password) echo "ok";
else echo "wrong";
}
else
{ $insert=mysql_query("insert into login values('".$fname."','".$lname."','".$mail."','".$password."','".$affiliation."')") or die(mysql_error());}
?>
I would like to return to js this ok or wrong value. How to do it?
xhr.onload=function()
{
if (xhr.status==200)
{
alert(xhr.response);
}else
{
alert("unknown server error");
}
}
it will be better if the server sends a response code, and javascript will transfer this code to the text. For example:
onload=function()
{
switch(xhr.response)
{
case "0":{alert("unknown error")};break;
case "1":{alert("email is already used")};break;
...
}
}
I think thought it is clear
I do not have the rep to comment or I'd ask for details, but if you can consider using ajax, it could look something like this:
php:
$doit = //your query;
if($doit){
$youdid = 'ok';
}
else{
exit('1');
}
js:
$(document).ready(function () {
var foo = $("#formfield")val();
$.ajax({
"foo":foo;
type: 'POST',
url: 'some.php',
success: function(responseText) {
if(responseText == "1") {
alert("Leave instantly");
};
}
else {
alert("One of us");
}
If you want to return either ok or wrong to the JavaScript to handle you could do something like this in your registration.php page:
$q=mysql_query("select password from login where mail='".$mail."' ");
$pp=mysql_fetch_row($q);
if($pp[0]=$password){
header('Content-Type: application/json');
echo json_encode(array('password' => 'ok'));
}else{
header('Content-Type: application/json');
echo json_encode(array('password' => 'wrong'));
}
I have not fully testing this, but the idea is to set the header to return json and then send it a JSON string.
Does that make sense?
Like I said in my comment below I have only used jQuery for AJAX. But here is a little something of what I know about XMLHttpRequest and my undertsanding of how you would test what you get back.
You can set up a listener for when you get a response back onreadystatechange and then put the response in a variable var pass = xhr.response and then just output the text to an alert box like alert(pass.password).
if (xhr.onreadystatechange === 4 && xhr.status === 200){
var pass = xhr.response;
//should output either ok or wrong
alert(pass.password);
}
Read more about XMLHttpRequest here
Let me know if that works.

JQuery $.post not sending data to $_POST global

The send() function is my JavaScript function which uses AJAX $.post. Though the function(data) is successful, everything I intend it to do is working fine. But the data being sent, in my example, recipient && chat_sent && date is not being sent to the global variable $_POST. The second part of the code is my PHP code. Though since the data is not being sent, the if statement IN MY PHP CODE cannot be executed. What could be the problem?
function send(){
var datetemp= new Date();
var tempUser = "<? echo $user ?>";
var tempRecipient = document.getElementById("recipient_chat").value;
var chat_message= document.getElementById("chat_area").value;
$.post("searchPresentation.php", {chat_sent: chat_message, date: datetemp,
recipient:tempRecipient}, function( data ) {
$("#window").text(datetemp + $("#window").text() + tempUser + " - " + chat_message);
});
}
This is searchPresentation.php:
if (isset($_POST['chat_sent']) && isset($_POST['date']) && isset($_POST['recipient']))
{
//DO SOMETHING
}
if (!empty($_POST['chat_sent']) && !empty($_POST['date']) && !empty($_POST['recipient']))
{//DO SOMETHING}
all of param already set! "document.getElementById("chat_area").value" maybe is ' ' but it is set so use empty()

Categories