Cant parse JSON with JavaScript and Ajax - javascript

Ive got an PHP which creates a .json file:
<?php
$data=array( "Name"=>"Someone", "Surname" => "Somebody");
$jsontext = "[";
foreach($data as $key => $value) {
$jsontext .= "{objectValue: '".addslashes($key)."', textObject: '".addslashes($value)."'},";
}
$jsontext = substr_replace($jsontext, '', -1);
$jsontext .= "]";
echo $jsontext;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($jsontext));
fclose($fp);
?>
This is the results.json:
"[{objectValue: 'Name', textObject: 'Someone'},{objectValue: 'Surname', textObject: 'Somebody'}]"
The javascript:
var xmlHttp = createXmlHttpRequestObject();
var finalText;
window.onload = process;
function createXmlHttpRequestObject() {
var xmlHttp;
if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlHttp = false;
}
} else {
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
xmlHttp = false;
}
}
if (!xmlHttp) {
alert("Cant create XmlHTTP...");
} else {
return xmlHttp;
}
}
function process() {
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
xmlHttp.open("GET", "http://localhost/results.json", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} else {
//setTimeout('process()', 1000);
alert("Error: Server is busy");
}
}
function handleServerResponse() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
finalText = xmlHttp.responseText;
}else{
//alert("Error: server is busy");
}
}
function convertJSON(){
parsedText = JSON.parse(finalText);
alert(parsedText); //This shows the parsed text, it gets here
document.getElementById('finalResult').innerHTML += parsedText.objectValue;
document.getElementById('finalResult').innerHTML += parsedText.Name;
}
Whenever I summon convertJSON from a button onclick I keep getting undefined, when printing the results into the "finalResult" div... what am I doing wrong?

You're building your JSON by string concatenation, then sending it into json_encode. Instead build your JSON as an array:
$jsonData = array();
foreach($data as $key => $value) {
$jsonData[] = array('objectValue' => $key, 'textObject' => $value);
}
$jsontext = json_encode($jsonData);
echo $jsontext;
fwrite($fp, $jsontext);

You need to use valid JSON, strings are always surrounded with double-quotes and object keys are also surrounded by double-quotes. So your JSON string that is served up by PHP should read as follows:
[{"objectValue":"Name","textObject":"Someone"},{"objectValue":"Surname","textObject":"Somebody"}]
There's a good online reference for JSON structure that you might want to give a read.

Related

I need to send a request through JS to a php file via API

