Passing JSON object from php to JS via Ajax - php

I am trying to pass a JSON object from a php script to a Javascript file with Ajax. The code below worked for a simple string, but I am now trying to amend it to work with multiple strings contained within a JSON object. I have pasted extracts of each file below. What am I doing wrong?
This is a extract from the html/javascript file which is creating the request...
function retrieveAircraftInfo(str) {
var xmlhttp;
if (str.length==0) {
document.aircraftRegForm.aircraftManufacturer.value="";
return;
}
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) {
var aircraftDataJSON = xmlhttp.responseText.evalJSON();
document.aircraftRegForm.aircraftManufacturer.value = aircraftDataJSON.manufacuter;
document.aircraftRegForm.aircraftType.value = aircraftDataJSON.type;
document.aircraftRegForm.aircraftPopularName.value = aircraftDataJSON.popularName;
document.aircraftRegForm.aircraftGenericName.value = aircraftDataJSON.genericName;
}
}
xmlhttp.open("GET","scraper.php?q="+str,true);
xmlhttp.send();
}
This is an extract from the php file which is doing the database search:
$aircraftDataArray = array("manufacturer" => $extractedManufacturer,
"type" => $extractedType,
"popularName" => $extractedPopularName,
"genericName" => $extractedGenericName);
echo json_encode($aircraftDataArray);

Try
var aircraftDataJSON = JSON.parse(xmlhttp.response);
Otherwise, check in the console of the developer tools if PHP returns some error.
Your JS example worked for me with JSON.parse

Related

Sending value, get nothing

I created ajax function which sends data to php file but something is wrong because when i die it, it holds nothing, and i know that my ajax function was written good. Here is how am i sending it:
xmlhttp.send(dop);
And here is how i recieve it in php file:
$selectedLang = isset($_POST['dop']) ? $_POST['dop'] : '';
What am i doing wrong? I'am probably recieving info badly. Coz i can see that parameteres are good in ajax function. Please help, really need fast.
<script type="text/javascript">
function run()
{
var dop = document.getElementById("kalba").value;
return dop;
}
function insertData()
{
var dop = run();
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","style/wps-light/datafile.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("Reiksme=" + encodeURIComponent(dop));
}
</script>
datafile.php:
<?php
$selectedLang = isset($_POST['dop']) ? $_POST['dop'] : '';
die("Viskas ok $selectedLang");
?>
You need to get it like that:
$selectedLang = isset($_POST['Reiksme']) ? $_POST['Reiksme'] : '';
Because Reiksme is the key in $_POST array, not dop:
xmlhttp.send("Reiksme=" + encodeURIComponent(dop));
^^^^^^^

Second AJAX call unloading result of the first

