I have a PHP SOAP web service acting as a relay to call cross domain web services. The problem I'm having is calling my local PHP web service methods from JavaScript (using JQuery/Ajax). I want to call a specific method in my web service; e.g. "LoginToAccount";
I'm NOT interested in appending params in the url and then figuring out which method to call... This is very straight forward in .NET (mywebservice.asmx/LoginToAccount") but can't figure it out how to get this to work in PHP.
I continually get a "500 Internal Server Error" of "Bad Request":
Bad Request
Here is my PHP code:
<?php
function LoginToAccount($email, $passCodeHash) {
//...code calling cross-domain web services
return $jsonEncodedResponse;
}
function CreateAccount($email, $passCodeHash){
//...code calling cross-domain web services
return $jsonEncodedResponse;
}
$server = new SoapServer(null, array('uri' => "http://www.myurl/webservices/"));
$server->addFunction('LoginToAccount');
$server->addFunction('CreateAccount');
$server->handle();
?>
Here is my JavaScript code:
function AjaxCall() {
$.ajax({
type: "POST",
url: "phpRelay.php/LoginToAccount",
data: "{email : 'myEmail#email.com', passCodeHash: '12345'}",
contentType: "application/json",
dataType: "json",
success: succeeded,
error: queryError
});
}
function succeeded(data, textStatus, request) {
var result = $.parseJSON(data.d);
}
function queryError(request, textStatus, errorThrown) {
alert(request.responseText, textStatus + " " + errorThrown);
}
This is all on the same domain. Thanks!
instead of of using php soapserver you can replace it with the following code:
echo $data = (function_exists($_SERVER['QUERY_STRING'])) ? json_encode(array('d'=>$_SERVER['QUERY_STRING'](file_get_contents('php://input')))) : 'error: function does not exists';
what it does is use the query_string as the function name. it first check if the function exists, if not the error is printed, but if et exists it calls the function with the posted data as criteria, in string format. and in the end, the returned data from the function is printed as a json array with the result set as d.
so your javascript should be as follows (note the url call should be with ? instead of / before the function):
function AjaxCall() {
$.ajax({
type: "POST",
url: "phpRelay.php?LoginToAccount",
data: "{email : 'myEmail#email.com', passCodeHash: '12345'}",
contentType: "application/json",
dataType: "json",
success: succeeded,
error: queryError
});
}
function succeeded(data, textStatus, request) {
var result = $.parseJSON(data.d);
}
function queryError(request, textStatus, errorThrown) {
alert(request.responseText, textStatus + " " + errorThrown);
}
hope this can help you! I know it is a bit late to post this, but i posted it if there is anybody else that needed something like this! I needed it and could not any solution like this, so i had to make the solution myself.
cheers
c_bb
I have tried SOAP PHP server with ajax client and found working code
First Download nusoap library from Here
then create server.php
<?php
//call library
require_once ('lib/nusoap.php');
// Define the TriangleArea method as a PHP function
function TriangleArea($b, $h) { return 'The triangle area is: ' .(($b*$h)/2); }
// Define the RectangleArea method as a PHP function
function RectangleArea($L, $l) { return 'The rectangle area is: ' .($L*$l); }
// create the function
function get_message($your_name)
{
if(!$your_name){
return new soap_fault('Client','','Put Your Name!');
}
$result = "Welcome to ".$your_name .". Thanks for Your First Web Service Using PHP with SOAP";
return $result;
}
//using soap_server to create server object
$server = new soap_server;
// Initialize WSDL support
$server->configureWSDL('mathwsdl', 'urn:mathwsdl');
// Register the TriangleArea method
$server->register('TriangleArea', // method name
array('b' => 'xsd:int', 'h' => 'xsd:int'), // input parameters
array('area_t' => 'xsd:string'), // output parameters
'urn:mathwsdl', // namespace
'urn:mathwsdl#TriangleArea', // soapaction
'rpc', // style
'encoded', // use
'1=> : Calculate a triangle area as (b*h)/2' // documentation
);
// Register the RectangleArea method to expose
$server->register('RectangleArea', // method name
array('L' => 'xsd:int', 'l' => 'xsd:int'), // input parameters
array('area_r' => 'xsd:string'), // output parameters
'urn:mathwsdl', // namespace
'urn:RectangleAreawsdl#RectangleArea', // soapaction
'rpc', // style
'encoded', // use
'2=> : Calculate a rectangle area as (L*l)' // documentation
);
// Register the RectangleArea method to expose
$server->register('get_message', // method name
array('nm' => 'xsd:string'), // input parameters
array('area_r' => 'xsd:string'), // output parameters
'urn:mathwsdl', // namespace
'urn:get_messagewsdl#get_message', // soapaction
'rpc', // style
'encoded', // use
'3=> : Print a Message as name' // documentation
);
if ( !isset( $HTTP_RAW_POST_DATA ) ) $HTTP_RAW_POST_DATA =file_get_contents( 'php://input' );
$server->service($HTTP_RAW_POST_DATA);
// create HTTP listener
//$server->service($HTTP_RAW_POST_DATA);
exit();
?>
after that create client.php
<?php
require_once ('lib/nusoap.php');
//Give it value at parameter
$param = array( 'your_name' => 'Monotosh Roy');
//Create object that referer a web services
$client = new soapclient('http://localhost:81/WebServiceSOAP/server.php?wsdl', true);
// Check for an error
$err = $client->getError();
if ($err) {
// Display the error
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
// At this point, you know any calls to
// this web service's methods will fail
}
// Call the TriangleArea SOAP method
$result = $client->call('TriangleArea',
array('b' => 10, 'h' => 15));
// Check for a fault
if ($client->fault) {
echo '<h2>Fault</h2><pre>';
print_r($result);
echo '</pre>';
} else {
// Check for errors
$err = $client->getError();
if ($err) {
// Display the error
echo '<h2>Error</h2><pre>' . $err . '</pre>';
} else {
// Display the result
echo '<h2>Result</h2><pre>';
print_r($result);
echo '</pre>';
}
}
// Call the RectangleArea SOAP method
$result = $client->call('RectangleArea',
array('L' => 40, 'l' => 20));
// Check for a fault
if ($client->fault) {
echo '<h2>Fault</h2><pre>';
print_r($result);
echo '</pre>';
} else {
// Check for errors
$err = $client->getError();
if ($err) {
// Display the error
echo '<h2>Error</h2><pre>' . $err . '</pre>';
} else {
// Display the result
echo '<h2>Result</h2><pre>';
print_r($result);
echo '</pre>';
}
}
// Display the request and response
/* echo '<h2>Request</h2>';
echo '<pre>' . htmlspecialchars($client->request,
ENT_QUOTES) . '</pre>';
echo '<h2>Response</h2>';
echo '<pre>' . htmlspecialchars($client->response,
ENT_QUOTES) . '</pre>';*/
//Call a function at server and send parameters too
$response = $client->call('get_message',$param);
//Process result
if($client->fault)
{
echo "<h2>FAULT:</h2> <p>Code: (".$client->faultcode."</p>";
echo "String: ".$client->faultstring;
}
else
{
echo $response;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8">
<title>Web Service SOAP and AJAX</title>
</head>
<script type="text/javascript" src="ajaxSOAP.js"></script>
<body>
<div style="position:relative;left:0px;
top:-12px;background-color:#1D3968;margin:0px;">
<h2 align="center"><font color="#ffffff">
Consume WebServices through SOAP-AJAX calls</font></h2></div>
<table align="center" cellpading="0px" cellspacing="3px"
bordercolor="#000000" border="0"
style="position:relative;width:300px;height:200px;">
<tr>
<td colspan="2" align="center"><h1>Rectangle Area</h1></td>
</tr>
<tr>
<td valign="center"><font color="#cc0000" size="3">
Insert value for l:</font></td>
<td><input id="l_id" type="text"></td>
</tr>
<tr>
<td><font color="#cc0000" size="3">Insert value for L:</font></td>
<td><input id="L_id" type="text"></td>
</tr>
<tr>
<td><input type="button" value="Calculate Area" onclick="myAjax();"></td>
</tr>
<tr>
<td colspan="2">
<div id="resultDiv"></div>
</td>
</tr>
</table>
</body>
</html>
ajaxSOAP.js file contains
var xhrTimeout=100;
function myAjax(){
var l_var = document.getElementById("l_id").value;
var L_var = document.getElementById("L_id").value;
var soapMessage ='<?xml version="1.0" encoding="UTF-8"?><SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="urn:mathwsdl"> <SOAP-ENV:Body><tns:RectangleArea xmlns:tns="urn:mathwsdl"><L xsi:type="xsd:int">'+L_var+'</L><l xsi:type="xsd:int">'+l_var+'</l></tns:RectangleArea></SOAP-ENV:Body></SOAP-ENV:Envelope>';
var url='http://localhost:81/WebServiceSOAP/server.php';
if(window.XMLHttpRequest) {
httpRequest=new XMLHttpRequest();
}
else if (window.ActiveXObject) {
httpRequest=new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.open("POST",url,true);
if (httpRequest.overrideMimeType) {
httpRequest.overrideMimeType("text/xml");
}
httpRequest.onreadystatechange=callbackAjax;
httpRequest.setRequestHeader("Man","POST http://localhost:81/WebServiceSOAP/server.php HTTP/1.1")
httpRequest.setRequestHeader("MessageType", "CALL");
httpRequest.setRequestHeader("Content-Type", "text/xml");
httpRequest.send(soapMessage);
}
function callbackAjax(){
try {
if(httpRequest.readyState==4) {
if(httpRequest.status==200) {
clearTimeout(xhrTimeout);
resultDiv=document.getElementById("resultDiv");
resultDiv.style.display='inline';
resultDiv.innerHTML='<font color="#cc0000" size="4"><b>'+httpRequest.responseText+'</b></font>';
}
}
} catch(e) {
alert("Error!"+e);
}
}
Related
I am trying to return an error message for my react native register screen. The .php script called is :
<?php
include 'DBConfig.php';
// Creating connection.
$con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
if ($con == false) {
$ShitMSG = "Can't connect to database" ;
$ShitJson = json_encode($ShitMSG);
echo $ShitJson ;
}
// Getting the received JSON into $json variable.
$json = file_get_contents('php://input');
// decoding the received JSON and store into $obj variable.
$obj = json_decode($json,true);
// Populate User name from JSON $obj array and store into $name.
$name = $obj['name'];
// Populate User email from JSON $obj array and store into $email.
$email = $obj['email'];
//Checking Email is already exist or not using SQL query.
$CheckSQL = "SELECT * FROM UserRegistrationTable WHERE email='$email'";
$check = mysqli_fetch_array(mysqli_query($con,$CheckSQL));
if(isset($check)) {
$EmailExistMSG = "L'E-mail est déja utilisé !";
$EmailExistJson = json_encode($EmailExistMSG);
echo $EmailExistJson ;
}
else {
// Creating SQL query and insert the record into MySQL database table.
$Sql_Query = "insert into UserRegistrationTable (name,email) values ('$name','$email')";
if(mysqli_query($con,$Sql_Query)) {
$MSG = 'Utilisateur enregistré !' ;
$json = json_encode($MSG);
echo $json ;
}
else {
echo 'Réessayez';
}
}
mysqli_close($con);
?>
When called, it receives a body looking like
body: JSON.stringify({
name: UserName,
email: UserEmail
})
Consisting of inputs for my user's name and email. DBconfig.php is another PHP file where my db's ids are, to connect to it.
My script is launched by my react native app, from this function :
class LoginScreen extends React.Component {
constructor (props) {
super(props)
this.state = {
UserName: '',
UserEmail: ''
}
}
UserRegistrationFunction () {
const { UserName } = this.state
const { UserEmail } = this.state
fetch('http://c2isante.fr/appsante/login.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: UserName,
email: UserEmail
})
}).then((response) => response.json())
.then((responseJson) => {
Alert.alert(responseJson)
}).catch((error) => {
console.error(error)
})
}
render () {
return (
<View style={styles.MainContainer}>
<Text style={{ fontSize: 20, color: '#000', textAlign: 'center', marginBottom: 15 }}>User Registration Form</Text>
<TextInput
placeholder='Entrez votre nom'
onChangeText={UserName => this.setState({...this.state, UserName})}
underlineColorAndroid='transparent'
/>
<TextInput
placeholder='Entrez votre E-mail'
onChangeText={UserEmail => this.setState({...this.state, UserEmail})}
underlineColorAndroid='transparent'
/>
<Button title="M'enregistrer" onPress={this.UserRegistrationFunction.bind(this)} color='#2196F3' />
</View>
)
}
}
There are three possible outcomes of your PHP:
A JSON encoded string:
$EmailExistMSG = "L'E-mail est déja utilisé !";
$EmailExistJson = json_encode($EmailExistMSG);
echo $EmailExistJson ;
A JSON encoded string:
$MSG = 'Utilisateur enregistré !' ;
$json = json_encode($MSG);
echo $json ;
A plain text string:
echo 'Réessayez';
You should be consistent: always encode the output as JSON or never encode the output as JSON.
Either:
Change the third case to encode the result as JSON like the others or
Change the first two to output plain text and change the JavaScript so it doesn't try to parse it as JSON
Aside: you don't specify header("Content-Type: something"), so no matter which if plain text or JSON you output, you are claiming to output HTML (PHP's default). You should fix that.
In you php script you directly json_encode the string which in return a string only.
So in your javascript code receives the string from the php file and you can't JSON.parse on a string. So it giving you error.
What is the point of encoding a string in to json string. echo the string directly or create a response array and encode it.
$x= array(
"error_code": "404",
"message": "not found"
);
echo json_encode($x);
This is my Soap Response xml,I need to get RebillCustomerID
How I can do this?
<?xml version="1.0" encoding="utf-8"?><soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Header><eWAYHeader
xmlns="http://www.eway.com.au/gateway/rebill/manageRebill">
<eWAYCustomerID>87654321</eWAYCustomerID><Username>test#eway.com.au</Username>
<Password>test123</Password></eWAYHeader></soap:Header><soap:Body>
<CreateRebillCustomerResponse xmlns="http://www.eway.com.au/gateway/rebill/manageRebill"><CreateRebillCustomerResult>
<Result>Success</Result><ErrorSeverity /><ErrorDetails />
<RebillCustomerID>90246</RebillCustomerID></CreateRebillCustomerResult>
</CreateRebillCustomerResponse></soap:Body></soap:Envelope><pre></pre>
try the code below. I am assuming your xml response is in $soapXMLResult variable
$soap = simplexml_load_string($soapXMLResult);
$response = $soap->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->children()->CreateRebillCustomerResponse;
$customerId = (string) $response->CreateRebillCustomerResult->RebillCustomerID;
echo $customerId;
How I did, create eway soap request and get eway soap result,may help others!
<?php
$URL = "https://www.eway.com.au/gateway/rebill/test/manageRebill_test.asmx?wsdl";
$option = array("trace"=>true);
$client = new SOAPClient($URL, $option);
$functions = $client->__getFunctions();
$headeroptions=array('eWAYCustomerID'=>"87654321",'Username'=>"test#eway.com.au","Password"=>"test123");
$header = new SOAPHeader('http://www.eway.com.au/gateway/rebill/manageRebill', 'eWAYHeader',$headeroptions);
$bodyoptions = array(
"CreateRebillCustomer" => array(
"customerTitle" => "Mr",
"customerFirstName"=>"Muhammad",
"customerLastName"=>"Shahzad",
"customerAddress"=>"cust ome rAddress",
"customerSuburb"=>"customer Suburb",
"customerState"=>"ACT",
"customerCompany"=>"customer Company",
"customerPostCode"=>"2345",
"customerCountry"=>">Australia",
"customerEmail"=>"test#gamil.com",
"customerFax"=>"0298989898",
"customerPhone1"=>"0297979797",
"customerPhone2"=>"0297979797",
"customerRef"=>"Ref123",
"customerJobDesc"=>"customerJobDesc",
"customerComments"=>"customerComments",
"customerURL" => "http://www.acme.com.au"
)
);
try{
$response = $client->__soapCall("CreateRebillCustomer", $bodyoptions,NULL,$header,$outputHeader);
//echo $client->__getLastRequest();
//$response = $client->CreateRebillCustomer($bodyoptions);
//echo "<pre>";echo "<br/>";
// print_r($response);
echo $result = $response->CreateRebillCustomerResult->Result;echo "<br/>";
echo $customerId = $response->CreateRebillCustomerResult->RebillCustomerID;echo "<br/>";
echo "<br/>";
if($result=='Success' AND $customerId){
echo 'Member Created at eWay Successfully!...<br/>';
echo 'Creating Recurring Billing Cycle on eWay,Please wait......<br/>';
//$UpdateRebillCustomer = CreateRebillEvent($customerId);
//print_r($UpdateRebillCustomer);
}
else{
echo $ErrorSeverity = $response->CreateRebillCustomerResult->ErrorSeverity;echo "<br/>";
echo $ErrorDetails = $response->CreateRebillCustomerResult->ErrorDetails;echo "<br/>";
}
}
catch(SOAPFault $e){
print $e;
}
if($customerId){
$bodyoptions2 = array(
"CreateRebillEvent " => array(
"RebillCustomerID" => $customerId,
"RebillInvRef" => "Ref123",
"RebillInvDes"=>"description",
"RebillCCName"=>"Mr Andy Person",
"RebillCCNumber"=>"4444333322221111",
"RebillCCExpMonth"=>"12",
"RebillCCExpYear"=>"15",
"RebillInitAmt"=>"100",
"RebillInitDate"=>date('d/m/Y'),
"RebillRecurAmt"=>"200",
"RebillStartDate"=>date('d/m/Y'),
"RebillInterval"=>"31",
"RebillIntervalType"=>"1",
"RebillEndDate"=>"31/12/2013",
)
);
try{
$response = $client->__soapCall("CreateRebillEvent", $bodyoptions2,NULL,$header,$outputHeader);
//echo $client->__getLastRequest();
//print_r($response);
echo "<br/>";
echo $result2 = $response->CreateRebillEventResult->Result;echo "<br/>";
echo $RebillCustomerID = $response->CreateRebillEventResult->RebillCustomerID;echo "<br/>";
if($result2=='Success'){
echo 'Recurring Cycle Created Successfully at eWay!...<br/>';
echo 'Member Id is ===>'.$RebillCustomerID;
//$UpdateRebillCustomer = CreateRebillEvent($customerId);
//print_r($UpdateRebillCustomer);
}
else{
echo $ErrorSeverity = $response->CreateRebillEventResult->ErrorSeverity;echo "<br/>";
echo $ErrorDetails = $response->CreateRebillEventResult->ErrorDetails;echo "<br/>";
}
}
catch(SOAPFault $e){
print $e;
}
}
?>
If you are writing a client for a SOAP service and you want to manipulate or test their response by placing it in a local file and parsing that (maybe their response has errors and you want to fix the errors yourself), you can override the URL that your soapClient uses to call methods by calling __soapCall() directly:
$result = $this->soap_client->__soapCall( 'function_call_name', ['location' => $file_location] );
Where $file_location is the absolute or relative path to your copy of their xml response. What you put as your function call name doesn't matter, since the soap client will get the same xml response regardless of what function you try to call this way. The only thing that matters is that your $file_location be correct and that the xml file has the correct permissions to be read by apache if you run this in a browser.
You can then var_dump($response) and find the node you need rather than using simplexml_load_string. If you do it this way you can easily swap out your xml for their response later on.
I am trying to fetch the RSS feed document from rss.news.yahoo.com/rss/topstories using Ajax, extract the values associated with the 'titles' tags and echo them to the screen. xmlget.htm implements Ajax via GET request.
xmlget.php uses the PHP function file_get_contents to load in the web page at the URL supplied to it in the GET variable $_GET['url'] and display the 'title' tags on the screen.
The error I get is this:
XML Parsing Error: junk after document element Location: moz-nullprincipal:{2f186a54-8730-4ead-9bf9-f82c8d56ad8f} Line Number 2, Column 1:
xmlget.htm
<html>
<head>
<title>Ajax Example</title>
</head>
<body>
<h1 style="text-align: center;">Loading a web page into a DIV</h1>
<div id='info'>This sentence will be replaced</div>
<script>
nocache = "&nocache="+Math.random()*1000000
url = "rss.news.yahoo.com/rss/topstories"
request = new ajaxRequest()
request.open("GET","xmlget.php?url="+url+nocache,true)
out = "";
request.onreadystatechange = function(){
if(this.readyState == 4){
if(this.status == 200){
if(this.responseXML != ""){
titles = this.responseXML.getElementsByTagName('title')
for (j = 0 ; j < titles.length ; ++j)
out += titles[j].childNodes[0].nodeValue + '<br />'
document.getElementById('info').innerHTML = out
}
else alert("Ajax error: No data received")
}
else alert( "Ajax error: " + this.statusText)
}
}
request.send(null)
function ajaxRequest(){
try{
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e1){
try{
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e2){
try{
request = new XMLHttpRequest()
} catch (e3){
request = false
}
}
}
return request
}
</script>
</body>
xmlget.php
<?php
if(isset($_GET['url'])){
function SanitizeString($var) {
$var = strip_tags($var);
$var = htmlentities($var);
return stripcslashes($var);
}
header('Content-Type: text/xml');
echo file_get_contents("http://www.".SanitizeString($_GET['url']));
}
?>
please add the following line in the head
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=UTF-8" />
Found the problem!
The file_get_contents function was unable to find the host because the url was invalid. rofl...
INCORRECT
echo file_get_contents("http://www.".SanitizeString($_GET['url']));
CORRECT
echo file_get_contents("http://".SanitizeString($_GET['url']));
I am just starting to learn JSON where a tutorial from other site uses this code (which I already modified to simplify this):
$(document).ready(function(){
$('#getdata-button').click(function(){
$.ajax({
type: "GET",
url: "json-data.php",
dataType: "json",
success: function(){
alert('a');
$('#showdata').html(
"<p>item1="+data.item1+
" item2="+data.item2+
" item3="+data.item3+"</p>"
);
}
});
});
});
And this is the code for json-data.php
<?php
$item1 = "candy";
$item2 = "chocolate";
$item3 = "ice cream";
//return in JSON format
echo "{";
echo "item1: ", json_encode($item1), "\n";
echo "item2: ", json_encode($item2), "\n";
echo "item3: ", json_encode($item3), "\n";
echo "}";
?>
The problem is that alert function (for debugging purposes) isn't responding after I have clicked the button (with the id of "getdata-button"). Firebug says that the request is successful and I can see the data from there. No error was found. It is just the callback function is not executing, but why?
You need to output your JSON correctly. Replace your PHP with the below
$items = array(
'item1' => $item1,
'item2' => $item2,
'item3' => $item3
);
header('Content-type: application/json');
echo json_encode($items);
I have a form that looks like this. Now a client has asked to convert this to a format that queries and sends response in XML. Can someone pint me to appropriate tutorial or example in PHP. There seems to be many ways of doing this
<form action="" method='post'>
<table>
<tr><td>User Number </td><td><input type='text' name='task_user_no' value='<?=$task_user_no?>'></td></tr>
<tr><td>Date </td><td><input type='text' name='task_date' value='<?=$task_date?>'> (YYYYMMDD)</td></tr>
<tr><td>From Time </td><td><input type='text' name='task_from_time' value='<?=$task_from_time?>'>(HHMM)</td></tr>
<tr><td>To Time </td><td><input type='text' name='task_to_time' value='<?=$task_to_time?>'>(HHMM)</td></tr>
<tr><td>Message </td><td><input type='text' name='task_message' value='<?=$task_message?>'></td></tr>
<tr><td> </td><td><input type='submit' value='submit' name='submit' ></td></tr>
</form>
Well since you havent provided details ill lay down the basics:
A cron job, user interaction, or some other trigger invokes the request on the Remote Server (RS)
The php script on the RS builds a query to send to the Application Server (AS) that hosts your site/application
The AS parses the request variables and builds a query for the data store.
The AS makes the query on data store, and transforms the results to an XML format
The AS sends the response as XML to the RS
The RS parses the XML and does whatever it needs to do with the data it contains
So given these steps some example scripts:
RS Server Script
// set up params for query:
$params = array(
'task_no' => '0000000'
'task_date' => 'YYYYMMDD',
'task_from_time' => 'HHMM',
'task_to_time' => 'HHMM',
'taks_message' => 'The Message'
);
$client = curl_init('http://remote-server.com/task.php');
// return the response instead of outputting it
curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
// make it a POST request, use CURLOPT_GET for Get requests
curl_setopt($client, CURLOPT_POST, true);
// set the data to send.. if using get then intstead use http_build_query($params) and append the resuult to the URL used in curl_init
curl_setopt($client, CURLOPT_POSTFIELDS, $params);
$response = curl_exec($client);
// load the response as xml
try
{
$responseXml = new SimpleXmlElement($response);
// do stuff here with the result see SimpleXml documentation for working with the xml nodes
exit;
}
catch(Exception $e)
{
// log message from exception
// exit with a non-zero status code may be important for cron or a shell invocation
exit($e->getCode());
}
task.php script on the AS
// Im going to use PDO for simplicity sake
$db = new PDO($dsn, $user, $pass);
$query = 'SELECT * from table_name'
.'WHERE task_user_no = :task_user_no'
.'AND task_date = :task_date'
.'AND task_from_time = :task_from_time'
.'AND task_to_time = :task_to_time';
$stmt = $db->prepare($query);
$params = $_POST; // make a copy for binding
$xml = new DOMDocument('1.0', 'UTF-8');
// create some basic elements
$response = $xml->createElement('response');
$info = $xml->createElement('info');
$results = $xml->createElement('results');
// set up an array we can append later if there are errors
$errors = array();
foreach($params as $field => $value)
{
$paramName = ':' . $field;
switch($field)
{
case 'task_user_no':
$paramType = PDO::PARAM_INT; // assuming an int pk/fk
break;
default:
$paramType = PDO::PARAM_STR; // assuming string for all others
break;
}
if(!$stmt->bindParam($paramName, $param[$field], $paramType))
{
$errors[] = $xml->createElement('error', sprintf(
'Value for (%s) does not exist or is not of the proper type (%s).'
$field,
$paramType
));
}
}
if(!$stmt->execute() && ($pdoError = $stmt->errorCode()))
{
$errors[] = sprintf(
'There was an error retrieving your data, Error (%s)',
$pdoError
);
}
while(false !== ($record = $stmt->fetch(PDO::FETCH_ASSOC)))
{
$task = $xml->createElement('task');
foreach($record as $col => $val)
{
$task->appendChild($xml->createElement($col, $val));
$results->appendChild($task);
}
}
if(!empty($errors))
{
$errorsElement = $xml->createElement('errors');
foreach($errors as $error)
{
$errorsElement->appendChild($xml->createElement('error', $error));
}
$info->appendChild($errorsElement);
}
$response->appendChild($info);
$response->appendChild($results);
$xml->appendChild($response);
$responseStr = $xml->saveXml();
header('Content-type: text/xml');
header('Content-length: '. strlen($responseStr));
header('HTTP/1.1 200 Ok');
print $responseStr;
exit;
Of course you can use existing libraries to further simplicty things... For example instead of using curl you could use Zend_Http_Client (which i would definitely recommend since it not only allows you to use curl but also fopen and direct sockets). OR for the xml response parsing on the AS you could use Zend_Dom_Query which basically allows you to work with the xml response in a way similar to jQuery (css selectors and what not instead of xPath).
Take a look at Jquery Ajax Function
Doc