How Can I Use 2 $_POST without them interfering with one another? - javascript

I'm new to Web Development, and I am trying to understand why when I use 2 $_POST how the second is concatenating with the first. This is causing me to receive an error:
Uncaught SyntaxError: Unexpected number in JSON at position 11
at JSON.parse ()
at XMLHttpRequest.AJAX_handle_response (HangManMath.js:77)
Any Other tips with the code are appreciated as well as resources that will help me better understand AJAX programming.
I don't know that much about PHP, but I have tried everything. My Code is below.
$_POST = json_decode(file_get_contents('php://input'), true);
$response = "";
if (isset($_POST['guess']) && $_POST['guess'] !== '') {
$guess = $_POST['guess'];
if ($guess === 3)) {
$response = "Correct";
}
else {
$response = "Incorrect";
}
$response = json_encode($response);
header('Content-Type: application/json');
echo $response;
}
$_POST = json_decode(file_get_contents('php://input'), true);
if (empty($_POST["current_number"])) {
if($_POST["response-p"] === "Correct!"){
$current_number = 2; // $_POST["current_number"];
$current_number = intval($current_number);
$current_number++;
}
else {
$current_number = 1;//$current_number;
}
$current_number = json_encode($current_number);
echo $current_number;
}
//JAVASCRIPT
function Current_question(current, response){
current_number = document.getElementById(current).value;
response_p = document.getElementById(response).value;
console.log("Response: " + response_p);
console.log("Element id: " + current_number);
let req1 = new XMLHttpRequest();
req1.addEventListener("load", Current_question_status);
req1.open("POST", "HangManMath.php", true);
req1.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
req1.send(JSON.stringify(current_number, response_p));
}
function Current_question_status(){
console.log("Handeling Current_Question");
let current_number = this.responseText;
console.log("Before JSON parse..." + current_number);
current_number = JSON.parse(current_number);
console.log("After JSON parse..." + current_number);
current_number = parseInt(current_number);
if(AJAX_handle_response === "Correct"){
current_number++;
}
document.getElementById("current_number").innerHTML = current_number;
}
// Start an AJAX request with a JSON payload,
// sent via the POST http method to the server
// script (process_guess.php).
function AJAX_start(payload){
console.log("Sending new value to the server.");
console.log(payload);
let req = new XMLHttpRequest();
req.addEventListener("load", AJAX_handle_response);
req.open("POST", "HangManMath.php", true);
req.setRequestHeader("Content-Type", "application/json;charset=UTF-
8");
req.send(JSON.stringify(payload));
}
// Handles the server's response, when it is received.
function AJAX_handle_response(){
console.log("Handling server response: ");
let payload = this.responseText;
console.log("... Response text: " + payload);
if(payload === "")
return false;
payload = JSON.parse(payload);
// decode the guess and result from the server
let result;
if(payload === "Incorrect"){
result = "Incorrect!";
}
else{
result = "Correct!";
}
document.getElementById("response-p").innerHTML = result;
// Now we want to clear the input box as well,
// to make room for the next guess.
document.getElementById("guess").value = "";
return result;
}
I expect "Correct" for one POST and "3" for the other POST
I am actually getting "Correct"3

Related

Json decode from Javascript to php to Javascript

I am trying to get the value from json.stringfy sent to PHP file, for some reason php file is not receiving the key. If I manually add the key it is working fine. What could be wrong here:
My php file:
$request = json_decode(file_get_contents('php://input'), true);
$getID = $request['docid'];
$query = mysqli_query($con, "SELECT * FROM user_details WHERE id = $getID'");
if(mysqli_num_rows($query) > 0)
{
$response["details"] = array();
while ($row = mysqli_fetch_array ($query))
{
// temp user array
$detail = array();
$detail["docname"] = $row["docname"];
$detail["textresults"] = $row["textresults"];
array_push($response["details"], $detail);
}
echo json_encode($response);
$response["success"] = 1;
}
else
{
$response["success"] = 0;
echo json_encode($response);
}
This is my javascript file:
function loadData() {
var docid = window.localStorage.getItem('myKey');
console.log("Docid " + docid);
var xhr = new XMLHttpRequest();
var url = "./api/getData.php";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json);
}
};
var data = JSON.stringify({'docid': docid});
xhr.send(data);
}

Ajax Post from client side to server side to log errors