Code below is run in the onLoad event of the page. I first would like to populate a drop down menu with getCompany() and then fill in data from the server into text boxes and choose the selected option.
Both functions work, in fact when I reload the page with debugger running and step into everything both do what they are supposed to.
When I just open the page or reload with out debugger the text boxes are filled but the options disappear from the dropdown, why is that?
<script>
var result;
function init(){
var name = window.name;
name = name.split(",");
getCompany();
setTimeout(200);
if (name[0] = "update"){
id = name[1];
getTenant(id);
//get the info for the line that called the edit function
//fill fields with information from server
}
}
function getCompany() {
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 x() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("company").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getCompany.php",true);
xmlhttp.send();
}
function getTenant(id){
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 y() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
result = xmlhttp.responseText;
result = result.split(",");
//fill the form with old information
document.getElementById("fname").value = result[0];
document.getElementById("lname").value = result[1];
document.getElementById("company").selectedIndex = result[2];
document.getElementById("phone").value = result[3];
document.getElementById("email").value = result[4];
document.getElementById("crm").value = result[5];
}
}
xmlhttp.open("GET","getTenant.php?p=" + id,true);
xmlhttp.send();
}
</script>
I assume the input fields you are filling in data in the second request belong to the data fetched from the first request. I also assume you are using the setTimeout() to delay the 2nd request...
Javascripts are single threaded. To provide asynchronous behavior js uses callback mechanism. After sending a request to the server, js doesn't wait until the response comes. JS keeps executing the rest of code until the results from the server comes. When the response comes from the server the code in the callback function xmlhttp.onreadystatechange is executed. Because of that, both requests may happen at almost the same time and consequently the response for the 2nd request may come before the first response which leads the behavior you see as an error.
When you debug, you execute line by line. Therefore there is enough time to get the response for the first request before getting the response for the second request.
As a solution you can move the code for the second request inside the xmlhttp.onreadystatechange callback in the code for the first request. Then as the callback is always executed after the results are fetched, the second request is sent after the response for the first one comes.
You may google about asynchronous javascript and learn in details...
<script>
var result;
function init(){
var name = window.name;
name = name.split(",");
getCompany(name);
}
function getCompany(name) {
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 x() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("company").innerHTML = xmlhttp.responseText;
if (name[0] == "update"){
id = name[1];
getTenant(id);
//get the info for the line that called the edit function
//fill fields with information from server
}
}
}
xmlhttp.open("GET","getCompany.php",true);
xmlhttp.send();
}
function getTenant(id){
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 y() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
result = xmlhttp.responseText;
result = result.split(",");
//fill the form with old information
document.getElementById("fname").value = result[0];
document.getElementById("lname").value = result[1];
document.getElementById("company").selectedIndex = result[2];
document.getElementById("phone").value = result[3];
document.getElementById("email").value = result[4];
document.getElementById("crm").value = result[5];
}
}
xmlhttp.open("GET","getTenant.php?p=" + id,true);
xmlhttp.send();
}
</script>
It is happening because of a race condition between the two XHR calls made from getCompany and getTenant methods. Even though you are making the getTenant call 200ms after making the first XHR call there is no guarantee that the getComapny XHR call will finish first. When that happens the follwoing line of code
document.getElementById("company").innerHTML = xmlhttp.responseText;
removes all the options from the menu and also resets the selected index. To circumvent this issue do not make getTenant(id); call from init method. Instead make it from the success handler of the getCompany XHR call.
xmlhttp.onreadystatechange=function x() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("company").innerHTML = xmlhttp.responseText;
**getTenant(id);**
}
}
Make two different object name instead of one (xmlhttp). Like
in 'getCompany()' function object name is 'xmlhttp'
in 'getTenant()' function changed object name to 'xmlTalenthttp' (or any other name which you wish)

send POST with httprequest to php

