WCF with Json and bootstrap - javascript

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)
}

Related

Getting 403 error while making ajax request in jQuery

I'm getting a 403 error while making an AJAX request to a php page of my own website.
This is the error:
"jq.js:663 POST https://playonlineloto.com/backend/cstatus.php 403"
I'm using jQuery to make the request. The code is:
function status() {
var table = document.getElementById("table").value;
var name=document.getElementById("username").innerHTML;
var card=document.getElementById("card").innerHTML;
var dataString = "table=" + table+"&name="+name+"&card="+card;
$.ajax({
type: "POST",
url: "cstatus.php",
data: dataString,
cache: false,
success: function(html) {
if(html=="no"){
}else{
console.log("kicked out");
console.log(html);
var kick = document.getElementById("kick");
kick.style.display="block";
}
}
});
};
and I'm requesting from this url
https://playonlineloto.com/backend/custom-game.php?val=1&table=U7Gh8c7f6&admin=yes
My files have enough permission. Please help me!!

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.

AJAX call during server request is failing

I am using a button to trigger an AJAX call to retrieve data from an SQL database. The problem I'm having is when the button click also triggers a call to the server, the AJAX call fails.
Code:
$('.ptimage').click(function () {
document.getElementById('loading').style.display = "block";
if (dataStore.getItem('mlist') == null || dataStore.getItem('flist') == null) {
alert('isnull');
var nulldata = {};
nulldata.nullvar = "thing";
var jsonData = JSON.stringify({
nulldata: nulldata
});
$.ajax({
type: "POST",
url: "WebService.asmx/Getmf",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
error: OnErrorCall
});
function OnSuccess(response) {
var arraystring = response.d;
alert(arraystring);
mlist = arraystring.split(',');
mlist.splice(0, 1);
mlist.splice(-1, 1);
dataStore.setItem('mlist', JSON.stringify(mlist));
flist = arraystring.split(';');
flist.splice(0, 1);
flist.splice(-1, 1);
dataStore.setItem('flist', JSON.stringify(flist));
}
function OnErrorCall(response) {
alert("fail");
}
}
ptsession = dataStore.getItem('ptsessionval');
if (ptsession !== focusedcell) {
btn57.click();
}
})
So if ptsession != focusedcell, essentially if the clicked record is different from the current one, it will trigger a server call to the c# codebehind to get the new record.
If the record is different, the AJAX call fails and the call to the server from button57 (postback) succeeds. If the record is the same (so no call to the server from button57) the AJAX call succeeds. I can't figure out why this is happening.

Downloading Excel File via webmethod response by ajax calling

I have created a webmethod and the method just send a Excel file as webresponse.When i run only the webmethod it works fine as want
My webmethod is following:
public void Export_ex(string elem)
{
string elements = elem;
HttpContext.Current.Response.ContentType = "data:application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=Print.xls");
HttpContext.Current.Response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
HttpContext.Current.Response.Write("<head>");
HttpContext.Current.Response.Write("<div>");
HttpContext.Current.Response.Write("<META http-equiv=\"Content-Type\" content=\"text/html; charset=utf- 8\">");
HttpContext.Current.Response.Write("<!--[if gte mso 9]><xml>");
HttpContext.Current.Response.Write("<x:ExcelWorkbook>");
HttpContext.Current.Response.Write("<x:ExcelWorksheets>");
HttpContext.Current.Response.Write("<x:ExcelWorksheet>");
HttpContext.Current.Response.Write("<x:Name>Report Data</x:Name>");
HttpContext.Current.Response.Write("<x:WorksheetOptions>");
HttpContext.Current.Response.Write("<x:ValidPrinterInfo/>");
HttpContext.Current.Response.Write("</x:Print>");
HttpContext.Current.Response.Write("</x:WorksheetOptions>");
HttpContext.Current.Response.Write("</x:ExcelWorksheet>");
HttpContext.Current.Response.Write("</x:ExcelWorksheets>");
HttpContext.Current.Response.Write("</x:ExcelWorkbook>");
HttpContext.Current.Response.Write("</xml>");
HttpContext.Current.Response.Write("<![endif]--> ");
HttpContext.Current.Response.Write("</head>");
HttpContext.Current.Response.Write(elements);
HttpContext.Current.Response.Flush();
// HttpContext.Current.Response.End();
}
but when i call it from javascript function by ajax calling nothing happened. My ajax method is following :
var str = "something"
var data = { elem: str };
$.ajax({
type: 'POST',
url: "ImageSaving.asmx/Export_ex",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
mimeType: 'application/vnd.ms-excel',
success: function (response) {
var show = response.d;
},
failure: function (msg) {
alert("Error occur, could not load the service.");
}
});
I could not understand where i am getting wrong?? Any suggestion regarding this?
For security reasons, you cannot download file from client side. I advice to use a hidden button server side and simulate the click from another button client side.
Regards.

Calling PHP webservice method from Javascript/jQuery

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

Categories