I am working on a project for a client and they want to be able to update a list of costs dynamically depending on the registrants status as member/non-member or student. So I thought AJAX would have been the best way to do this but I am having trouble with my implementations. Every time I send my object I get a syntax error. I have placed the code below.
JavaScript
function checkMember(){
var member = document.getElementById("user_mem_id");
if(member.value == "" || member.value.trim() == ""){
document.getElementById("testError").innerHTML = "Please enter a membership id<br>";
document.getElementById("testError").style.color = "red";
}else{
var json = { "data":[{"membership_id":member.value}]}
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// For Old Microsoft Browsers
}catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");// For Microsoft IE 6.0+
}catch (e2) {
xmlHttp = false;// No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();//For Mozilla, Opera Browsers
}
xmlHttp.open("POST","member_check.php",true);
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("data=" + json);
xmlHttp.onreadystatechange=function(){
if (xmlHttp.readyState==4 && xmlHttp.status==200){
document.getElementById("testError").innerHTML=xmlHttp.responseText;
console.log(xmlHttp.responseText);
json_last_error;
};
};
}
}
PHP
<?php
if(isset($_POST["data"]))
{
$data = $_POST["data"];
$res = json_decode($data, true);
echo $data[membership_id];
}
The other issue is that when I try and access the membership "cell" of the data array I get illegal off set string. Thus I thought I had declared my original JSON object incorrectly but I appears (as I have viewed many examples on here and else where) that I have declared that correctly.
I think you need to use stringify in order to perform the post successfully.
var json = { "data":[{"membership_id":member.value}]};
json_data = JSON.stringify(json);
then use json_data in your ajax call.
There are quite a few things wrong with your code. As I stated in my first comment to you, you need to escape your json before you send it in the query string, as json converted to a string, without any special rules applied turns into [object Object], and that isn't valid json, nor is it parsed as such.
To do that, use JSON.stringify(json);. Example:
function checkMember(){
var member = document.getElementById("user_mem_id");
if(member.value == "" || member.value.trim() == ""){
document.getElementById("testError").innerHTML = "Please enter a membership id<br>";
document.getElementById("testError").style.color = "red";
}else{
var json = { "data":[{"membership_id":member.value}]}
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");// For Old Microsoft Browsers
}catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");// For Microsoft IE 6.0+
}catch (e2) {
xmlHttp = false;// No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();//For Mozilla, Opera Browsers
}
xmlHttp.open("POST","member_check.php",true);
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.send("data=" + JSON.stringify(json));
//json turned into proper string
//I should also note, you should url-encode this string if it contains
//any special characters using encodeURIComponent()
xmlHttp.onreadystatechange=function(){
if (xmlHttp.readyState==4 && xmlHttp.status==200){
document.getElementById("testError").innerHTML=xmlHttp.responseText;
console.log(xmlHttp.responseText);
//json_last_error; //Commented this out, as it will
//echo an error, causing the script to halt, as it doesn't
//exist.
};
};
}
}
Secondly, you send an object whose key 'data' contains an array of objects.. not a simple object:
<?php
if(isset($_POST["data"]))
{
$data = $_POST["data"];
$res = json_decode($data, true);
echo $data[membership_id]; // There are many things wrong here
// ^ ^ this is not a constant and likely does not exist.
// |- This is still your string, which doesn't work
}
<?php
if(isset($_POST["data"]))
{
$data = $_POST["data"];
$res = json_decode($data, true);
echo $res['data'][0]['membership_id'];
// ^ ^ ^ ^
// | |first item |-string
//The result|-string
}
Hopefully my comments will be self explanatory.. but in case they are not... $res is your decoded array, 'data' is the first position of that array, 0 is the first position of the array at that position, and 'membership_id' is the item you want to access. You access members as strings, indexes as integers.
The basic problem with your code is the ";" terminator when you are defining variable. Check your following line
json = { "data":[{"membership_id":member.value}]}
You haven't put a semicolon at the end. (however it might still work a few times but mostly its an error)
Rather you have written a lot of code too. I would suggest you to use jquery's $.ajax function to simplify your task.
Also in case if you only have membership id in your json data its more easy to create a json object like the one below
var json = {"membership_id" : member.value " } ;
Also you need to send your json data after quoting in string using JSON.stringify(json)
Related
I know how to pass data from JS to PHP using AJAX, but have no idea how to select data to JS from db using AJAX+php.
I tried to find examples of it but nothing clear found.
Could anyone show me how can I get data from SQL? How I tried:
js function
getdata() {
// ?
var result // I want result to store here
var data = new FormData();
data.append('somekey', 'somevalue');
// AJAX CALL
var xhr = new XMLHttpRequest();
// query for getting some data from SQL
xhr.open('POST', "../php/get_answer.php", true);
xhr.onload = function(){
result = this.response // I presume that I can get result here
};
xhr.send(data);
console.log("RESULT GETTING JSON")
console.log(result)
}
get_answer.php
<?php
include("config.php");
$con = setConnection();
$id = $_COOKIE["id"];
$query = "SELECT results FROM `survey_results` WHERE user_id='$id'";
$n = mysqli_query($con, $query);
$results = 0;
while ($row = mysqli_fetch_assoc($n)) {
$results = $row['results'];
}
// return results ?
$con->close();
?>
In your php file, you can return your data as JSON string.
To do this, tell the client it's json by settings the response header to
header('Content-Type: application/json');
and return the results or data with
echo json_encode($data);
For the Javascript part, XMLHttpRequest is now an old way to make Ajax request but it's a good start to learn.
Fisrt, in your code you have to check if XMLHttpRequest is available in the navigator and try to use the old IE fashion way if not. To do this:
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
now you have your object so you have to set a listener witch listen for change in the state of XMLHttpRequest. If all seems ok the result go there:
xhr.onreadystatechange = function()
{
console.log("Wait server...");
if(xhr.readyState == 4) // 4 : request finished and response is ready
{
if(xhr.status == 200) // HTTP OK
{
console.log("Got data!");
result=xhr.responseText; // or result = JSON.parse(xhr.responseText) to have your data as js object
//It's here you have to modify your dom to show your data, change a variable, etc...
} ;
else // bad http response header like forbiden, not found, ...
{
console.log("Error: returned status code", xhr.status, xhr.statusText);
}
}
};
now you can set the URI and send your request:
xhr.open("GET", "../php/get_answer.php", true);
xhr.send(null)
;
If you want more informations about states and status, have a look at XMLHttpRequest Object Methods
I started learning about AJAX very recently and this little problem seemed to have come out of no where. I wrote an html page that uses this code to create an AJAX connection and send a get request with an id.
function loadXML() {
var xmlhttp;
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("text").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "textTesting.php?id='first'", true);
xmlhttp.send();
}
In my textTesting.php, just for the sake of testing, I compared incoming variable $_GET[id] with the string I expect to be true, first. But the comparison always seem to fail for some reason.
textTesting.php:
<?php
$output = "";
if(isset($_GET["id"])) {
$output = $_GET["id"];
if($output == 'first'){
$output .= " confirmed";
}
}
echo $output;
?>
Is there a concept of PHP or AJAX that I am missing? When writing this if statement I was expecting 'first confirmed' to become the output.
Please ask any further question if needed.
The value you are passing is 'first' but you are comparing it against first so it doesn't match.
In your query string the quotes are data. In your PHP, the quotes are string delimiters.
Either add quotes to the data in the PHP or remove them from the query string.
I am trying to upload an image and some strings/numbers using AJAX. The code is working fine (as in, everything is getting into the database) except for one very important problem. I very much want the "character" variable to be unique, and every attempt I use to bring up an error message for trying a character name that has already been taken does not work. Here is my code:
AJAX:
function CSubmit() {
clearInterval(MoveDrawTimer);
var a=document.forms['form-id']["thefiles"].value; if (a == "") { document.getElementById("info").innerHTML="You must upload an image."; return };
if (showFileSize() > 5000000) { document.getElementById("info").innerHTML="File is too big. Maximum size is 5,000,000 bytes."; return };
var accepted = [".gif",".png",".jpg",".jpeg"];
if (Ext in oc(accepted) == true) {
var dataURLToBlob = function(dataURL) {
var BASE64_MARKER = ';base64,';
if (dataURL.indexOf(BASE64_MARKER) == -1) {
var parts = dataURL.split(',');
var contentType = parts[0].split(':')[1];
var raw = parts[1];
return new Blob([raw], {type: contentType});
}
var parts = dataURL.split(BASE64_MARKER);
var contentType = parts[0].split(':')[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {type: contentType}); };
newImage = dataURLToBlob(dataURL); } else { document.getElementById("info").innerHTML="Cannot send file. Check your extensions."; return };
var canvas = document.getElementById("Cinfo");
var context = canvas.getContext("2d");
context.clearRect(0, 0, 400, 400);
var TotalSpent = StrPts + IntPts + WisPts + SpdPts + MovPts;
var theform = document.getElementById("CharName");
if (theform.value == "") { document.getElementById("info").innerHTML="Your character must have a name."; return }
if ( /[^a-zA-Z0-9]/.test(theform.value) ) {
document.getElementById("info").innerHTML="Name must contain only letters and / or numbers."; return }
if (theform.value.length > 14) { document.getElementById("info").innerHTML="Character names must be 14 characters max."; return }
if (TotalSpent !== 2) { document.getElementById("info").innerHTML="You must spend exactly 2 points."; return }
var fd = new FormData();
fd.append('data', newImage);
fd.append('character', theform.value);
fd.append('str', StrPts);
fd.append('int', IntPts);
fd.append('wis', WisPts);
fd.append('spd', SpdPts);
fd.append('mov', MovPts);
//beginning of server transmission. above is javascript front end authentication.
//sending the following information:
//theform.value // character name
//StrPts, IntPts, WisPts, SpdPts, MovPts // the character stats
var xmlhttp;
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.onreadystatechange=function(){ xmlhttp.addEventListener("progress", document.getElementById("info").innerHTML="Please wait . . ." , false);
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
if (xmlhttp.responseText.length <= 14) {
document.getElementById("info").innerHTML="Congratulations, " + xmlhttp.responseText + " has been approved.";
SelectScreen();} } }
xmlhttp.open("POST","CHunique.php",true);
xmlhttp.send(fd);
};
As you can see, I am appending everything to a form and then sending it to CHunique.php, which is the following (currently an incomplete test page for demonstration of problem):
<?php
#$con=mysqli_connect("$db_host","$db_username","$db_pass", "$db_name") or die ("Could not connect to the database. Please try again later.");
mysqli_set_charset($con,"UTF8");
$Err = "fine";
session_start();
$login = $_SESSION['account'];
$CHresult = mysqli_query($con,"SELECT * FROM CHstats");
while($row = mysqli_fetch_array($CHresult)) {
$thecharacters = $row['character'];
if (strtolower($character) === strtolower($thecharacters)) { $Err = " Character name already in use."; break; }; }
The problem here is that I do not get any response back from the server at all. It stays infinitely on its "progress" function, which is to say "Please wait . . . " This is true for ALL while loops that I attempt on the php page...the server just gets stuck in loading. This is a huge problem because I need to use a while loop to loop through all the characters in order to see if the user's name is unique or not.
Again, everything is working fine, including the image upload, EXCEPT for this check. This check is very important, and I'm wondering why every single while loop I try in the php page just results in an infinite load time?? Please help.
Also keep in mind I do not use JQuery.
Why not just change your query to do the work for you, doesn't really make sense to do the comparison in PHP
$query = sprintf("SELECT * FROM CHstats WHERE LOWER(character) = LOWER('%s')", $thecharacters);
$result = mysqli_query($con, $query);
if(mysqli_num_rows($result) > 0){
// duplicate character name
}
Also, are you sure that the while loop is what's causing your page to hang? It is very likely that the connection to mysql isn't being made or is taking a long time. If you haven't already, move a die statement around your code to see where it is getting hung up.
YES! I actually solved it all on my own after several hours of frustration. The answer lies in my stupid AJAX conditional: if (xmlhttp.responseText.length <= 14). The responses were more than 14 characters and thus caused the server to load indefinitely.
I would like to display a list when a user is typping text (like autocompletion).
I load a xml with the list and when the user is typping text, a javascript function loops into the xml to find matches.
Everything is ok except on Internet Explorer where it SOMETIMES displays this error : "SCRIPT65535: Invalid calling object".
The first time i call the js function to loop into the xml always works but if i wait 5 seconds before calling it again, it will dispay the error.
If i wait less than 1 second it won't display the error.
It may be because in the loop i call the getAttribute() method... when i remove it there is no error.
Thx for any help !
Here is the code :
Ajax loading :
var ajax = {};
ajax.getXMLHttpRequest = function(){
var xhr = null;
if(window.XMLHttpRequest || window.ActiveXObject){
if(window.ActiveXObject){
try{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
else xhr = new XMLHttpRequest();
}
else return null;
return xhr;
};
ajax.loadFile = function(callback){
var xhr = ajax.getXMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)){
callback(xhr.responseXML);
xhr = null;
}
};
xhr.open("GET", 'file.xml', true);
xhr.setRequestHeader("Content-Type", "text/xml");
xhr.send(null);
};
ajax.loadFile(callback);
Callback function :
var xml_nodes = '';
function callback(response){
xml_nodes = response.getElementsByTagName('node');
}
Then a mouseclick or whatever triggers this function :
function buttonClick(){
for(var i=0; i<xml_nodes.length; i++){
var attr = xml_nodes[i].getAttribute('attr');
}
}
This is a caching problem that only occurs in Internet Explorer. Your callback(response) function assigns the node elements to the xml_nodes variable. These nodes are a part of the response which is a part of the XMLHttpRequest, which gets disposed because you have no pointers to it.
The buttonClick function will iterate over the xml_nodes that are connected to disposed XMLHttpRequest's. And these are disposed because you have no pointers to it, and are therefore invalid objects.
A simple workaround will be caching your requests in an array. However this will result in large amounts of unwanted memory usage. You should create objects from the xml response and store them. These new objects won't have any pointers to the responseXML and are therefore valid objects.
Hope this helped, had the same problem to :)
The php script is returning a value and the 1st alert works.
I am unable to reference the value returned by httprequest at the 2nd alert. Ideally, I would call the function get_captcha() - and it would return the value - its just that I dont know how to do this.
I realize setting the variable globally may not be the best way to do this but its the only thing I could think of - Im open to alternatives.
<script type="text/javascript">
var url = "captcha_get_code.php"; // The server-side script
var cap;
function ValidateForm() {
get_captcha()
alert(cap); //undefined
}
function get_captcha() {
http.open("GET", url, true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
}
function handleHttpResponse() {
if (http.readyState == 4) {
if (http.status==200) {
//return http.responseText;
cap=http.responseText;
alert(cap); //this one works
}
}
}
function getHTTPObject() {
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlhttp;
}
var http = getHTTPObject(); // We create the HTTP Object
</script>
You cannot "return" values from successful XMLHttpRequest invocations. You can perform whatever sort of processing you need inside the callback function.
XMLHttpRequests are performed asynchronously. You cannot make your code "wait" for them (unless you make them synchronous) (and you really, really should not do that). There's no real need, however, because the runtime system will call your "readystatechange" handler when the request completes. From in that code, you're free to do whatever you need.
This fact requires you to think a little differently about how to write the code, but it's not really that much of an adjustment. If, for example, you would be inclined to write a "processResults()" function, then you can still do that — you would simply call that from inside the "readystatechange" handler.
I see this thread is 4 years old, but it has wrong answer!
You can get return value from a successful XMLHttpRequest invocations.
My project use WebSocket, but it use XMLHttpRequest to upload images.
In a javascript, call uploadSend(containerID) where all <img> are stored.
// ----- uploadSend()
// ----- This function sends all objects in a container (containerID)
// ----- All object has to be <img>
FILE: upload.js
function uploadSend(containerID) {
var elm = document.getElementById(containerID);
for (i=0; i<elm.childNodes.length; i++) {
var form = new FormData();
form.append('id', elm.childNodes[i].id);
form.append('src', elm.childNodes[i].src);
TOS(form);
}
}
function xhrState(self) {
if ((self.readyState == 4) && (self.status === 200))
console.log(self.responseText);
}
function xhrProgress(event) {
if (event.lengthComputable)
if (event.loaded == event.total)
console.log('Image 100% uploaded.');
}
function TOS(form) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () { xhrState(this); }
xhr.open('POST', '/upload.php');
xhr.upload.onprogress = function(event) { xhrProgress(event); }
xhr.send(form);
}
FILE: upload.php
header("Content-type: text/plain");
$filename = '/var/www/public/upload/'.microtime(true);
// ----- Save a complete file for what we did get.
$hnd = fopen($filename . 'TXT', 'wb');
fwrite($hnd, print_r($_COOKIE, true));
fwrite($hnd, print_r($_GET, true));
fwrite($hnd, print_r($_FILES, true));
fwrite($hnd, print_r($_POST, true));
fclose($hnd);
// ----- Save just jpg for the images we did get.
$hnd = fopen($filename . 'jpg', 'wb');
$image = explode(',', $_POST['src']);
fwrite($hnd, base64_decode($image[1]));
fclose($hnd );
// ----- Type the result that you want back.
echo "{$filename}.jpg";