I want to send a random number to an xml-file with http request and php.
But i cant really figure out how to add the value of the generated number and add it to the post.
This is what i have so far.
var x=document.getElementsByClassName("demo");
x[x.length-1].innerHTML=Math.floor((Math.random()*1000000)+1);
// Generates a random number and print it on the last demo class
var xmlhttp;
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/project3/php/update.php",true); //Calls the php update file
xmlhttp.send();
PHP file
<?php
$dom = new DOMDocument();
$dom->load('../stickers.xml');
$stickers = $dom->documentElement;
$xpath = new DOMXPath($dom);
$result = $xpath->query('/stickers/sticker[id="$POST"]/id'); //Not sure.
$result->item(0)->nodeValue .= 'hi';
echo $dom->saveXML();
$dom->save('../stickers.xml');
?>
The get method sends parameters as a query string in the URL, whereas the post query string is sent within the http headers:
xmlhttp.open("POST","/project3/php/update.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("random="+x[x.length-1].innerHTML);
On the PHP side of things, posts variables are added to a global associative array like so:
<?php echo $_POST['random'];

ajax and portable OSes

Well, i have an select list in my php page and i want to refresh only that with new data from my database.Idone it using ajax but on android or other mobiles OSes this messes up the layout.Is there a problem with protable OSes and ajax?Can you give me any hints to solve this problem?
Edited
/*function loadXMLDoc()
{
var xmlhttp;
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)
{
var sel1 = document.getElementById("select1");
var selectedI = sel1.selectedIndex;
var i=0;
var excode = excur[selectedI];
var val = sel1.options[selectedI];
excursioncode=excode;
excindex = selectedI;
val.innerHTML = xmlhttp.responseText;
//alert(xmlhttp.responseText);
//setTimeout("loadXMLDoc();",10000);
}
}
xmlhttp.open("POST","<?php echo SITE_ROOT;?>ajaxphp/ajax_get_seats.php?excode="+excursioncode+"&date="+selected_date,true);
xmlhttp.send();
}
function timedRefresh(timeoutPeriod) {
tm=setTimeout("loadXMLDoc();",timeoutPeriod);
}
*/
This is some code that is doing the job.On a regular pc is working but on a mobile browser brings up problems.Anyu ideas
If the problem were with the AJAX, it would not be causing layout issues. Instead the problem is most likely with your implementation of using the data retrieved by AJAX. However, I can't provide any more insights because I have no clue what you're working on and have never experienced such a problem.

Onbeforeunload - popux box will not display or trigger

I am building a website with user-profiles. I am at the picture part at the moment. When a person upload their image with no problem, the picture will be stored in 4 different folders. One for size 25, 100, 150 and normal size. After this they will be redirected to the same page, with new content. This is the part, where they need to crop their picture. Crop part works great, but I have a problem. When they leave the site without cropping, the pciture they just uploaded is still stored in the folders, and that's not what i want. So i mate some checks with AJAX, and it will unlink the 4 files sotred already. My problem is, that this shall only happen, when they leave the site(onbeforeunload.)
This works very great in IE, but not in Chrome.(Only two browsers i've tested yet.)
Here is what I'm doing:
function unfinished(album,img){
var xmlhttp;
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) {
return xmlhttp.responseText;
}
}
xmlhttp.open("GET","incl/unfinished.php?a=" + album + "&i=" + img,true);
xmlhttp.send();
}
The function above get information from "uncl/unfinished.php" by the query string. And it all works well.
Code on unfinished.php:
session_start();
require('../dbconnect.php');
$sql = "SELECT * FROM users WHERE username='".$_SESSION['username']."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
$username= $row['brugernavn'];
}
$album = $_GET['a'];
$img = $_GET['i'];
$sourcex = "../users/".$username."/images/".$album."/x-x/".$img;
$source25 = "../users/".$username."/images/".$album."/25/".$img;
$source100 = "../users/".$username."/images/".$album."/100/".$img;
$source150 = "../users/".$username."/images/".$album."/150/".$img;
if(unlink($sourcex)){
}
if(unlink($source25)){
}
if(unlink($source100)){
}
if(unlink($source150)){
}
echo "Error 908. The picture didn't get cropped, and neither saved. Try again.";
The AJAX code and unfinished.php deletes the images withpout any problems. I've tested that already. Now my problem:
I am running the AJAX code by
The code should be running inside this:
//function warn(album,img){
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = unfinished(album,img);
}
// For Safari
return unfinished(album,img);
};
//}
But when i try to return xmlhttp.responseText, the popup box doesn't popup, and i am not able to see the response.
But if i add "Hello world"(or some text) to the return like return Helloworld!''; or e.returnValue = 'Hello world!';, instead of the xmlhttp.responseText value, it pops up, and display the message. But it doesn't display the xmlhttp.responseText, because it doesn't run the unfinished() function.
any solutions how i can run the AJAX when user leaves page?
If it helps here is the HTML code:
if($_POST['where'] == "newalbum"){
$nameonalbum = $_POST['nameonalbum'];
}else{
$nameonalbum = $_POST['existingalbum'];
}
$filenamenew=time().'.gif';
?>
<body onload="warn('<?=$nameonalbum?>','<?=$filenamenew?>')">
Solved it by myself. Did like this:
function unfinished(album,img){
window.onbeforeunload = function (e) {
e = e || window.event;
var response = '';
var xmlhttp;
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){
response = xmlhttp.responseText;
}
}
xmlhttp.open("GET","incl/unfinished.php?a=" + album + "&i=" + img,true);
xmlhttp.send();
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = response;
}
// For Safari
return response;
}
}
But now i have another problem... 1st of all the unload function works great, but I don't want it to trigger when the "Save crop" button is clicked. Any ideas how to do this?
Save button html:

Categories