Error in PHP file for Ajax response - php

I found this helpful example:
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
that shows how to work with data using Ajax. However, the article does not give details about what the PHP file should contain to make the example actually work.
I have tried this:
<?php
$name = (isset($_POST['userName'])) ? $_POST['userName'] : 'no name';
$computedString = "Hi, " . $name;
echo json_encode($computedString);
?>
And variations thereof, to no avail. The result is a message box that says undefined. What should be in the PHP file for this example to make it work?
Here is the HTML page, complete with the JS:
<label>Your name:
<input type="text" id="ajaxTextbox" />
</label>
<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
Make a request
</span>
<script type="text/javascript">
(function() {
var httpRequest;
document.getElementById("ajaxButton").onclick = function()
{
var userName = document.getElementById("ajaxTextbox").value;
makeRequest('test.php',userName);
};
function makeRequest(url, userName)
{
httpRequest = new XMLHttpRequest();
if (!httpRequest)
{
alert('Giving up - cannot create an XMLHTTP instance.');
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('POST', url);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send('userName=' + encodeURIComponent(userName));
}
function alertContents()
{
if (httpRequest.readyState === XMLHttpRequest.DONE)
{
if (httpRequest.status === 200)
{
//alert(httpRequest.responseText);
try
{
var response = JSON.parse(httpRequest.responseText);
}
catch(e)
{
console.log(e.message + " in " + httpRequest.responseText);
return;
}
alert(response.computedString);
}
else
{
alert('There was a problem with the request.');
}
}
}
})();
</script>
EDIT:
The alertContents() function was modified as follows:
function alertContents()
{
if (httpRequest.readyState === XMLHttpRequest.DONE)
{
if (httpRequest.status === 200)
{
//alert(httpRequest.responseText);
console.log(response);
console.log(httpRequest.responseText);
var response = "default message";
try
{
response = JSON.parse(httpRequest.responseText);
}
catch(e)
{
console.log(e.message + " in " + httpRequest.responseText);
return;
}
alert(response.computedString);
}
else
{
alert('There was a problem with the request.');
}
}
}
The first console.log line is line #44 in the script. Rerunning the program and looking in the Console here is what happens:
When
console.log(response);
is commented out this is the result:
ANOTHER EDIT:
The problem does indeed appear to have been in the PHP script. Here is the updated PHP script and the result:
$name = (isset($_POST['userName'])) ? $_POST['userName'] : 'no name';
$computedString = "Hi, " . $name;
$array = ['computedString' => $computedString];
echo json_encode($array);
A further improvement:
$array = ['userData' => $name, 'computedString' => $computedString];
results in:

Updated:
Based on my understanding with your comments, it looks liek your PHP file is not returning the JSON response. It is returning the text whihc you passed from your form. So your responseText is simple string.
Hence, when you are trying to read it's property, it is undefined. Try the following code now.
function alertContents()
{
if (httpRequest.readyState === XMLHttpRequest.DONE)
{
if (httpRequest.status === 200)
{
if(httpRequest.responseText == '')
{
alert('Error in code');
return;
}
alert(httpRequest.responseText);
}
else
{
alert('There was a problem with the request.');
}
}
}
Original:
There is an issue with the variable scope in your code.
var response = JSON.parse(httpRequest.responseText);
Here, you are defining response as a variable inside the try block and then trying to alert outside the block. That is why it is undefined.
Either you should move the alert statement inside the TRY block or define the variable outside.
function alertContents()
{
if (httpRequest.readyState === XMLHttpRequest.DONE)
{
if (httpRequest.status === 200)
{
//alert(httpRequest.responseText);
var response = "Some default message";
try
{
response = JSON.parse(httpRequest.responseText);
}
catch(e)
{
console.log(e.message + " in " + httpRequest.responseText);
return;
}
alert(response.computedString);
}
else
{
alert('There was a problem with the request.');
}
}
}

Related

XML HTTP request fails to send request to my PHP file from JS

In log.js the following function is not working for some reason and I really want it to work and maybe someone knows how to use post instead of get so that I don't have to use cookie to retrieve login info in PHP file
function refreshData(file,msg){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", file);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
location.reload();
} else {
swal(msg);
};
}
}
but without request when I replace that function with this one everything works fine but it opens up a new tab
function refreshData(file,msg){
window.open("login.php");
}
Here is my index.php:
<DOCTYPE! HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="/cafe/script/main2.js"></script>
<link rel='stylesheet' type='text/css' href='../style/main.css' media='screen' />
</head>
<body>
<div align='left' class='nav-top'>
<a class='logo' id='logo'>kush.</a>
<a class='logo2' id='logo'>by</a>
<a href='../novosti' id='btnNews'>news</a>
<a href='../zavedenia' id='btnPlaces'>places</a>
<a href='../kontakty' id='btnContacts'>contacts</a>
<a href='../blog' id='btnBlog'>blog</a>
<script src='log.js'></script>
</body>
</html>
here is my log.js
var authentication = "no";
var authentication=getCookie("auth");
var email=getCookie("email");
if(authentication=="logged_in")
{
//some code
if(email.indexOf("#cafe.eda")>-1)
{
loadCafeProfile(email);
}
else
{
loadPersonProfile(email);
}
}
else
{
//some code
var login = document.getElementById("btnLogIn");
login.addEventListener('click', logIn);
}
function logIn()
{
var email = document.getElementById("InputEmail").value;
var pass = document.getElementById("InputPass").value;
var re = /^[a-zA-Z0-9]+$/i;
if(!validateEmail(email))
{
swal("check email");
}
else if(pass.length<6)
{
swal("max password length 6 char");
}
else
{
setCookie("email",email,1);
setCookie("pass",pass,1);
refreshData("login.php","login in");
}
}
function validateEmail(email)
{
//email validation
return //true false
}
function setCookie(cname,cvalue,exdays)
{
var d = new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires="expires="+d.toGMTString();
document.cookie=cname+"="+cvalue+";"+expires+";path=/";
}
function getCookie( name )
{
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
var end = null;
if (begin == -1)
{
begin = dc.indexOf(prefix);
if (begin != 0)
{
return null;
}
end = document.cookie.indexOf(";", begin);
}
else
{
begin += 2;
end = document.cookie.indexOf(";", begin);
if (end == -1)
{
end = dc.length;
}
}
return decodeURI(dc.substring(begin + prefix.length, end) ).replace(/"/g, '');
}
function loadCafeProfile(email)
{
//load cafe profile
}
function loadPersonProfile(email)
{
//loads persons profile
}
function refreshData(file,msg){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", file);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
location.reload();
} else {
swal(msg);
};
}
}
here is mine login.php
<?php
$ini_array = parse_ini_file("../../db.ini");
$servername=$ini_array['sn'];
$username=$ini_array['un'];
$password=$ini_array['pw'];
$dbname=$ini_array['dn'];
setcookie("jumbo","jumbo",time()+3600,'/');
$conn=new mysqli($servername,$username,$password,$dbname);
//check conection
if(!$conn)
{
setcookie('error','connection_fail',time()+3600,'/');
//header("Location:../cafe");
}
$email=mysqli_real_escape_string($conn,$_COOKIE['email']);
$pass=mysqli_real_escape_string($conn,$_COOKIE['pass']);
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate e-mail and password
if (filter_var($email, FILTER_VALIDATE_EMAIL) && !preg_match('/[^A-Za-z0-9]/', $pass))
{
$pass=md5(sha1(md5($pass)));
if(strpos($email,'#cafe.eda')!==false)
{
$sql="SELECT * FROM cafe WHERE email='".$email."' and parol='".$pass."'";
}
else
{
$sql="SELECT * FROM rebyata WHERE email='".$email."' and parol='".$pass."'";
}
$result = mysqli_query($conn, $sql);
if ($row = mysqli_fetch_array($result, MYSQLI_BOTH))
{
setcookie('auth','logged_in',time()+3600*2400,'/');
setcookie('ses',md5($email.$pass),time()+3600*2400,'/');
//echo "<script>window.close();</script>";
}
else
{
setcookie('error','loginfail',time()+3600*2400,'/');
//header("Location:../cafe");
}
}
else
{
setcookie('error','wrong_input',time()+3600*2400,'/');
//header("Location:../cafe");
}
?>
Okay, so instead of using cookies to transfer data with your xmlHttpRequest() you can pass information using the send() function.
Web APIs | MDN:
send() accepts an optional parameter which lets you specify the request's body; this is primarily used for request such as PUT. If the request method is GET or HEAD, the body parameter is ignored and request body is set to null.
Objects
send() allows for parameters; in this case you can pass the username and password inside of an object:
.send({
user: email,
pass: password
});
Then in PHP just get the $_POST data into the correct array:
if($_POST)
{
$email = $_POST['user'];
$password = $_POST['pass'];
}
Serialize
Or you can serialize the data into a string:
var params = "email="+ email + "&pass="+ password;
Then send it:
.send(params);
If you are using jQuery you can also use their handy little serialize() function.
$('form').serialize();
Which will simply put the items into a string as shown above.
Once you receive the data in the login.php file you can parse the string if serialized, and if you put them into the object, you can just use your standard $_POST variable.
if($_POST)
{
parse_str($_POST, $form);
// you can now get the post data into an array:
$form['email'];
$form['password'];
}
Resolution
Your login() function:
function logIn() {
var email = document.getElementById("InputEmail").value;
var pass = document.getElementById("InputPass").value;
var re = /^[a-zA-Z0-9]+$/i;
if (!validateEmail(email)) {
swal("check email");
} else if (pass.length < 6) {
swal("max password length 6 char");
} else {
refreshData("login.php", {
email: email,
password: pass
});
}
}
Then your refreshData() function would look like this:
function refreshData(file, data) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", file);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(data);
xmlhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
location.reload();
} else {
swal(msg);
};
}
}
Promises
Or, better yet, you can use fetch() which is a better (newer) alternative to xmlHttpRequest. You can also use promises - which work very well.
function refreshData(url, data) {
return fetch(url, {
body: JSON.stringify(data),
cache: 'no-cache',
method: 'POST',
mode: 'cors'
})
.then(function(response){
return response.json();
})
.catch(function(e) {
console.log("Error: ", e);
});
}
That is the new method of implementing AJAX call, if you are interested look MDN's documentation, they are very good and there are also good examples.

