can't parse JSON data from php when using parse() function - javascript

I have trouble converting json data from PHP into javascript JSON format. When I use the responseText() function, I can see the that data was parsed successfully from PHP. But when I convert the ajax response to JSON, for example, var json = JSON.parse(ajax.responseText), I don't see any information outputted to the screen. I don't mind jquery answers, but I would like to see at least an example in pure javascript.
header('Content-Type: application/json');
if (isset($_POST["height"])) {
$height = preg_replace('/[^0-9]/', '.', $_POST['height']);
$width = preg_replace('/[^0-9]/', '.', $_POST['width']);
$areaInches = $height * $width;
$areaCM = $areaInches * 0.00064516;
$result = array(
'area_inches' => $areaInches,
'area_cm' => $areaCM
);
echo json_encode($result);
}
function sendData() {
var height, width;
height = parseFloat(document.getElementById('input_height').value);
width = parseFloat(document.getElementById('input_width').value);
console.log(height);
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var json = JSON.parse(ajax.responseText);
document.getElementById('jsondata1').innerHTML = json.area_inches + "ft^2";
document.getElementById('jsondata2').innerHTML = json.area_cm + "cm^2";
console.log(ajax.responseText);
} else {
console.log('error');
}
};
ajax.open("POST", "calculate_area.php", true);
ajax.setRequestHeader("Content-type",
"application/x-www-form-urlencoded");
ajax.send('height=' + height +
'&width=' + width
);
}
<h1>Calculate Area of Rectangle</h1>
<div class="wrapper">
<label>Height</label>
<input id="input_height" class="clear" type="text">
</div>
<div class="wrapper">
<label>Width</label>
<input id="input_width" class="clear" type="text">
</div>
<br>
<div class="wrapper">
<button onclick="sendData();">Calc. Area</button>
<input id="jsondata1" class="mt" type="text" readonly>
<input id="jsondata2" class="mt" type="text" readonly>
<div></div>
</div>

Related

Pass session variable as Key-Value pair to PHP file using AJAX post

I have a session variable, say $_SESSION['Current_User']. I want to pass it to a URL as a key-value pair using AJAX. I have some HTML inputs as follows:
HTML is:
<INPUT type='text' name='input_1' id="INPUT_1"></INPUT>
<INPUT type='text' name='input_2' id="INPUT_2"></INPUT>
<INPUT type='text' name='input_3' id="INPUT_3"></INPUT>
<BUTTON id="BUTTON_1" name="BUTTON_1_SUBMIT" value="SUBMIT_1" onclick="ajax_post()">Post</BUTTON>
<DIV id="Sub_Div_4"></DIV>
Javascript is:
function ajax_post()
{ var AJAX = new ajaxFunction();
AJAX.onreadystatechange = function()
{ if((AJAX.readyState == 4) && (AJAX.status == 200))
{ var PHP_REPLY = AJAX.responseText;
var RECI_EVE_D = JSON.parse(PHP_REPLY);
var STRING_jsonified = "|||data_1: " + RECI_EVE_D.data_1 + "||| data_2: " + RECI_EVE_D.data_2+ "||| data_3: " + RECI_EVE_D.data_3;
document.getElementById("Sub_Div_4").innerHTML = STRING_jsonified;
} }
var INP_1 = document.getElementById("INPUT_1").value;
var INP_2 = document.getElementById("INPUT_2").value;
var INP_3 = document.getElementById("INPUT_3").value;
var PARAM = "input_1=" + INP_1 + "&input_2=" + INP_2 + "&input_3=" + INP_3 ;
AJAX.open("POST", "PHP/PHP_SIMPLE_AJAX_POST.PHP", true);
AJAX.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
AJAX.send(PARAM);
}
Lets say, the PHP file PHP_SIMPLE_AJAX_POST.PHP needs that session information, and the user inputs to do some processing and send back JSON. So my question is, how do I package the existing $_SESSION['Current_user'] and send it to the PHP file?
Thanks, much appreciated!!
If you mean, how to use the value of any currently existing $_SESSION values, you could try this:
<INPUT type='text' name='input_1' value="<?php echo $_SESSION['Current_user']['input_1']; ?>" id="INPUT_1"></INPUT>
<INPUT type='text' name='input_2' value="<?php echo $_SESSION['Current_user']['input_2']; ?>" id="INPUT_2"></INPUT>
<INPUT type='text' name='input_3' value="<?php echo $_SESSION['Current_user']['input_3']; ?>" id="INPUT_3"></INPUT>
Update
Then you should manipulate the $_POST value in your PHP script as such:
$_SESSION['Current_user']['input_1'] = $_POST['input_1'];
$_SESSION['Current_user']['input_2'] = $_POST['input_2'];
$_SESSION['Current_user']['input_3'] = $_POST['input_3'];

