Calling PHP webservice method from Javascript/jQuery - javascript

I've have created a PHP web service method
public function import_external_xml($importXml)
I want to allow a client to upload xml via my web service method. My web service is not on the same domain as the client. The client has a webpage with a button where he want to write some javascript/jQuery to upload the xml via my web service method.
How can he do this?
Web service method in server.php:
public function import_external_xml($importXml)
{
echo 'import_external_xml';
exit;
}

I did the same thing using Ruby on Rails. But was sending data that was not in xml format.
One important thing as you said that your webservice is not on the same domain, you will have to deal with CORS. You can get idea about CORS here https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
You can refer this Post JQuery JSON Calls To PHP WebService Always Runs "Error" Callback
function callPhpAPI(){
var dataa = {"your_data":youdata};
$.ajax({
url : yourwebserviceurl,
type: 'POST',
data : JSON.stringify(dataa),
contentType : "application/json",
success:function(data)
{
if(data){
alert(data);
//console.log("Data from Server"+JSON.stringify(data));
}
else{
console.log("Data is empty");
}
},
error: function(xhr) {
alert('Error! Status = ' + xhr.status + " Message = " + xhr.statusText);
//console.log('Error! Status = ' + xhr.status + " Message = " + xhr.statusText);
}
});
});

You can call your php function like this using ajax
xmlDocument = $("<wrap/>").append(xmlDocument).html();
xmlDocument = encodeURIComponent(xmlDocument);
then ajax
jQuery.ajax({
type: "POST",
url: 'your_functions_address.php',
processData : false,
contentType : 'text/xml',
data : xmlDocument,
success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
i think you want pass xml via this ajax post , then you can refer this discussion
post xml
also check this

Related

Cross-Domain Ajax POST request with php proxy

First of all, I have already read this answer, which is to do the Cross-Domain Ajax GET request with php proxy. But what I need is a Ajax POST request.
So in my project, long time ago. Someone wrote this php file and together the ajax call in JavaScript, those are mean to solve the cross origin problem and which works really good! So I never think about to understand this, because I basiclly just need to change the url in the JavaScript and don't need to understand how this Ajax call works together with php.
PHP:
<?php
$nix="";
$type=$_GET['requrl'];
if ($_GET['requrl'] != $nix) {
$file = file_get_contents($_GET['requrl']);
}
elseif ($_POST['requrl'] != $nix) {
$file = file_get_contents($_POST['requrl'], false, $_POST['data']);
}
else {
$file = "false type";
}
echo $file;
?>
JavaScript:
var url = "https://XXXXXXXXXXXXXX";
url = encodeURI(url);
var useProxyPhp = true;
var data = (useProxyPhp) ? {requrl: url} : "";
var ajaxUrl = (useProxyPhp) ? "proxy.php" : url;
var ajaxProperties = {
type: 'GET',
data: data,
url: ajaxUrl,
cache: false
};
res = jQuery.ajax(ajaxProperties).done(function(res) {
// do something with the result here
})
So what I need to do is just take the same ajax GET request (copy and paste in JS) and just replace the url every time ==> job done!
Now, the first time I need to do a ajax POST request to send a xml file to the server, the server will do some calculate on it and give me a response.
I tested first with the POSTMAN and everything works fine, but when I switch to my real project. I become the Cross origin problem. So I think If I could do something to the already existing php and js, so I can solve the cross origin problem.
I tried this in my JavaScript but I got only the "false type" as antwort
function sendWPSRequest(xml) {
var url = "https://XXX.XXX.XXX.XXX:XXXX/wps";
useProxyPhp = true;
var data = (useProxyPhp) ? {requrl: url, data: xml} : "";
var ajaxUrl = (useProxyPhp) ? "proxy.php" : url;
$.ajax({
type: "POST",
url: ajaxUrl,
dataType: "text",
contentType: "application/xml",
data: data,
success:function (response) {
console.log('POST success: ', response);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("POST", textStatus, errorThrown);
}
});
}
Can someone help me a little bit to understand what the php is doing here and what should I do to modify the php and JS.

WCF with Json and bootstrap

I have a simple bootstrap page with a button and when the button is clicked the modal opens up.
the question is the modal content or the modal body should be filled with wcf data, both the webpage and the wcf json data will be hosted in IIS can anyone please help me how to achieve this?
Thanks in advanceenter image description here
What you need to do is to make a ajax call in jquery that will call the WCF method. Below is how you call the service.
var Type;
var Url;
var Data;
var ContentType;
var DataType;
var ProcessData;
function WCFJSON() {
var userid = "1";
Type = "POST";
Url = "Service.svc/GetUser";
Data = '{"Id": "' + userid + '"}';
ContentType = "application/json; charset=utf-8";
DataType = "json"; varProcessData = true;
CallService();
}
// Function to call WCF Service
function CallService() {
$.ajax({
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
data: Data, //Data sent to server
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
processdata: ProcessData, //True or False
success: function(msg) {//On Successfull service call
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
});
}
function ServiceSucceeded(result) {
if (DataType == "json") {
$("#ModalBody").html(result)
}

Why is my Ajax request sending "Content-Type: application/x-www-form-urlencoded" when I have dataType: "JSON"?

When I am using the following to respond to a button click, it it called (verified by using the console.log()), however, the http request it generated has the header "Content-Type: application/x-www-form-urlencoded; charset=UTF-8\r\n". Shouldn't it be json?
I am using google chrome 34.0.1847.132 on Ubuntu. Jquery version 1.8.3.
Thanks in advance!
function action (mode) {
console.log("action called with mode " + mode);
$.ajax({
type: "POST",
url: '/saas.php',
data: {
action: (mode == 1)? "start" : "stop"
},
dataType: "json",
success: function(data) {
//alert(data);
if (data.msg != null) {
alert(data.msg);
} else {
if (mode == 1) {
document.getElementById('createLoadGen').innerHTML = 'creating loadGen...';
setTimeout(checkStatus, 1000);
}
}
}
});
if (mode == 2) {
document.getElementById('createLoadGen').innerHTML = '<button onclick="action(1)" >create LoadGen</button>';
document.getElementById('deleteLoadGen').style.display = 'none'
}
}
Not generally. The Content-Type header in the request describes the content in the request body, not the type of content that is expected in the response (describing the expected response format is the job of the Accept header).
By default, jQuery will encode the data using the standard encoding used by HTML forms.
Now, it might be that the server is expecting the request to be formatted as JSON, in which case you would need to make the following modifications to the jQuery call:
Say that you are sending JSON
Encode the content you are sending as JSON instead of letting jQuery encode it itself
Such:
data: JSON.stringify({
action: (mode == 1)? "start" : "stop"
}),
contentType: "application/json",
sass.php will then have to parse the JSON request instead of letting PHP do it invisibly in the background and just plucking the data out of $_POST.

PHP/ajax - prevent user from submitting a url with get variables except in ajax call

Hi I have a jquery function that uses an ajax call to send information to a php page. It sends this information using the get method. My concern for this is that what if a user goes directly to the php page and enters some get variables in the url. Whilst sensitive data is not being processed by the php script, I still want just the ajax call to be able to interact with the script and not a user (via entering the url in their browser). How can this be done?
js code
$.ajax({
type: "GET",
url: "/add.php",
data: 'id=' + itemid,
dataType: "json",
success: function (data) {
document.getElementById("name").innerHTML = data[0];
document.getElementById("desc").innerHTML = data[1];
document.getElementById("price").innerHTML = data[2];
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
php code
$output = array();
$output[0] = $itemname . " " . $_GET['id'];
$output[1] = $itemdescription;
$output[2] = $itemprice;
echo json_encode($output);
exit();
Unfortunatley I cannot use the POST method, as this clashes with some code.
Most ajax frameworks (like jQuery) are sending the HTTP_X_REQUESTED_WITH header. Here is already described how to retrieve it's value.
I think it's really not recommended to secure your script using header values because you can manipulate the request headers (e.g. curl). Which method you use, GET, POST, PUT or DELETE doesn't matter, your server side api must be secured. If you want to prevent repeated calls to that url, take a look at captcha services or add uids to urls that are only valid once.
For POST or GET request, if you are doing insert in your database you HAVE TO
- securize your form
- securize posted data
Plus, you should consider prefering using array of key/values
$output = array(
'id' => $_GET['id'],
'name' => $itemname,
'description' => $itemdescription,
'price' => $itemprice
);
echo json_encode($output);
js
$.ajax({
type: "GET",
url: "/add.php",
data: 'id=' + itemid,
dataType: "json",
success: function ( item ) {
document.getElementById("name").innerHTML = item.name + " " + item.id;
document.getElementById("desc").innerHTML = item.description;
document.getElementById("price").innerHTML = item.price;
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
To securize your ajax query, you must escape html entities, sql injection.
To securize the form, you could generate a token for your each form, and encode data before sending them to the server, the client won't be able to read what kind of data you're sending to the server.
On the server side, you could decode before your insert.

Client Side Ajax with jQuery reading a JSON

I'm trying to make a JavaScript that is fetching a JSON (IP DATA) and retrieves data from it (GEO IP) with AJAX and this is what I have so far:
$(document).ready(function(){
var path_to_the_webservice = "http://www.pathtothescript.com/check.php";
$.ajax({
url: path_to_the_webservice,
success: function(html)
{
if(html)
{
alert('3');
$('#content').append(html);
}
else
{
alert('4');
}
}
});
});
and I get alert(4), WHY?
Basically when you access http://www.pathtothescript.com/check.php from browser, retrieves a JSON that I have to parse with:
$.getJSON(path_to_the_json,
function(data)
{
$.each(data, function(i,item)
{
});
}
but I'm not sure how to make it.
The JSON looks like this http://j.maxmind.com/app/geoip.js
Any help?
It can be caused by Same origin policy.
Try to use JSONP request:
$.getJSON('http://example.com?callback=?', function(data) {
console.log(data);
});
Handling the response from http://j.maxmind.com/app/geoip.js
// Actually we can send regular AJAX request to this domain
// since it sends header Access-Control-Allow-Origin:*
// which allows cross-domain AJAX calls.
$.get('http://j.maxmind.com/app/geoip.js', function(data) {
console.log('Retrieved data:',
data,
'is type of', typeof data);
// Now we have some functions to use:
console.info('Some info:', geoip_country_name(),
geoip_latitude(),
geoip_longitude());
});​
Fiddle
UPDATE:
In chat we found that my previous example works good in Google Chrome but doesn't work in Mozilla Firefox.
Though I played a little bit with it and found the solution:
// Actually we can send regular AJAX request to this domain
// since it sends header Access-Control-Allow-Origin:*
// which allows cross-domain AJAX calls.
$.ajax({
url: 'http://j.maxmind.com/app/geoip.js',
type: 'GET',
success: function(data) {
// Now we have some functions to use:
alert(geoip_country_name() + ': ('
+ geoip_latitude() + '; '
+ geoip_longitude() + ')');
},
error: function(e) {
console.log('Error:', e);
},
contentType: 'application/javascript; charset=ISO-8859-1',
dataType: 'script'
});
​
Fiddle
Also I've set a charset accordingly to service documentation.

Categories