For some weird reason this line of code is not working:
var ajax = ajaxObj("POST", "php_parsers/status_system.php");
What could it be?
I figured it must be the above line using window.alert's since after that line window.alert does not run.
Full code:
The function is called:
$status_ui = '<textarea id="statustext" onkeyup="statusMax(this,250)" placeholder="What's new with you '.$u.'?"></textarea>';
$status_ui .= '<button id="statusBtn" onclick="postToStatus(\'status_post\',\'a\',\''.$u.'\',\'statustext\')">Post</button>';
The function:
function postToStatus(action,type,user,ta){
window.alert("status passed 1");
var data = _(ta).value;
if(data == ""){
alert("Type something first weenis");
return false;
}
window.alert("status passed 2");
_("statusBtn").disabled = true;
var ajax = ajaxObj("POST", "php_parsers/newsfeed_system.php");
window.alert("status passed 3");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "post_ok"){
var sid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
var currentHTML = _("statusarea").innerHTML;
_("statusarea").innerHTML = '<div id="status_'+sid+'" class="status_boxes"><div><b>Posted by you just now:</b> <span id="sdb_'+sid+'">delete status</span><br />'+data+'</div></div><textarea id="replytext_'+sid+'" class="replytext" onkeyup="statusMax(this,250)" placeholder="write a comment here"></textarea><button id="replyBtn_'+sid+'" onclick="replyToStatus('+sid+',\'<?php echo $u; ?>\',\'replytext_'+sid+'\',this)">Reply</button>'+currentHTML;
_("statusBtn").disabled = false;
_(ta).value = "";
} else {
alert(ajax.responseText);
}
}
}
ajax.send("action="+action+"&type="+type+"&user="+user+"&data="+data);
window.alert("status passed 4");
}
newsfeed_system.php
if (isset($_POST['action']) && $_POST['action'] == "status_post"){
// Make sure post data is not empty
if(strlen($_POST['data']) < 1){
mysqli_close($db_conx);
echo "data_empty";
exit();
}
// Make sure type is a
if($_POST['type'] != "a"){
mysqli_close($db_conx);
echo "type_unknown";
exit();
}
// Clean all of the $_POST vars that will interact with the database
$type = preg_replace('#[^a-z]#', '', $_POST['type']);
$data = htmlentities($_POST['data']);
$data = mysqli_real_escape_string($db_conx, $data);
// Insert the status post into the database now
$sql = "INSERT INTO newsfeed(author, type, data, postdate)
VALUES('$log_username','$type','$data',now())";
$query = mysqli_query($db_conx, $sql);
$id = mysqli_insert_id($db_conx);
mysqli_query($db_conx, "UPDATE newsfeed SET osid='$id' WHERE id='$id' LIMIT 1");
mysqli_close($db_conx);
echo "post_ok|$id";
exit();
}
Ajax methods:
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
Please help!
The ajax is not refrenced! You need to include the library or put the code for calling an 'ajaxObj'.
Related
I am sending some information to a php file that runs a query but I want to also retrieve some information from that php file at the same time. The php file executes fine but I can't get the json_encoded object.
Javascript function that sends a string and a number to a php file:
function open_close(){
var status = encodeURIComponent(SelectedTicket["Status"]);
var ticketNum = encodeURIComponent(SelectedTicket["TicketNum"]);
var info = "Status="+status+"&TicketNum="+ticketNum;
var http3 = createAjaxRequestObject();
if (http3.readyState == 4) {
if (http3.status == 200){
alert("Ticket Updated!"); //This never gets hit
getUpdatedTicket(JSON.parse(http3.responseText));
}
}
http3.open("POST", "openClose.php", true);
http3.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http3.send(info);
}
PHP File that takes the string and number and updates a table
<?php
include("config.php");
session_start();
$status = $_POST["Status"];
$num = $_POST["TicketNum"];
$newStatus = " ";
if(strcmp($status, "Open") == 0){
$newStatus = "Closed";
}
elseif(strcmp($status, "Closed") == 0){
$newStatus = "Open";
}
$sql = "UPDATE tickets SET Status = \"$newStatus\" where TicketNum = $num ";
$r = $conn ->query($sql) or trigger_error($conn->error."[$sql]");
$sql = "SELECT * FROM tickets where TicketNum = $num";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$data[] = $row;
}
echo json_encode($data);
?>
How can I retrieve the json_encoded object in the same javascript function?
You'd need a readyState listener to know when the request is done, and then get the data from the responseText
function open_close() {
var status = encodeURIComponent(SelectedTicket["Status"]);
var ticketNum = encodeURIComponent(SelectedTicket["TicketNum"]);
var info = "Status=" + status + "&TicketNum=" + ticketNum;
var http3 = createAjaxRequestObject();
http3.onreadystatechange = function () {
if (http3.readyState == 4) {
if (http3.status == 200) {
console.log(http3.responseText); // <- it's there
}
}
}
http3.open("POST", "openClose.php", true);
http3.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http3.send(info);
}
As I was coding I encountered an absolute annoying error when callbacking the responseText from PHP.
Now the issue is that, when I run the fpass.php file, and fill out the data, everything works except when callbacking the responseText, for example if it prints out MAIN_FPASS_USER_NO_MATCH from the PHP file it should change the _('status').innerHTML to a different text of my choice, and not what the PHP printed. Some ideas for what I missed in my code?
JS Script:
function fpass(){
var e = _("email").value;
if(e == ""){
_("status").innerHTML = "Type in your email address</br></br>";
} else {
_("fpassbtn").style.display = "none";
_("status").innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "/fpass.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == 'MAIN_FPASS_SUCCESS'){
_("fpassform").innerHTML = '<h3>Step 2. Check your email inbox in a few minutes</h3><p>You can close this window or tab if you like.</p>';
} else if(ajax.responseText == "MAIN_FPASS_USER_NO_MATCH"){
_("fpassbtn").style.display = "none";
_("status").innerHTML = "Sorry that email address is not in our system";
} else if(ajax.responseText == "MAIN_FPASS_EMAIL_FAILURE"){
_("fpassform").innerHTML = "Mail function failed to execute";
} else if (ajax.responseText == "MAIN_FPASS_EXISTS") {
_("fpassform").innerHTML = "already fpass";
} else {
_("status").innerHTML = ajax.responseText;
}
}
}
}
ajax.send("e="+e);
}
JS Functions:
// getElementById Function
function _(x){
return document.getElementById(x);
}
// emptyElement Function
function emptyElement(x){
_(x).innerHTML = "";
}
Ajax Functions:
function ajaxObj(meth, url){
var x = new XMLHttpRequest();
x.open(meth, url, true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//x.send(data);
return x;
}
// END Ajax Object
// Start Ajax Return
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
HTML Code:
<span id="status"></span>
<form id="fpassform" onsubmit="return false;">
<input id="email" type="text" placeholder="Email" onfocus="emptyElement('status')" maxlength="88">
<button id="fpassbtn" onclick="fpass()">Reset</button></br>
</form>
PHP Code:
// AJAX CALLS THIS CODE TO EXECUTE
if(isset($_POST['e'])){
include_once("vendor/db.php");
$e = $mysqli->real_escape_string($_POST['e']);
$usql = "SELECT * FROM users WHERE useremail='$e' AND activated='1' LIMIT 1";
$uresult = $mysqli->query($usql);
$unumrows = $uresult->num_rows;
if($unumrows == 1){
$fpsql = "SELECT * FROM forgotpass WHERE useremail='$e' LIMIT 1";
$fpresult = $mysqli->query($fpsql);
$fpnumrows = $fpresult->num_rows;
if($fpnumrows == 0) {
if($fetch = $uresult->fetch_array(MYSQLI_FETCH_ASSOC)){
$u = $fetch["username"];
$e = $fetch['useremail'];
$pn = $fetch['userphone'];
$fpkey = substr(md5(uniqid($u)), 0, 14);
$sql = "INSERT INTO `forgotpass` (username,useremail,userphone,fpkey)
VALUES ('$u','$e','$pn','$fpkey') ";
if($mysqli->query($sql)) {
$to = "$e";
$from = "auto_responder#yoursite.com";
$headers ="From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1 \n";
$subject ="yoursite Temporary Password";
$msg = 'MSG here';
if(mail($to,$subject,$msg,$headers)) {
echo 'MAIN_FPASS_SUCCESS';
exit();
} else {
echo 'MAIN_FPASS_MAIL_FAILURE';
exit();
}
}
}
} else {
echo 'MAIN_FPASS_EXISTS';
exit();
}
} else {
echo 'MAIN_FPASS_USER_NO_MATCH';
exit();
}
exit();
}
Here is my JavaScript and my PHP for a dynamic ajax search. I am trying to get data from the database and display it in my DOM as a string.
javascript
var searchBox = document.getElementById("searchBox");
var searchButton = document.getElementById("searchButton");
var search = getXmlHttpRequestObject();
searchBox.addEventListener("keyup", ajaxSearch);
function getXmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if (window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
}
else{
alert("Your browser does not support our dynamic search");
}
}
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
delay(displaySuggestions);
}
function displaySuggestions(){
var ss = document.getElementById("searchSuggestion");
ss.innerHTML = '';
string = search.responseText;
ss.innerHTML = string;
}
function delay(functionName){
setTimeout(functionName, 100);
}
function setSearch(x){
document.getElementById("searchBox").value = x;
document.getElementById("searchSuggestion").innerHTML = "";
}
searchBox.addEventListener('click', ajaxSearch);
window.addEventListener('click', function(){
document.getElementById('searchSuggestion').innerHTML = '';
});
php
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "Products";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$searchValue = $_GET['search'];
if(isset($searchValue) && $searchValue != ''){
$search = addslashes($searchValue);
$statement = $conn->prepare("SELECT Name FROM Product WHERE Name LIKE('%" . $search . "%') ORDER BY
CASE WHEN Name like '" . $search . " %' THEN 0
WHEN Name like '" . $search . "%' THEN 1
WHEN Name like '% " . $search . "%' THEN 2
ELSE 3
END, Name");
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($result);
echo $json;
}
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
What i want to know i how to get specific values from my response.
[{"Name":"iMac"},{"Name":"iPad 2"},{"Name":"iPhone 5"},{"Name":"iPhone 6"},{"Name":"iPod Touch"},{"Name":"iWatch"}]
For my search to work effectively i need it to display just the string of the product name and not the whole object.
Using a delay rather than the ajax callback is just shockingly prone to failure. Suppose your ajax call takes more than 100ms? It can totally happen. Similarly, why wait 100ms if your server is nice and fast and it finishes in 25?
Ditch the global search object, and change this:
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
delay(displaySuggestions);
}
to
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
var search = getXmlHttpRequestObject();
if (search) {
search.onreadystatechange = function() {
if (search.readyState == 4 && search.status == 200) {
displaySuggestions(JSON.parse(search.responseText));
}
};
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
}
}
Then displaySuggestions receives an array:
function displaySuggestions(results) {
// Use standard array techniques on `results`, e.g., `results[0]` is the first,
// maybe loop while `index < results.length`, maybe use `results.forEach(...)`...
}
Or taking it further, let's add a level of convenience there:
var failed = false;
function getXmlHttpRequestObject(done, failed){
var xhr;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
if (!failed) {
alert("Your browser does not support our dynamic search");
failed = true;
}
return null;
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200 {
if (done) {
done(xhr);
}
} else {
if (failed) {
failed(xhr);
}
}
}
};
return xhr;
}
Then:
function ajaxSearch(){
var str = escape(document.getElementById('searchBox').value);
var search = getXmlHttpRequestObject(function(xhr) {
displaySuggestions(JSON.parse(xhr.responseText));
});
if (search) {
search.open("GET", '../searchSuggest.php?search=' + str, true);
search.send(null);
}
}
I am having a little trouble figuring out why my ajax response is sending me the entire page.
I am not using conventional AJAX code simply because this is how the guy was doing it in a tutorial I was following. I am using firebug to track all my javascript variables and when I break the code at the responseText var it gives me the entire page. Here is the code for the javascript on the page I am working with :
function changepass() {
var u = _("username").value;
var cp = _("currentPass").value;
var np = _("newPass").value;
var cnp = _("confirmNewPass").value;
if(np != cnp) {
_("status").innerHTML = "The passwords given do not match!";
} else if (cp === "" || np === "" || cnp === "") {
_("status").innerHTML = "Please fill out all of the fields.";
} else {
_("changepassbtn").style.display = "none";
_("status").innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "change_password.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var response = ajax.responseText;
if(response == "success"){
_("status").innerHTML = "Your password change was successful! Click the button below to proceed.<br><br>Back To Home Page";
} else if (response == "no_exist"){
_("status").innerHTML = "Your current password was entered incorrectly.";
_("changepassbtn").style.display = "initial";
} else if(response == "pass_failed"){
_("status").innerHTML = "Change password function failed to execute!";
_("changepassbtn").style.display = "initial";
} else {
_("status").innerHTML = "An unknown error occurred";
_("changepassbtn").style.display = "initial";
}
}
}
ajax.send("u="+u+"&cp="+cp+"&np="+np+"&cnp"+cnp);
}
}
Here is the AJAX code that I use to handle the requests.
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
Any help would be greatly appreciated.
Thanks!
Here is the server side PHP:
if(isset($_POST["u"]) && isset($_POST['oe']) && isset($_POST['ne']) && isset($_POST['p'])) {
$oe = mysqli_real_escape_string($db_conx, $_POST['oe']);
$ne = mysqli_real_escape_string($db_conx, $_POST['ne']);
$p = md5($_POST['p']);
$u = mysqli_real_escape_string($db_conx, $_POST['u']);
var_dump($oe, $ne, $p, $u);
$sql = "SELECT username, password, email FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$db_username = $row[0];
$db_password = $row[1];
$db_email = $row[2];
var_dump($db_username, $db_password, $db_email);
if($db_email != $oe) {
echo "bad_email";
exit();
} else if($db_password != $p) {
echo "no_exist";
exit();
} else {
$sql = "UPDATE users SET email='$ne' WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$sql = "SELECT email FROM users WHERE username='$db_username' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
$db_newemail = $row[0];
if($db_newemail == $ne) {
echo "success";
exit();
} else {
echo "email_failed";
exit();
}
}
}
My mistake was a simple syntax error. Gosh PHP is picky! The error occurs in the ajax.send command. I am miss an '=' on the last parameter.
Thanks for your help guys!
what i am trying to do is getting data from database and tick the checkbox according to that but i did not success any idea?
i am not sure what is the problem
JS code
function editPer(role_pk) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState === 4) {
var jsonObj = JSON.parse(xmlHttp.responseText);
document.getElementById("role_pk1").value = jsonObj.pk;
document.getElementById("role_name1").value = jsonObj.name;
for (var i = 1; i < 29; i++){
if (jsonObj.permission_fk+i != null)
document.getElementById("per"+i).checked = true;
else
document.getElementById("per"+i).checked = false;
}
}
};
xmlHttp.open("GET", "classes/controller/RoleController.php?action=getp&pk=" + role_pk, true);
xmlHttp.send();
/*
* Reset error message
* Show update role button
*/
resetErrorMessage("roleMessage");
showUpdateRoleButton();
$("#perModalDetail").modal('show');
};
PHP code RoleController.php
}else if ($action == "getp") {
if (isset($pk)) {
/*
* Select single Role value
*/
$itemArray = $roleDao->getp($pk);
if (count($itemArray) == 0) {
echo NULL;
} else {
echo json_encode($itemArray[0]);
}
}
PHP code in the class roleDao
public function getp($pk) {
$query = "SELECT pk, name FROM roles WHERE pk=".$pk.";";
$result = mysql_query($query, $this->dbconn);
$itemArray = array();
while ($row = mysql_fetch_row($result)) {
$item = array("pk" => $row[0], "name" => $row[1]);
array_push($itemArray, $item);
}
$query = "SELECT permission_fk FROM role_permission WHERE role_fk=".$pk.";";
$result = mysql_query($query, $this->dbconn);
$i=1;
while ($row = mysql_fetch_row($result)) {
$item = array("permission_fk$i" => $row[0]);
$i++;
array_push($itemArray, $item);
}
//print $itemArray;
return $itemArray;
}