Help me please. There are two php files Data.php and Status.php. When you enter data in the zip field, you need to send a request to the Data.php file, and if zip is available, send the data to Status.phpenter code here and parse the response in the field.Below I will give a js example and Data.php, Status.php
I will be grateful for the help)
function ajax(params) {
var xhr = new XMLHttpRequest();
var url = params.url || '';
var body = params.body || '';
var success = params.success;
var error = params.error;
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(body);
xhr.onload = function () {
if (xhr.readyState === 4 && xhr.status === 200 && typeof success === 'function') {
success(xhr.response);
} else if (xhr.readyState === 4 && xhr.status !== 200 && typeof error === 'function') {
error(xhr.response);
}
};
xhr.onerror = error || null;
}
//Data.php
<?php
header('Content-Type: application/x-www-form-urlencoded');
header('Access-Control-Allow-Origin: *');
if (isset($_POST['zip'])) {
$zip = filter_var($_POST['zip'], FILTER_VALIDATE_REGEXP, array('options'=>array('regexp'=>'/^[0-9]{5}/')));
if ($zip) {
$status = (int) $zip < 33333 ? array('zip' => $zip, 'state' => 'OH', 'city' => 'NEWTON FALLS') : array('zip' => $zip, 'state' => 'CA', 'city' => 'BEVERLY HILLS');
echo json_encode($status);
} else {
echo 'error';
}
} else {
echo 'error';
}
//Status.php
<?php
header('Content-Type: application/x-www-form-urlencoded');
header('Access-Control-Allow-Origin: *');
if (isset($_POST['zip'])) {
$zip = filter_var($_POST['zip'], FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => '/^[0-9]{5}/')));
if ($zip) {
$status = (int) $zip < 33333 ? 'allowed' : 'blocked';
echo $status;
} else {
echo 'error';
}
} else {
echo 'error';
}
You need to send an AJAX call from the first php to second php.
Include following script inside first php file.
test1.php
<?php
// other content
<script>
(function() {
var httpRequest;
document.getElementById("ajaxButton").addEventListener('click', makeRequest);
function makeRequest() {
httpRequest = new XMLHttpRequest();
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('GET', 'test2.php');
httpRequest.send();
}
function alertContents() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText); // your response
} else {
alert('There was a problem with the request.');
}
}
}
})();
</script>
?>
Then return your content data from the next php file as follows.
test2.php
<?php
$x = "content data";
echo $x;
?>
For more details about AJAX, follow below link
https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started
javaScript Code
const data = { name: 'scott' }; // data for post
fetch('url', {
method: 'POST',
headers: {
'Content-Type': 'application/json', // type
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch((error) => {
console.error(error);
});

Cannot get data passed to a php file using AJAX

I am trying to pass data back to the server and then use the reply to update the browser page.
My code for a SELECT input is as follows;
<select id ="MatchCaptain" name="MatchCaptain" onchange="findTeleNo(this.value)"
<?php
$MC = $_SESSION["MatchCapt"];
player_load($MC);
?>
>
</select>
The script code is as follows;
<script>
function findTeleNo(that){
alert("I am an alert box!" + that);
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("TeleNo").value = this.responseText;
}
}
};
xhttp.open("GET", "findTeleNo.php?q=" + that, true);
xhttp.send();
</script>
The purpose of the script is to take the value selected in the dropdown (variable "that") and submit it to the php file as variable q.
And the PHP file is as follows;
<?php
$MatchCaptain = $_REQUEST["q"];
$teleNo = "";
$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementDB";
$db_found = mysqli_select_db($db_handle, $database);
if ($db_found) {
$SQL = "SELECT * FROM `playerstb` ORDER BY `Surname` ASC, `FirstName` ASC";
$result = mysqli_query($db_handle, $SQL);
$ufullName = split_name($MatchCaptain);
while ( $db_field = mysqli_fetch_assoc($result) ) {
$uName = $db_field['FirstName'];
$uName = trim($uName);
$Surname = $db_field['Surname'];
$Surname = trim($Surname);
$fullName = $uName." ".$Surname;
if ($fullName == $ufullName )
{
$teleNo = $db_field['TeleNo'];
break;
}
}
}
echo $teleNo;
function split_name($name) {
$name = trim($name);
$last_name = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name);
$first_name = trim( preg_replace('#'.$last_name.'#', '', $name ) );
$ufullName = $first_name." ".$last_name;
return $ufullName;
}
?>
The php file requests the q variable from the url and makes it $MatchCaptain.
This will be a name like Joe Bloggs. The next piece of code connects to a MySQL table to extract players first names surnames and telephone numbers. The first names and surnames are concatenated to form the fullname which is compared with the $MatchCaptainWhen a match is made the variable $teleNo is set to the Telephone Number of that player. The echo statement rerurns the value to the script.
The field id I am trying to update is;
<p><b>Telephone Number: </b> <span id="TeleNo"> <?php echo $_SESSION["TeleNo"]; ?></span></p>
The alert in the script function findTeleNo shows me that I have entered the function but nothing happens after that.
Any help as to how I get this working would be grateful.
I have changed my script to
<script>
function findTeleNo(that){
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "findTeleNo.php?q=" + encodeURIComponent(that), true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
// OK
alert('response:'+xhttp.responseText);
document.getElementById("TeleNo").innerHTML = this.responseText;
// here you can use the result (cli.responseText)
} else {
// not OK
alert('failure!');
}
}
};
};
</script>
The response shown by alert('response:'+xhttp.responseText); is correct and the line of code
document.getElementById("TeleNo").innerHTML = this.responseText;
does print the response to the web page.

Live Search Using Ajax and PHP mysql

I created a Live Search using AJAX,PHP and mysql.here when I click on search result ,redirecting me to a particular page it works perfectly. Now I need a small change.
All I need is:
When I click on the search result, that particular result should be display in the input field.
Here is my AJAX code:
<script type="text/javascript">
END OF AJAX CODE
PHP CODE
<?php
ob_start();
session_start();
include("Base.php");
$dbase=new Base();
#$userID=$_SESSION['userID'];
$createdDate=date("Y-m-d");
$createdTime=date("h:i:s A");
$partialStates=mysql_escape_string($_REQUEST['q']);
$qryy="SELECT * from `gon_pro` WHERE `pro_name` LIKE
'%$partialStates%' ";
$pser=$dbase->execute($qryy);
$ser_nums=mysqli_num_rows($pser);
while($co[]=mysqli_fetch_array($pser)){
}
?>
<?php
foreach ($co as $key => $namo) {
$cv=$namo['pro_name'];
$cv_id=$namo['id'];
$cv_p=$namo['price'];
?>
<a href="pro_det.php?prolod=<?php echo $cv_id; ?>"><p class="res
col-md-6"><?php echo $cv; ?></p></a>
<?php
}
?>
END OF PHP CODE
function getStates(str) {
if (str.length == 0) {
document.getElementById("row").innerHTML = "";
document.getElementById("results").innerHTML =""
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("results").innerHTML =
xmlhttp.responseText;
}
};
xmlhttp.open("GET", "support/getStates.php?q=" + str, true);
xmlhttp.send();
}
}
</script>