I'm trying to create an ajax post function which can log the errors at run time and send them silently to the server side for
This is the Code that i gave to post the data from the client side page
var isDebugging = false;
var logJsErrors = true;
alert('passed variable decleration');
function ErrorSetting(msg, file_loc, line_no) {
alert('entered the error setting method');
var e_msg = msg;
var e_file = file_loc;
var e_line = line_no;
var error_d = "Error in file: " + file_loc +
"\nline number:" + line_no +
"\nMessage:" + msg;
if (logJsErrors) {
theData = "file=" + file_loc + "&line=" + line_no + "&err=" + msg;
alert('passed logging errors');
ajaxCtrl(
function () {
return true;
}, "http://localhost:57410/ServerPage.aspx", theData
);
alert('passed the ajax post');
}
if (isDebugging)
alert("Error Found !!!\n--------------\n" + error_d);
return true;
}
window.onload = ErrorSetting;
This is the definition for Ajax post function
var callInProgress = false;
var xmlHttp;
function ajaxCtrl(fnfragment,theUrl,theData){
var bAsync = true;
this.xmlHttp = XmlHttp.create();
if(theUrl)
var url = theUrl;
else{
alert('Target URL is Empty');
return false;
}
try {
xmlHttp.open("POST", url,bAsync);
callInProgress = true;
}catch(e){
callInProgress = false;
return false;
}
if (bAsync) {
xmlHttp.onreadystatechange= function(){
//alert(xmlHttp.readyState);
switch (xmlHttp.readyState) {
case 4:
callInProgress = false;
if(fnfragment){
fnfragment();
// Clean up so IE doesn't leak memory
//delete xmlHttp.onreadystatechange;
//xmlHttp = null;
}
break;
}
/* if(xmlHttp.readyState == 4){
callInProgress = false;
if(fnfragment){
fnfragment();
// Clean up so IE doesn't leak memory
//delete xmlHttp.onreadystatechange;
//xmlHttp = null;
}
} */
}
}
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded;charset=UTF-8");
if(theData)
theKeyValPair = theData;
else
theKeyValPair = "";
try {
callInProgress = true;
xmlHttp.send(theKeyValPair);
}
catch (e) {
callInProgress = false;
alert("Could not contact Server at this Time. Please Try again Later");
return false;
}
if (!bAsync) {
done();
}
}
This is the VB Script that i have tried to add to the server side to get the data from the client page
IF (request.form("") && request.form("file")!="") THEN
Set fcontent = Date+request.form("file")+"\t"+request.form("line")+"\t"+request.form("err")+"\r\n"
MsgBox(fcontent);
WriteToFilecustom(fcontent)
END IF
function WriteToFilecustom(log)
set filename = "Logs\errorlog.txt"
Dim fso, fs,tfile,fo
Set fso = CreateObject("Scripting.FileSystemObject")
IF (fso.FileExists(filename)) then
const ForAppending =8
Set tfile = fso.OpenTextFile(filename, ForAppending ,true)
tfile.WriteLine(log)
else
Set fo=fso.GetFolder(".\Logs")
Set tfile=fo.CreateTextFile(name,false)
tfile.WriteLine(log)
END IF
tfile.Close
Set fo = Nothing
Set fso = Nothing
end function
I don't understand where i am going wrong as my post method is calling the URL but i'm unable to post the data

Using Ajax/XMLhttprequest to send data to a php file with mail function

I have been following this tutorial (https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started) but I had no luck. I am trying to communicate with a php file with a javascript file using XMLhttpRequest. This is the code bellow. I still dont understand how to fully transfer the data across.
HTML
form id="uDF" method="post" onsubmit="submitValidation()">
JavaScript
function submitValidation(){
var data = [document.forms ["uDF"] ["uDFName"].value, document.forms ["uDF"] ["uDFNumber"].value,
document.forms ["uDF"] ["uDFEmail"].value, document.forms ["uDF"] ["uDFSubject"].value,
document.forms ["uDF"] ["uDFMessage"].value,]
console.log(data);
var char = ''; // variable used to check whether email has #
var x;
var isEmail = false;
var isNotEmpty = false;
//for loop checks email for # char
for(x = 0; x<data[2].length;x++)
{
char = data[2].charAt(x);
if(char === "#"){
isEmail = true;
break;
}
}
var i;
//for loop check if data is collected
for(i=0;i < 5;i++){
if(data[i] === ""){
isNotEmpty = false;
}else{
isNotEmpty = true;
}
}
if(isEmail === true && isNotEmpty === true)
{
var httpRequest;
httpRequest = new XMLHttpRequest();
if(!httpRequest){
return false;
}
httpRequest.onreadystatechange = function(){
if(httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200)
{
var response = JSON.parse(httpRequest.responseText);
}
httpRequest.open('POST', '../userData.mail.php')
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send('uDFName=' + encodeURIComponent(data[0]) + 'uDFNumber=' + encodeURIComponent(data[1]) + 'uDFNumber=' + encodeURIComponent(data[3])
+ 'uDFNumber=' + encodeURIComponent(data[4]))
}
}else if (!isNotEmpty){
alert("empty fields");
}else if(!isEmail){
alert("Please enter valid email!");
}
}
PHP
$uDFName = (isset($_POST['uDFName'])) ? $_POST['uDFName'] : '';
$uDFNumber = (isset($_POST['uDFNumber'])) ? $_POST['uDFNumber'] : '';
$uDFEmail = "my#email";
$uDFSubject = (isset($_POST['uDFSubject'])) ? $_POST['uDFSubject'] : '';
$uDFMessage = $uDFName . "\r\n" . $uDFNumber . "\r\n" . "just testing";
$message = wordwrap($message, 70, "\r\n");
mail($uDFEmail, $uDFSubject, $uDFMessage);
You have to open and send the request outside of the event handler function. The onreadystatechange handler only executes when the ready state of your request changes.
If you don't open and send the request, the handler function is not executed, and you won't see any results.
This solution should work:
var httpRequest = new XMLHttpRequest();
// this function executes whenever the ready state of the request changes
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
var response = JSON.parse(httpRequest.responseText);
}
}
// open the request ...
httpRequest.open('POST', '../userData.mail.php')
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// ... and send it
httpRequest.send('uDFName=' + encodeURIComponent(data[0]) + 'uDFNumber=' + encodeURIComponent(data[1]) + 'uDFNumber=' + encodeURIComponent(data[3])
+ 'uDFNumber=' + encodeURIComponent(data[4]));

