echo is adding a new line to what i output in PHP - javascript

I am sending echoing some data to be received in Javascript however when i debug it, it seems that a new line has been added.
PHP
<?php
header("Content-Type: application/json; charset=UTF-8");
require './connection.php';
$obj = json_decode($_POST["x"], false);
$usernamequery = "SELECT * FROM User WHERE username='$obj->newUser'";
$result = mysqli_query($db, $usernamequery);
$row = mysqli_fetch_assoc($result);
if($row["Username"] == null){
$updatequery = "UPDATE User SET User='$obj->newUser' WHERE username ='$obj->username'";
$result = mysqli_query($db, $updatequery);
echo "valid";
} else{
echo "invalid";
}
?>
JS
///// USERNAME
$(document).ready(function () {
$("#userSubmitForm").on("click", function(e) {
$username = document.getElementById("user").value;
$newUser = document.getElementById("newUser").value;
user = $newUser;
obj = { "username":$username, "newUser":$newUser};
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
validity = this.responseText;
if (validity === "valid"){
$('#usernameModal .modal-header .modal-title').html("Result");
$('#usernameModal .modal-body').html("Your Username Has Been Changed to '$newUser'");
$("#passSubmitForm").remove();
$("#userCloseForm").remove();
window.setTimeout(redirect,3000);
} else{
$('#error').html("This Username Already Exists"); ;
}
}
};
What is happening is responseText will be receive "valid"/"Invalid" as "valid[newline]"/"invalid[newline]"

As stated at http://php.net/manual/en/function.echo.php that can't be a "problem" of the echo. There must be some newline-character after your -tags

A simple solution would be to just trim your response text like this: var validity = this.responseText.trim(); in order to strip it from unwanted space/tab/newline characters.

Related

ajax. Retrieve information from query

I am really confused at the moment, I am very new to all this just being learning java script and php . I am trying to use ajax to check the db to see if the email exist and then if it is cancel the submit of the form. I cant seem to retrieve the information from the XML. I am probably doing it completely wrong, but that why I am asking here , to lean
So if you could help would be great
JAVA SCRIPT
//validate the sign up/regiser form
function validateForm() {
//Get password varibles
var pass = document.forms["signup"]["sign-up-password"].value;
var confPass = document.forms["signup"]["password-confirm"].value;
//Check if they match
if (pass != confPass) {
alert("Password does not match");
return false;
}
//Ajax functions
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
alert("im here");
email = document.getElementById('email2').value;
xmlHttp.open("GET", "php/ajaxCom.php?email=" + email, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout('process()',1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4){
var check=xmlHttp.status;
if(xmlHttp.status==200){
alert("also here 2");
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
alert(message);
return message;
}
}
}
php/xml
<?php
$status;
if (isset($_GET['email'])) {
$email_in_use = $_GET['email'];
$query = mysqli_query($link, "SELECT * FROM users WHERE email='".$email_in_use."'");
if(mysqli_num_rows($query) > 0){
$status = false;
}else{
if( !mysqli_query( $link, $query ) )
{ $status = mysqli_error( $link ); }
else
{ $status = true; }
}
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8" standalone="yes" ?><response><status/></response>');
$xml->response->status = $status;
echo $xml->asXML();
echo $status;
}
?>
You are building and handling ajax XMLHttpRequest in an incorrect way.
Also, to be able to receive an XML response - set additional request header(will be shown further).
Change you ajax request as shown below:
var xmlHttp = null; // this variable should be global to access from different functions
...
//Ajax functions
email = document.getElementById('email2').value;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "php/ajaxCom.php?email=" + email, true);
xmlHttp.setRequestHeader("Accept", "text/xml");
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
...
function handleServerResponse(){
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
var check=xmlHttp.status;
var xmlResponse = xmlHttp.responseXML;
var xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
alert(message);
return message;
} else{
setTimeout('process()',1000);
}
}

Can't Pass Data From PHP to AJAX

I have an input box in html. The input searches an database through ajax and return the results in front-end. The problem is that I don't get the result from PHP. I don't know what I did wrong, so I hope you guys have a better understanding from me.
HTML
<body onload="AjaxFindPerson()">
.....
</body>
JS
var xmlHttp = createXmlHttpRequestObject();
function AjaxFindPerson() {
if ((xmlHttp.readyState == 0 || xmlHttp.readyState == 4) && document.getElementById("PersonSearchInput").value != "") {
person = encodeURIComponent(document.getElementById("PersonSearchInput").value);
xmlHttp.open("GET", "../lib/search.php?email=" + person, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else {
document.getElementById('Label-Result').innerHTML = "";
document.getElementById('UserNameSearchResult').innerHTML = "";
$('#add-person-btn').attr("disabled", "disabled");
setTimeout('AjaxFindPerson()', 1000);
}
}
function handleServerResponse() {
if (xmlHttp.readyState == 4 ) {
if (xmlHttp.status == 200) {
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
result = xmlDocumentElement.firstChild.data;
if (result[0] != false) {
document.getElementById('Label-Result').innerHTML = result[1];
document.getElementById('UserNameSearchResult').innerHTML = result[0];
$('#add-person-btn').removeAttr("disabled", "disabled");
}
else {
document.getElementById('Label-Result').innerHTML = result[1];
}
setTimeout('AjaxFindPerson()', 1000);
}
else {
alert('Somenthing went wrong when tried to get data from server'+ xmlHttp.readyState);
}
}
}
PHP
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
session_start();
define("DB_HOST", 'mysql6.000webhost.com');
define("DB_USER", '');
define("DB_PASSWORD", '');
define("DB_DATABSE", '');
echo '<response>';
$email = $_GET['email'];
$conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db(DB_DATABSE, $conn);
$sq = mysql_query("SELECT UserEmail FROM Users");
$UserInfo = array();
while ($row = mysql_fetch_array($sq, MYSQL_ASSOC)) {
$UserInfo[] = $row['UserEmail'];
}
if (in_array($email, $UserInfo)) {
$result = mysql_query("SELECT UserName FROM Users WHERE UserEmail = '".$email."'");
$row = mysql_fetch_row($result);
$returnRes = array($row[0], "We found results"); //row[0] holds the UserN
echo $returnRes;
}
else {
$returnRes = array(false, "We couldn't find results");
echo $returnRes;
}
echo '</response>';
?>
If we check the php-xml file alone will see the image bellow :
Do I need to pass the values to xml-php with another way?
UPDATE 1 in PHP
I manage to found a way to return the data correctly. Here are the update 'touch'
header('Content-Type: application/json');
and
if (in_array($email, $UserInfo)) {
$result = mysql_query("SELECT UserName FROM Users WHERE UserEmail = '".$email."'");
$row = mysql_fetch_row($result);
echo json_encode(array( 'found' => $row[0], 'msg' => "We found results"));
}
else {
echo json_encode(array( 'found' => null, 'msg' => "We couldn't find results"));
}
The problem now is how to manipulate the js file to handle the return array. I made a try but it didn't worked:
result = xmlDocumentElement.firstChild.data;
if (result['found'] != null) {
document.getElementById('Label-Result').innerHTML = result['msg'];
document.getElementById('UserNameSearchResult').innerHTML = result['found'];
$('#add-person-btn').removeAttr("disabled");
}
else {
document.getElementById('Label-Result').innerHTML = result['msg'];
}
**UPDATE 2 WORKING JS **
I figure out how to retrieve the data from PHP.
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
var result = JSON.parse(xmlDocumentElement.firstChild.data);
if (result['found'] != null) {
document.getElementById('Label-Result').innerHTML = result['msg'];
document.getElementById('UserNameSearchResult').innerHTML = result['found'];
$('#add-person-btn').removeAttr("disabled");
}
else {
document.getElementById('Label-Result').innerHTML = result['msg'];
}
NOW ALL THE CODE IS WORKING! THANK YOU VERY MUCH GUYS!
+1 to all of you!
Four things :
Usage of send(null) doesn't seems to be right, just don't pass null in it.
Second one is timeout method. Instead the way you are using it, you can call it in the callback function or instead of string use the name at the function call.
The usage to remove the attribute is also wrong. It is currently using a set method as you have supplied a second argument. The remove attribute method only takes a attribute name.
I would rather suggest you to set a header for the application/json and use json_encode() method to return data.
For printing an array, you can either use json_encode(), or do somehow else transform your array into a string.
If we were to ignore the white elephant in the room and gloss over the use of mysql_* functions then a slightly different approach
<?php
session_start();
define('DB_HOST', 'mysql6.000webhost.com');
define('DB_USER', '');
define('DB_PASSWORD', '');
define('DB_DATABASE', '');
$dom=new DOMDocument('1.0','utf-8');
$root=$dom->createElement('response');
$dom->appendChild( $root );
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['email'] ) ){
/* Basic filtering IF mysql_* functions are used! */
$email = trim( strip_tags( filter_input( INPUT_GET, 'email', FILTER_SANITIZE_EMAIL ) ) );
$conn = mysql_connect( DB_HOST, DB_USER, DB_PASSWORD );
mysql_select_db( DB_DATABASE, $conn ) or die('error: database connection failed');
/* By the looks of the original there should be no need for two queries and then an array lookup */
$result = mysql_query("SELECT `UserName` FROM `Users` WHERE `UserEmail` = '".$email."';");
/* If there are results, add nodes to the dom object */
if( mysql_num_rows( $result ) > 0 ){
while( $rs=mysql_fetch_object( $result ) ){
$root->appendChild( $dom->createElement( 'user', $rs->UserName ) );
}
} else {
/* Otherwise add error message */
$root->appendChild( $dom->createElement( 'error', 'We couldn\'t find any results!' ) );
}
}
/* Send the xml back to the js client */
header('Content-Type: text/xml');
$xml=$dom->saveXML();
$dom=null;
exit( $xml );
?>

I can't retrieve JSON data array from php page to another

<?php
require_once './db_connect.php';
$db = new DB_Connect();
$db->connect();
$data = json_decode($_POST['myData']);
$array=json_decode($_REQUEST['question']);
if(isset($_POST['myData'])){
$obj = json_decode($_POST['myData']);
//some php operation
$q = "insert into questions(question)
values ('". $obj."')";
$result = mysql_query($q) or die(mysql_error());
}
?>
I want to retrieve the JSON data that is being sent from another php page to this page , but I just can't ,,why is that ?
here's the other page
function validateForm()
{
var q = document.forms["form1"]["question"].value;
var T = document.forms["form1"]["title"].value;
if (T == null || T == "")
{
alert("please type you form title first");
return false;
}
if (q == null || q == "")
{
document.getElementById("question").style.color="black";
alert("please enter your question");
return false;
}
question.push(q);
//alert(JSON.stringify(question));
var xhr = new XMLHttpRequest();
xhr.open('post', 'create_form.php',true);
// Track the state changes of the request
xhr.onreadystatechange = function(){
// Ready state 4 means the request is done
if(xhr.readyState === 4){
// 200 is a successful return
if(xhr.status === 200){
alert(xhr.responseText); // 'This is the returned text.'
}else{
alert('Error: '+xhr.status); // An error occurred during the request
}
}
}
// Send the request to send-ajax-data.php
xhr.send({myData:JSON.stringify(question)}); //+encodeURI(JSON.stringify(question))
// addField();
return true;
}
can someone please help me ??
I'm tried to solve this using jquery ajax , it's just the same ,, that's why i tried to use only javascript to solve this
try this
$json = file_get_contents('php://input');
$obj = json_decode($json, TRUE);
instead of this
$data = json_decode($_POST['myData']);
$array=json_decode($_REQUEST['question']);
if(isset($_POST['myData'])){
$obj = json_decode($_POST['myData']);

Ajax not working in visual studio for windows(Blend)

I am using ajax to login user but this script is not working. When i call login function to execute nothing happens..
function login() {
var login = new XMLHttpRequest;
var e = document.getElementById("email").value;
var p = document.getElementById("password").value;
var vars = "email=" + e + "&password=" + p;
login.open("POST", "http://example.com/app/login.php", true);
login.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
login.onreadystatechange = function(){
if (login.readyState == 4 && login.status == "200") {
var response = login.responseText;
//document.getElementById("status").innerHTML = response;
}
document.getElementById("status").innerHTML = "Loggin in....";
login.send(vars);
if (response == "Sucess") {
window.location.replace("/logged.html");
}
else {
document.getElementById("status").innerHTML == "Login Failed";
}
}
}
login.php contains following codes
require_once('../db_/connection.php');//Holds connection to database
$email = mysqli_real_escape_string($con, $_POST['email']);//Sanitizing email
$pass = md5($_POST['password']);//Hashing password
$sql = "SELECT id FROM users WHERE email='$email' AND password='$pass' LIMIT 1";
$query = mysqli_query($con, $sql);
$check = mysqli_num_rows($query);
if($check < 1){
echo "fail";
//mysqli_close($con);
exit();
}
else{
echo "Sucess";
//mysqli_close($con);
exit();
}
Calling login function does not execute the code.
Line 2: The parentheses are missing after new XMLHttpRequest
Line 15: Your if (response == "Sucess") { ... } is misspelled and it gets executed before the ajax request is returned, because it's asynchronous
I made a working version at JSFiddle for you: http://jsfiddle.net/eRv83/
You might find the MDN referrence helpfull: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

Ajax post request login issue

We are having a issue when trying to login. Is we send our username and password over a XMLhttprequest as post there parameters do not seem to be send with them and therefor we are unable to login.
The code is as following:
Javascript file
$("#submit").click(function(){
console.log("click");
usernm= document.getElementById("username").value;
passwd= document.getElementById("password").value;
var send2 = "username=" + usernm + "&password=" + passwd;
var request = new XMLHttpRequest;
request.open('POST' , "myurl.com/login.php",true);
request.dataType=('jsonp');
request.setRequestHeader("Content-type","application/x-www-form- urlencoded");
request.onreadystatechange = function() {//Call a function when the state changes.
if(request.readyState == 4 && request.status == 200) {
alert(request.responseText);
}
}
request.send(send2);
The login.php is this
require_once 'connect.php';
session_start();
$uName = ($_GET['username']);
$pWord = ($_GET['password']);
$login = "SELECT Username,Password FROM User WHERE Username = '$uName' and Password='$pWord'";
$res = mysql_query($login);
$num_row = mysql_num_rows($res);
$row=mysql_fetch_assoc($num_row);
if( $num_row == 1 ) {
echo "true";
}
else {
echo "false";
}
You collapsed both POST and GET method,
Modify this one,
$uName = ($_POST['username']);
$pWord = ($_POST['password']);
$uName = ($_POST['username']);
$pWord = ($_POST['password']);

Categories

Resources