I am trying to fetch image from database using ajax in php

here's my code i am trying to fetch image from Data Base using ajax but its not working please hep me out . image uploading working properly when i am trying to fetch image using anchor tag but it show my image on another page . but i want on same page at window load time.
getImage.php
if(filter_has_var(INPUT_GET, "image_id") !== false && filter_input(INPUT_GET, 'image_id', FILTER_VALIDATE_INT) !== false)
{
$image_id = filter_input(INPUT_GET, "image_id", FILTER_SANITIZE_NUMBER_INT);
try {
$dbh = new PDO("mysql:host=localhost;dbname=flipbook", 'root', '');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT image, image_type FROM testblob WHERE user_id=$image_id";
/*** prepare the sql ***/
$stmt = $dbh->prepare($sql);
$stmt->execute();
/*** set the fetch mode to associative array ***/
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$array = $stmt->fetch();
if(sizeof($array) == 2)
{
header("Content-type: ".$array['image_type']);
echo $array['image'];
}
else
{
throw new Exception("Out of bounds Error");
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
catch(Exception $e)
{
echo $e->getMessage();
}
}
else
{
echo 'Please use a real id number';
}
}
index.php
<body onload="showUserProfilePic(<?php echo $_SESSION['current_user_id'];?>)">
<div id="txtHint">Child Picture will be listed here.</div>
<script>
function showUserProfilePic(str) {
//alert(str);
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getImage.php?image_id="+str,true);
xmlhttp.send();
}
}
Try using
$sql = "SELECT image, image_type FROM testblob WHERE user_id='" . $image_id . "';
and where is your tag?

PHP not receiving JSON from Ajax post

I am trying to send some JSON to a PHP processing code via Ajax. Here is my JavaScript:
var j = {"a":"b"};
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
};
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
console.log(xmlhttp.responseText)
};
};
xmlhttp.open("POST", "server.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xmlhttp.send({
"json": j
});
And the PHP:
$json = $_POST["json"];
echo $json;
But this echoes null. What have I done wrong? This seems like it should work. Thanks!
Please no jQuery. And if you vote down, please tell me why so I can improve.
Your j variable is a object. You need to encode this into a json string before you post it.
Okay I have re-written my answer from scratch.
Update your server.php like this:
<?php
// Request Handler
if (count($_POST))
{
$json = isset($_POST['json']) ? $_POST['json'] : '';
if (!empty($json))
{
$jsonObj = json_decode($json);
print_r($jsonObj);
}
else
{
echo "No json string detected";
}
exit();
}
?>
Change your ajax request like this:
<script type="text/javascript">
var j = {"a":"b"};
var xmlHttp = new XMLHttpRequest();
var parameters = "json="+ encodeURIComponent(JSON.stringify(j));
xmlHttp.open("POST", "server.php", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", parameters.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
console.log(xmlHttp.responseText);
}
}
xmlHttp.send(parameters)
</script>
Here's a demo of it working:
So, in the PHP script, I am printing the $jsonObj and it's contents. If you want to use it in your script; you'd do this:
e.g.
<?php
if ($jsonObj->a == 'b') {
// do something ?
}
?>
If you want an associative array to work with (instead of an object), you can do this:
Change: $jsonObj = json_decode($json); To: $jsonObj = json_decode($json, true);
Now you can do this:
<?php
if ($jsonObj['a'] == 'b') {
// do something ?
}
?>
Javascipt :
encode en JSON with JSON.stringify(j);
if j contain & in string and not a separator de data :
j.split("&").join("%26");
in php
$json = $_REQUEST['json'];
$json = str_replace("%26","&",$jsonData);
$json = html_entity_decode($json,ENT_NOQUOTES,'UTF-8');
$data = json_decode($json,true);
the value of json as array of data.
To submit JSON properly, it'd be:
xmlhttp.send(JSON.stringify({"json": j});
Then for the PHP:
$json = json_decode(file_get_contents('php://input'));
The problem is that when sending JSON (if it's a proper JSON request), PHP won't automatically parse it.

Categories