creating and passing a checkbox array to javascript function

I have an html form displaying a series of checkboxes. The checkboxes (an array called "checkbox" is ) are created using a loop in php. I want to use this array for some background processing.
Trying to use AJAX as below, but I am not able to get it working.
Please help!
Here is test.php: containing html form:
<!DOCTYPE html>
<script language="javascript">
function activate(checkbox){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
document.getElementById("ajaxState").innerHTML =xhttp.readyState;
document.getElementById("ajaxStatus").innerHTML =xhttp.status;
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("ajaxResponse").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "process.php", true);
xhttp.setRequestHeader( "Content-Type", "application/json" );
xhttp.send(JSON.stringify(checkbox));
}
</script>
<html>
<body>
<form>
<?php
for ($i=0; $i<10; $i++){
echo "$i: ";
echo "<input type='checkbox' name='checkbox[".$i."]'></input><br>";
}
?>
<button type="button" name="button" onclick="activate(checkbox)" >Test</button>
</form>
<p>ajaxState: <span id="ajaxState"></span></p>
<p>ajaxStatus: <span id="ajaxStatus"></span></p>
<p>ajaxResponse: <span id="ajaxResponse"></span></p>
</body>
</html>
Output: Don't get any response.
process.php: decode json data and display the array
<?php
$data = file_get_contents( "php://input" );
$checkbox = json_decode( $data, true );
echo "Hello!<br>";
var_dump($checkbox);
?>
NOTE: If, in the button element, I use this.checkbox, var_dump returns NULL.
<button type="button" name="button" onclick="activate(this.checkbox)" >Test</button>
Response:
ajaxState: 4
ajaxStatus: 200
ajaxResponse: Hello!
NULL
Check the below code...
<!DOCTYPE html>
<script language="javascript">
function activate(){
/*getting all inputs*/
var inputs = document.getElementsByTagName("input");
var cbs = []; //will contain all checkboxes
var checked = []; //will contain all checked checkboxes
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
cbs.push(inputs[i]);
if (inputs[i].checked) {
checked.push(inputs[i]);
}
}
}
//then making a request
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
document.getElementById("ajaxState").innerHTML =xhttp.readyState;
document.getElementById("ajaxStatus").innerHTML =xhttp.status;
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("ajaxResponse").innerHTML = xhttp.responseText;
}
};
console.log(xhttp);
xhttp.open("POST", "process.php", true);
xhttp.setRequestHeader( "Content-Type", "application/json" );
xhttp.send(JSON.stringify(checked));//sending checked instead of checkbox
}
</script>
<html>
<body>
<form>
<?php
for ($i=0; $i<10; $i++){
echo "$i: ";
echo "<input type='checkbox' name='checkbox[".$i."]'></input><br>";
}
?>
<button type="button" name="button" onclick="activate()" >Test</button>
</form>
<p>ajaxState: <span id="ajaxState"></span></p>
<p>ajaxStatus: <span id="ajaxStatus"></span></p>
<p>ajaxResponse: <span id="ajaxResponse"></span></p>
</body>
</html>
used this to get all checkboxes
Better use Query see jQuery - AJAX
Here realization "Click on button and show id current button in ajax, for use in second needed tasks". If I right anderstand you.
{{--include jQuery CDN Library--}}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<button type="button" name="1" id="test" >Test</button>
<button type="button" name="2" id="test" >Test</button>
<button type="button" name="3" id="test" >Test</button>
...
<style>
$("button#test").change(function(){
var id = $(this).attr('name');
$.ajax({
method: 'POST',
url: 'process.php',
data: {id: id}
})
.done(function(msg){
console.log('button: ' + msg);
});
});
</style>
And php file
<?php
$data = $_POST['id']
$checkbox = json_encode($data);
echo "Hello!<br>";
echo $data; // show id checkbox
?>
It is simpler realization codes, from same javascript codes