GDownloadUrl replacement in Gmap V3

I want to send and receive data from php files. What is the best possible way to do this?
What is the best replacement for GDownloadUrl in Google Map V3?
Here is my existing function to check if I inserted successfully:
function checkSaveGeoFenceData(data,code)
{
//var geoFenceDataJson = eval('(' + json + ')');
if(code===200)
{
//alert("JSON VALUE : "+data+"test");
if(data=="SMGFE\n")
{
alert("Geo Fence " +
document.getElementById("geoFenceName").value +
" Already Exist");
}
else {
alert("Successfully Inserted");
window.opener.location.reload();
window.close();
}
}
else
{
alert("Fail to insert");
}
}
Existing function to grab data from php:
function processtViewData(json)
{
dataJson = eval('(' + json + ')');
var totalData = dataJson.data1.length;
}
There is no equivalent to GDownloadUrl in the API V3. Loading data via AJAX is a general javascrip task that is not specific to the API or to Google Maps.
Here's a function that will do the same:
function ajaxLoad(url,callback,postData,plain) {
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType && plain) {
http_request.overrideMimeType('text/plain');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
eval(callback(http_request));
}
else {
alert('Request Failed: ' + http_request.status);
}
}
};
if (postData) { // POST
http_request.open('POST', url, true);
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http_request.setRequestHeader("Content-length", postData.length);
http_request.send(postData);
}
else {
http_request.open('GET', url, true);
http_request.send(null);
}
}
Make sure your server responds with a content-type:text/plain header
Call it with postdsata:
var postdata = 'a=1&b=2';
ajaxLoad(serverUrl,myCallback,postdata);
function myCallback(req){
var txt = req.responseText;
// optional, if needed to evaluate JSON
eval(txt);
}

