PHP AJAX response in XML string - php

I have a web page that is making an AJAX call which echoes a XML string in below format:
<ECG>Abnormal</ECG><SP>10.99</SP><BP>120/90</BP><OXY>139</OXY><TMP>23</TMP>
AJAX call
$.ajax({
type:'post',
url: 'check_status.php',
dataType: 'xml',
success: function(xml) {
var ecg = $(xml).find("ECG").text();
var sp = $(xml).find("SP").text();
var bp = $(xml).find("BP").text();
var oxy = $(xml).find("OXY").text();
var tmp = $(xml).find("TMP").text();
alert(tmp);
},
error: function(){
alert('Error');
update();
}
});
The XML response is simply created by PHP backend script by constructing the XML string:
$resp = "<ECG>" . $ecg . "</ECG>" ....
echo $resp;
But still the alert in the AJAX error method is called - is there something else that I need to do from backend script.

As I told in comments, the response isn't well formed XML. You're missing a document node which wraps the other nodes. Like this:
<?xml version="1.0"?>
<RESPONSE>
<ECG>Abnormal</ECG>
<SP>10.99</SP>
<BP>120/90</BP>
<OXY>139</OXY>
<TMP>23</TMP>
</RESPONSE>
Also you are encouraged to set the proper content type header from PHP:
header('Content-Type: text/xml');
(before the output)

Related

PHP capture data and join together

Okay so I need to parse two parts. Here is the code im trying to parse.
<input type="hidden" name="10528935" value="12-1-D33D19A3F048E845A9AA885220729B98" />
I would like it to parse and output like this once done.
10528935=12-1-D33D19A3F048E845A9AA885220729B98
Here is the site I'm trying to do this for
https://www.payqwiq.com/login?uid=582063bd-1973-42e4-8235-b28f5addf8bf
All I need is that data to be parsed and joined like above so I can continue with my program :)
Would appreciate some help if possible :)
I'm completely new in PHP.
Php is a back-end language. Since you are attempting to get data stored in a document object on the front-end, you should use a front-end language to parse the document object, then send the data to a php handler to do what you want with it on the back-end.
Using jQuery you can achieve the desired output with one line of code, then build an ajax call to send the output data to the desired php handler.
// when document is loaded
$(document).ready(function() {
// get data from document object to send to php handler
var combinedData = $('input').attr('name') + '=' + $('input').val();
// execute ajax method to send data to php handler
sendData(combinedData);
});
function sendData(data) {
// ajax method to send data to php handler
$.ajax({
url: 'pageToSendTo.php',
type: 'POST',
data: {
"data": JSON.stringify(data)
},
dataType: 'JSON',
success: function(data) {
console.log(data);
},
error: function(xhr) {
console.log('error: ' + xhr.responseText);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name="10528935" value="12-1-D33D19A3F048E845A9AA885220729B98" />
<!-- this is the "pageToSendTo.php" php handler. -->
<?php
if ($_POST['data']) {
//echo 'received data!';
$data = json_decode($_POST['data']);
// do stuff with data
print_r(json_encode($data));
}
?>

Ajax call failing; xhr.responseXML is undefined

I'm trying to make a simple ajax call:
When the user selects and option, some info about that option will be
echoed into a div (this is dynamic)
Here's my code for the ajax call
ajax.js
$(document).ready(function()
{
//Add Event
//Currently Broadcasting #Zone
$('#beacon0').on('change', function ()
{
var Selected = $(this).find("option:selected");
var SelectedText = Selected.text();
var SelectedEncoded = encodeURIComponent(SelectedText);
$.ajax
({
url: 'ajax-addevent.php',
data: 'n_beacon='+ SelectedEncoded,
dataType: 'JSON',
success: function(returnClass)
{
var resultajax = jQuery.parseJSON(returnClass)
console.log(resultajax);
},
error: function(xhr, status, error)
{
var errors = JSON.parse(xhr.responseText);
console.log("failed");
console.log (errors);
}
});
});
});
SO the ajax call should give the name of the zone in the URL, so I can $_GET the parameter in my php script. This is the php I run just to test the ajax call.
ajax-addevent.php
<?php
include("classes/event.class.php");
$event = new Event();
$GetZoneName = $_GET['n_beacon'];
$ZoneName = urldecode($GetZoneName);
$arrayDetails = $event->getBeaconEvent($ZoneName);
while($row = mysqli_fetch_array($arrayDetails))
{
$EventTitle = $row["n_title"];
$EventLink = $row["n_link"];
$EventDate = $row["n_date"];
}
$arr = array( "EventTitle" => $EventTitle,
"EventLink" => $EventLink,
"EventDate" => $EventDate );
header("content-type:application/json");
$json_arr = json_encode($arr);
return $json_arr;
?>
My problem is that the ajax call fails and gives me this as result:
What's wrong why my ajax call? Can you help?
EDIT Update Code:
You're trying to get an XML response when the returned datatype is JSON - xhr.responseXML will always be undefined unless the response is valid XML.
Try using xhr.responseText instead. You can use JSON.parse(xhr.responseText) to get a javascript object out of it.
Another good technique is to use the dev tools of your current browser to inspect the network response directly (F12 in Firefox or Chrome, then open the Network tab).

jsonp, jQuery & PHP to make cross-domain ajax call

http://serverA.com/list.php:
html:
<form id="myform">
<input id="inputfield" name="view">
</form>
js:
var inputdata = $('#inputfield').val('ocean-view');
$('#myform').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: 'http://serverB.com/detail.php',
data: inputdata,
dataType: 'jsonp'
});
});
http://serverB.com/detail.php
php:
<?php
$view = $_GET['callback'].'('.json_encode(name) .')';
?>
html:
<h4><?php echo $view; ?></h4>
what the code does is:
from serverA, assign a value "ocean-view" to an input field, submit this form to serverB, and display this value in a h4 tag.
I couldn't quite figure out how to write the server-side code to output the value, even though I have found the following posts.
this and this.
Any kind of help is appreciated.
UPDATE:
I used YQL to help to see the jsonp callback response, here is the json structure:
callback({
"query": {
"count": 1,
"created": "2013-07-29T13:01:12Z",
"lang": "en-US",
"results": {
"h3": {
"class": "mytitle",
"content": "Example"
}
}
}
});
Actually You are very close to success... just read these points.
Whenever you are making an ajax request the browser sends a hit on ajax URL with respected parameters and details. On respected URL PHP code executes. It can return data in some format. It can not return data in directly PHP variable.
Formats are:
text/html
json
xml
......
Mainly for cross domain requests we use JSONP.
And it means PHP script will return data in JSON.
So you will just echo your json_encode in directly script. That will be the response of your ajax request.
Now when you have got the data in ajax function, then jQuery uses success: function(response){ } where you response will come.
So variable response will contain JSON.
You can access JSON and put data in any tag by using jQuery selector.
$().html(response.);
These thing can be analyzed in any browser in debug console. That what is requested and what is returned.
even you can use Firebug in Mozilla to inspect ajax request.
So you will do three changes.
In Ajax function write a success function:
var inputdata = $('#inputfield').val('ocean-view');
$('#myform').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: 'http://serverB.com/detail.php',
data: "inputdata="+inputdata,
dataType: 'jsonp',
success:function(response){
// response will be json type so access it
// print ur json in html tag like resposne is {"data":23}
$(<jquery selector>).html(reponse.data);
}
});
});
<?php
// echo this
$inputdata = $_GET['inputdata'];
// perform you logic ,
// make an array to encode it in json
echo $_GET['callback'].'('.json_encode($responseArr) .')';
?>
and remove PHP code from h4 tag.