How to retain the values displayed in the HTML after it is fetch from the PHP?

I have an HTML page that takes the user input and displays the output based on the database. I have a hyperlink to the other pages. I want when I navigate from first page to other HTML page, I add a back button and it shoud return to the first page but it should show the fetched values. Here is the code below.
1st HTML:
<script>
function PostData() {
var online = navigator.onLine;
if(online){
// 1. Create XHR instance - Start
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
// 1. Create XHR instance - End
// 2. Define what to do when XHR feed you the response from the server - Start
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
document.getElementById('div1').innerHTML = xhr.responseText;
}
}
}
// 2. Define what to do when XHR feed you the response from the server - Start
var userid = document.getElementById("userid").value;
var pid = document.getElementById("pid").value;
// var image = document.getElementById("image").value;
// 3. Specify your action, location and Send to the server - Start
xhr.open('POST', 'login3.php');
//xhr.open('POST', 'config.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("userid=" + userid + "&pid=" + pid);
//xhr.send("&pid=" + pid);
// 3. Specify your action, location and Send to the server - End
}
else{
alert("You are offline");
}
}
</script>
</head>
<body>
<form>
<label for="userid">User ID :</label><br/>
<input type="text" name ="userid" id="userid" /><br/>
<label for="pid">Password :</label><br/>
<input type="password" name="password" id="pid" /><br><br/>
<div id="div1">
<input type="button" value ="Login" onClick="PostData()" />
</div>
</form>
</body>
PHP:
<?php
if(isset($_POST['userid'],$_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM demo WHERE username = '$userid' and password = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo $row['week'].'<br/>'.'<br/>';
echo '<a href="2ndHTML.html"/>'.$row['day1'].'</a>'.'<br/>';
?>
2nd HTML:
<body>
<form enctype="multipart/form-data" id="form" action="" method="post">
<input type="file" id="imageid" name="image" onchange="readURL();" />
<img id="blah" src="#" alt="your image" /><br/><br/>
<input type="button" value="upload" onclick="javascript:uploadInage();" />
BACK
</form>
</body>
I want to retain the values fetched on the 1stHTML.html
It's best to use session. Once the user has completed the first form set a session to signal that, so when they return to the first page it will read the session and automatically redirect them to the necessary page.
You'll need to put this at the top of your 1sthtml.php and 2ndhtml.php page to signal that you want to use sessions:
<?php
session_start();
On your 1sthtml.php page you'll need to set the session information:
<?php
if(isset($_POST['userid'],$_POST['pid']))
{
$userid = trim($_POST["userid"]);
$pid = trim($_POST["pid"]);
$sql = "SELECT * FROM demo WHERE username = '$userid' and password = '$pid'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
echo $row['week'].'<br/>'.'<br/>';
echo '<a href="2ndHTML.html"/>'.$row['day1'].'</a>'.'<br/>';
// ---- SET SESSION HERE ---
$_SESSION['stage'] = 1;
}
?>
And then, on the 1sthtml.php again you'll need to check to see if that session variable exists, if it does then forward onto the page you want. So, at the top of your 1sthtml.php, next to your previous session_start():
<?php
session_start();
if (isset($_SESSION['stage'])) {
header('Location: 2ndhtml.php');
exit();
}

upload image with ajax and pass muti parameter

i'm having trouble uploading image with other input text form and send to ajax_php_file.php. But only image is uploaded, my input text is all empty. Would appreciate if anyone can assist here. Thanks alot.
<div id="imagebox">
<div class="image_preview">
<div class="wrap">
<img id="previewing" />
</div>
<!-- loader.gif -->
</div><!--wrap-->
<!-- simple file uploading form -->
<form id="uploadimage" method="post" enctype="multipart/form-data">
<input id="file" type="file" name="file" /><br>
<div id="imageformats">
Valid formats: jpeg, gif, png, Max upload: 1mb
</div> <br>
Name:
<input id="name" type="text"/>
<input id="cat" type="hidden" value="company"/>
Description
<textarea id="description" rows="7" cols="42" ></textarea>
Keywords: <input id="keyword" type="text" placeholder="3 Maximum Keywords"/>
<input type="submit" value="Upload" class="pre" style="float:left;"/>
</form>
</div>
<div id="message">
</div>
script.js
$(document).ready(function (e) {
$("#uploadimage").on('submit',(function(e) {
e.preventDefault();
$("#message").empty();
$('#loading').show();
var name = document.getElementById("name").value;
var desc = document.getElementById("description").value;
var key = document.getElementById("keyword").value;
var cat = document.getElementById("cat").value;
var myData = 'content_ca='+ cat + '&content_desc='+desc+ '&content_key='+key+ '&content_name='+name;
$.ajax({
url: "ajax_php_file.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this,myData), // Data sent to server, a set of key/value pairs representing form fields and values
//data:myData,
contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
success: function(data) // A function to be called if request succeeds
{
$('#loading').hide();
$("#message").html(data);
}
});
}));
// Function to preview image
$(function() {
$("#file").change(function() {
$("#message").empty(); // To remove the previous error message
var file = this.files[0];
var imagefile = file.type;
var match= ["image/jpeg","image/png","image/jpg"];
if(!((imagefile==match[0]) || (imagefile==match[1]) || (imagefile==match[2])))
{
$('#previewing').attr('src','noimage.png');
$("#message").html("<p id='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>");
return false;
}
else
{
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
function imageIsLoaded(e) {
$("#file").css("color","green");
$('#image_preview').css("display", "block");
$('#previewing').attr('src', e.target.result);
$('#previewing').attr('width', '250px');
$('#previewing').attr('height', '230px');
};
});
ajax_php_file.php
<?php
session_start();
$user_signup = $_SESSION['user_signup'];
if(isset($_FILES["file"]["type"]))
{
$name = filter_var($_POST["content_name"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$ca = filter_var($_POST["content_ca"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$desc = filter_var($_POST["content_desc"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$key = filter_var($_POST["content_key"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
$imagedata = addslashes(file_get_contents($_FILES['file']['tmp_name']));
$imagename= ($_FILES['file']['name']);
$imagetype =($_FILES['file']['type']);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 1000000)//Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
}
else
{
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "upload/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
mysql_query("INSERT INTO upload(name,picname,image,type,email,cat,description,keyword) VALUES('".$name."','".$imagename."','".$imagedata."','".$imagetype."','".$user_signup."','".$ca."','".$desc."','".$key."')");
}
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}
?>
the format of the formData maybe incorrect. Change it like the following:
var myData = {'content_ca':cat,
'content_desc':desc
}
i think you are using jquery
So you can use
data:$("#uploadimage").serialize(),

How do I POST multiple form data to PHP

I am trying to send data from a form into a php for it then to write it into a html, without loading into onto php file page. The var_dump shows the data is ready, it somehow just doesn't want to pass over to the php...
<!DOCTYPE html>
<html lang="en">
<head>
<title>TEST</title>
<meta charset="UTF-8" content="bla bla bla">
<script type="text/javascript" src="jquery-2.1.1.min.js"></script>
<script type="text/javascript" language="javascript">$(function(){$('body').on('click', 'input.sumbit', function(){gogosend();});});</script>
</head>
<body>
<form method="post">
<ul class="form">
<li class="short">
<label>First Name<span class="required"></span></label>
<input type="text" name="first" id="first"/>
</li>
<li class="short">
<label>Last Name<span class="required"></span></label>
<input type="text" name="last" id="last" />
</li>
<li class="long">
<label>Email Address<span class="required"></span></label>
<input type="text" name="email" id="email"/>
</li>
<li class="short">
<label>Company Name</label>
<input type="text" name="company" id="company"/>
</li>
<li class="short">
<label>Telephone Number</label>
<input type="text" name="phone" id="phone" />
</li>
<li class="textarea">
<label>Message<span class="required"></span></label>
<textarea name="message" id="message" rows="20" cols="30"></textarea>
</li>
<li class="button">
<input class="sumbit" name="sumbit" id="sumbit" value="Submit" type="submit" />
</li>
</form>
<script>
function gogosend()
{
var dfirs = document.getElementById("first").value;
var dlast = document.getElementById("last").value;
var demai = document.getElementById("email").value;
var dcomp = document.getElementById("company").value;
var dphon = document.getElementById("phone").value;
var dmess = document.getElementById("message").value;
alert(dfirs);
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data_first = "first=" +dfirs ;
var data_last = "last=" +dlast ;
var data_email = "email=" +demai ;
var data_company = "company=" +dcomp ;
var data_phone = "phone=" +dphon ;
var data_message = "message=" +dmess ;
alert(data_first);
xhr.open("POST", "mailer.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data_first);
xhr.send(data_last);
xhr.send(data_email);
xhr.send(data_company);
xhr.send(data_phone);
xhr.send(data_message);
}
</script>
<?php
var_dump($_POST);
echo "</br>";
?>
</body>
</html>
And here is the php file code :
<?php
$first = $_POST["first"];
$last = $_POST["last"];
$email = $_POST["email"];
$company = $_POST["company"];
$phone = $_POST["phone"];
$message = $_POST["message"];
$text = "NAME: $first $last <br>
EMAIL: $email<br>
COMPANY: $company<br>
TELEPHONE NUMBER: $phone<br>
MESSAGE: $message<br><hr><br><br><br>";
$file = fopen("contactrequests.html","a+");
fwrite($file, $text);
fclose($file);
?>
How do I rewrite the above for it to work ? For example now it gives me the var_dump for random data that I entered :
array (size=7)
'first' => string '24' (length=2)
'last' => string '225' (length=3)
'email' => string '25g2' (length=4)
'company' => string '2d5' (length=3)
'phone' => string '2d5' (length=3)
'message' => string '2d5' (length=3)
'sumbit' => string 'Submit' (length=6)
I tried How to pass multiple values from ajax to php file But that did not help.
I would suggest sending a JSON object extracted from your form to be accessed by the PHP script... In the PHP script create a PHP class instance or an indexed array from this JSON using this function http://php.net/manual/en/function.json-decode.php
To serialize form to a JSON in javascript client side you can use this http://api.jquery.com/serializearray/
And if I might give an advice, skip using xhr directly... use the jQuery ajax wrapper... it will ensure running on all major browsers the same way without hassle
You just need to format those data according to application/x-www-form-urlencoded.
function gogosend()
{
var dfirs = document.getElementById("first").value;
var dlast = document.getElementById("last").value;
var demai = document.getElementById("email").value;
var dcomp = document.getElementById("company").value;
var dphon = document.getElementById("phone").value;
var dmess = document.getElementById("message").value;
alert(dfirs);
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data_first = "first=" +dfirs ;
var data_last = "last=" +dlast ;
var data_email = "email=" +demai ;
var data_company = "company=" +dcomp ;
var data_phone = "phone=" +dphon ;
var data_message = "message=" +dmess ;
var data = ([data_first, data_last, data_email, data_company, data_phone, data_message]).join('&');
alert(data_first);
xhr.open("POST", "mailer.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", data.length);
xhr.send(data);
}
As easy as add a return false; to your gogosend function
( the form submission requires a return false; at the end to stay on the page, btw the data is allready submitted to mailer.php )
VoilĂ  :)

Categories

Resources