How to send data to php file and return the value in javascript function?

In Js file I've created a function which has to send an id and return boolean value to php file which returns false or true; but how can I do it?
JS function
function findDB(id)
{
}
PHP side
include_once("kutuphane/inc.php");
$id = $_POST['tipi'];
$sql= "select count(id) from bolge_db where parent_id=$id";
$faz2= $_SESSION["VT"]->doQuery($sql);
$flag=false;
if($faz2>0)
{
$flag= true;
}
else
{
$flag= false;
}
It's simple AJAX! Try out this code in js:
function MakeRequest()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "ajax.php", true);
xmlHttp.send(null);
}
keep in mind that you have to echo something in php! eg: echo 1; echo 0;
Or using jQuery
var data = {
var1 : "string or another var"
};
$.post('url.php',data , function(data) {
var response = data;
//Do What Ever You Want
});

Posting not working via JS (Jquery) but is with form

I have a rather confusing problem.
I have a php file (http://example.com/delete.php)
<?php
session_start();
$user_id = $_SESSION['user_id'];
$logged_in_user = $_SESSION['username'];
require_once('../classes/config.php');
require_once('../classes/post.php');
$post = new Post(NULL,$_POST['short']);
#print_r($post);
try {
if ($post->user_id == $user_id) {
$pdo = new PDOConfig();
$sql = "DELETE FROM posts WHERE id=:id";
$q = $pdo->prepare($sql);
$q->execute(array(':id'=>$post->id));
$pdo = NULL;
}
else {throw new Exception('false');}
}
catch (Exception $e) {
echo 'false';
}
?>
and I'm trying to get this jquery to post data to it, and thus delete the data.
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short');
var conf = confirm("Delete This post? (" + num + ")");
if (conf == true) {
var invalid = false;
$.post("http://example.com/delete.php", {short: num},
function(data){
if (data == 'false') {
alert('Deleting Failed!');
invalid = true;
}
});
if (invalid == false) {
alert("post Has Been Deleted!");
}
else {
event.preventDefault();
return false;
}
}
else {
event.preventDefault();
return false;
}
});
and when I do that, it returns "Post Has Been Deleted!" but does not delete the post.
Confused by that, I made a form to test the php.
<form action="http://example.com/delete.php" method="POST">
<input type="hidden" value="8" name="short"/>
<input type="submit" name="submit" value="submit"/>
</form>
which works beautifully. Very odd.
I have code almost identical for deleting of a comment, and that works great in the javascript.
Any ideas? Beats me.
Thanks in advance,
Will
EDIT:
this works... but doesn't follow the href at the end, which is the desired effect. Odd.
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short');
var conf = confirm("Delete This Post? (http://lala.in/" + num + ")");
if (conf == true) {
var invalid = false;
$.post("http://example.com/delete/post.php", {short: num},
function(data){
if (data == 'false') {
alert('Deleting Failed!');
invalid = true;
}
});
if (invalid == false) {
alert("Post Has Been Deleted!");
******************************************
event.preventDefault();
return false;
******************************************
}
else {
event.preventDefault();
return false;
}
}
else {
event.preventDefault();
return false;
}
});
If your PHP script delete the post, it doesn't return anything.
My bad, it's not answering the real question, but still is a mistake ;)
Actually, it seems that PHP session and AJAX doesn't quite work well together sometimes.
It means that if ($post->user_id == $user_id) will never validate, hence the non-deleting problem.
2 ways to see this :
Log $user_id and see if it's not null
Try to send the $_SESSION['user_id'] with your ajax post and check with it. But not in production, for security reason.
1-
Your PHP should return something in every case (at least, when you're looking for a bug like your actual case).
<?php
[...]
try {
if ($post->user_id == $user_id) {
[...]
echo 'true';
}
else {throw new Exception('false');}
}
catch (Exception $e) {
echo 'false';
}
?>
2-
jQuery is nice to use for AJAX for many reasons. For example, it handles many browsers and make checks for you but moreover, you can handle success and error in the same .ajax() / .post() / .get() function \o/
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short'); // If that's where your data is... Fair enough.
if (confirm("Delete This Post? (http://lala.in/" + num + ")")) {
$.post("delete/post.php", {short: num}, // Relative is nice :D
function(data){
if (data == 'false') {
alert('Deleting Failed!');
}else{
alert("Post Has Been Deleted!");
// Your redirection here ?
}
});
}
});
3-
If you need to send data from a form to a script and then do a redirection, I won't recommand AJAX which is usually use not to leave the page !
Therefore, you should do what's in your comment, a form to a PHP script that will apparently delete something and then do a redirection.
In your code I don't see num defined anywhere...and invalid isn't set when you think it is, so you're not passing that 8 value back and you're getting the wrong message, either you need this:
$.post("http://example.com/delete.php", {short: $("input[name=short]").val()},
Or easier, just .serialize() the <form>, which works for any future input type elements as well:
$.post("http://example.com/delete.php", $("form").serialize(),
I'm not sure where your code is being called, if for example it was the <form> .submit() handler, it'd look like this:
$("form").submit(function() {
$.post("http://example.com/delete.php", $(this).serialize(), function(data){
if (data == 'false') {
alert('Deleting Failed!');
} else {
alert("Post Has Been Deleted!");
}
});
Note that you need to check inside the callback, since invalid won't be set to true until the server comes back with data the way you currently have it, because it's an asynchronous call.

Why does my AJAX validation code not work properly?

I made a website that depends on PHP, AJAX and Javascript.
The problem here is that the website is unstable which means sometimes the validation is working and some times it is not working at all.
The validation code is written in JavaScript. Does this mean that we need more special conditions?
The code for validation:
<script language=Javascript>
function Inint_AJAX() {
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {} //IE
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE
try { return new XMLHttpRequest(); } catch(e) {} //Native Javascript
alert("XMLHttpRequest not supported");
return null;
};
function dochange(src, val)
{
var req = Inint_AJAX();
req.onreadystatechange = function ()
{
if (req.readyState==4)
{
if (req.status==200)
{
document.getElementById(src).innerHTML=req.responseText;
}
}
};
req.open("GET", "traditional_locate.php?data="+src+"&val="+val);
req.send(null);
}
window.onLoad=dochange('cities', -1);
function submitform()
{
if(document.form1.onsubmit())
{
document.form1.submit();
}
}
function validate()
{
var p_o_box=(document.form1.p_o_box.value);
var owner_name=(document.form1.owner_name.value);
var cities=(document.form1.cities.value);
var post_office=(document.form1.post_office.value);
if(cities == 0)
{
alert("Please Choose city");
document.form1.cities.focus();
return false;
}
else if(post_office == 0)
{
alert("Please Choose post office");
document.form1.post_office.focus();
return false;
}
else if (p_o_box=="")
{
alert ("Please Write P.O.Box");
document.form1.p_o_box.focus();
return false;
}
else if(owner_name=="")
{
alert("Please Write Owner Name");
return false;
}
else if(p_o_box!="")
{
var a=new Array;
<?php
session_start();
$zipinfo=$_SESSION[zip_code];
$conn=mysql_connect('localhost','root','');
mysql_select_db('post_db',$conn);
$query="select p_o_box from p_o_box where zip_code='$zipinfo' ";
$result = mysql_query ($query , $conn ) or die ( mysql_error ());
$rows=mysql_num_rows($result);
$n = array();
for($i=0;$i<$rows;$i++)
{
$data=mysql_fetch_row($result);
$n[] = $data[0];
}
for($i=0;$i<count($n); $i++)
{
echo "a[$i]='".$n[$i]."';\n";
}
?>
var ss=0;
for(i=0;i<a.length;i++)
if(a[i]==p_o_box)
{
var ss=1;
}
if (ss==0)
{
alert('not correct p.o. box');
document.form1.p_o_box.focus();
return false;
}
else
{ return true;}
}
return true;
}
</script>
Very hard to answer because I don't see a question.
What exactly does not work?
But I can suppose some problems:
Are you sure, that body.onload runs? Sometimes doesn't...
scripting is not crossbrowser
session_start() should fail because there is an output before and headers can't be sent.
you said that validation fails, but where is it being called?
please, provide more exact question and more clear example of code which does not work (i.e. I'm not sure, that source of submitform() is so nessecary).
Validation should be done on the server side. What happens when a use disables their JavaScript?
Also, that block of JavaScript will only execute the PHP when the page loads, and not everytime the user validates.

Categories