How do I evaluate this specific JSON with Prototype(JS)?

Data from a Server became a JSON array as responseText an ajax request :
Price : [{"id":"1","max_price":"100000"},{"id":"2","max_price":"150000"},{"id":"3","max_price":"200000.55"}]
Name : [{"id":"1","name":"P1"},{"id":"2","name":"P2"},{"id":"3","name":"P3"}]
I see into Prototype this method : var json = transport.responseText.evalJSON(true);
How can I just get the Price array, so JSON equals:
[{"id":"1","max_price":"100000"},{"id":"2","max_price":"150000"},{"id":"3","max_price":"200000.55"}]`
The php needs to include the json header:
header('Content-type: application/json');
The ajax request needs to include evalScripts (make sure you trust the source):
new Ajax.Request("json.php",
{ method: 'get',
parameters: {'xyz': 'json', 'var2': 'some_val'},
evalScripts: true,
onSuccess: function(response){your_function(response);}});
Then your function can get the json like the following:
your_function = function (response) {
var result = response.responseJSON;
...
}
Edit: There's also these instructions directly from the source:
http://www.prototypejs.org/learn/json
Edit2: Here's how to update the server:
$return_data = array();
$return_data['price'] = getPrice($db);
$return_data['name'] = getName($db);
echo json_encode($return_data)."\n";
after you do this, in js you can do something like the following (from the above your_function example):
alert ("first id is: " + result['price'][0]['id']);

Dynamic XML Generated from PHP

I have a PHP script that loads XML content dynamically:
require_once 'directory/directory/';
$nice= '1149632';
$key = 'adf995jdfdfddda44rfg';
$mixer = new Live_Products($key);
$result = $mixer->product($nice)
->show(array('name','Price'))
->query();
echo $result
This will work fine when it is loaded. But I am trying to use an ajax/jquery script to send the value $nice to the PHP script; and to ultimately send the result back from the dynamically created XML file. I've been trying to figure this out for hours
Here is the ajax Script
function sendValues() {
$("$nice")
$.ajax({
url: "/myphp.php",
data: {str}
cache: false
});
}
Has anybody done something similar to this concept?
Why not pass it as a GET param like so...
jQuery
function sendValues(something) {
$.ajax({
url: "/myphp.php?nice=" + something,
cache: false,
dataType: 'xml',
success: function(xml) {
// Work with the XML
}
});
}
PHP
require_once 'directory/directory/';
$nice= '1149632';
$key = 'adf995jdfdfddda44rfg';
$mixer = new Live_Products($key);
$result = $mixer->product($_GET['nice'])
->show(array('name','Price'))
->query();
// You said it is XML?
header('Content-Type: text/xml');
echo $result;

Categories