jQuery.post() dynamically generated data to server returns empty response

I'm generating a series of variables in a loop (using JS), and I'm assigning them an .id and a .name based on the current index. At each loop I'm sending a request to the server using jQuery.post()method, but the returning response is just an empty variable.
Here's the code:
JavaScript
for ( var index = 0; index < 5; index++ ) {
var myVar = document.createElement('p');
myVar.id = 'myVarID' + index;
myVar.name = 'myVarName' + index;
//Send request to server
$(document).ready(function(){
var data = {};
var i = 'ind';
var id = myVar.id;
var name = myVar.name;
data[id] = name;
data[i] = index;
$.post("script.php", data, function(data){
console.log("Server response:", data);
});
});
}
PHP
<?php
$index = $_POST['ind'];
$myVar = $_POST['myVarID'.$index];
echo $myVar;
?>
Response: Server response: ''
If I instead set a static index in JS code, getting rid of the loop, so for example:
var index = 0;
I get the expected result: Server response: myVarName0
Why is this happening? And how can I solve it?
Assuming the php file is in order. I use this:
function doThing(url) {
getRequest(
url,
doMe,
null
);
}
function doMe(responseText) {
var container = document.getElementById('hahaha');
container.innerHTML = responseText;
}
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)
;
}
}
var thing = "script.php?" + url;
req.open("GET", thing, true);
req.send(null);
return req;
}
then use it like this:
doThing("myVarID="+myVar.id+"&i="+index);
also, you will have to change your PHP to something like this:
<?php
$index = $_GET['ind'];
$myVar = $_GET['myVarID'.$index];
echo $myVar;
?>
Obviously this code needs to be edited to suit your own needs
the function doMe is what to do when the webpage responds, in that example I changed the element with the id hahaha to the response text.
This won't win you any prizes but it'll get the job done.
Solution
It is working fine removing:
$(document).ready()
Working code
for ( var index = 0; index < 5; index++ ) {
var myVar = document.createElement('p');
myVar.id = 'myVarID' + index;
myVar.name = 'myVarName' + index;
//Send request to server
var data = {};
var i = 'ind';
var id = myVar.id;
var name = myVar.name;
data[id] = name;
data[i] = index;
$.post("script.php", data, function(data){
console.log("Server response:", data);
});
}

Unexpected end of input error with chrome.tabs.query

I've been struggling with this and have had no luck. I've included the error and most of the context around the block in question.
var successURL = 'https://www.facebook.com/connect/login_success.html';
var userFirstName = ''
var userEmail = ''
function onFacebookLogin(){
if (localStorage.getItem('accessToken')) {
chrome.tabs.query({}, function(tabs) {
for (var i = 0; i < tabs.length; i++) {
if (tabs[i].url.indexOf(successURL) !== -1) {
var params = tabs[i].url.split('#')[1];
var accessToken = params.split('&')[0];
accessToken = accessToken.split('=')[1];
localStorage.setItem('accessToken', accessToken);
chrome.tabs.remove(tabs[i].id);
console.log(accessToken);
pullSecurityToken();
findFacebookName();
}
}
});
}
}
chrome.tabs.onUpdated.addListener(onFacebookLogin);
function pullSecurityToken(){
var pointUrl = "localhost:3000/api/v1/retrieve_token_for/" + localStorage.accessToken + "/" + localStorage.securityToken;
var xhr = new XMLHttpRequest();
xhr.open("GET", pointUrl, true);
alert(JSON.parse(xhr.responseText));
}
var response = ''
function findFacebookName(){
if (localStorage.accessToken) {
var graphUrl = "https://graph.facebook.com/me?access_token=" + localStorage.accessToken;
console.log(graphUrl);
var xhr = new XMLHttpRequest();
xhr.open("GET", graphUrl, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if(xhr.status == '401'){
alert("Security Token Invalid, please check and try again.");
}
response = JSON.parse(xhr.responseText);
userFirstName = response.first_name
userEmail = response.email
console.log(response);
}
}
}
xhr.send();
}
Here's the error:
Error in response to tabs.query: SyntaxError: Unexpected end of input
at onFacebookLogin (chrome-extension://dapeikoncjikfbmjnpfhemaifpmmgibg/background.js:7:17)
Even if you use a synchronous request, you still need to send it. So add an xhr.send(); after the xhr.open inside pullSecurityToken.
As Felix Kling points out in the comments, the lack of send will directly cause your error, because the responseText property is still an empty string and such a string is not valid JSON whereas "" would be valid JSON.

Categories

Resources