SOAP webservice call by ajax in phonegap error - ajax

I'm having a problem with trying to set up a working web service in my application I'm making using Phonegap. I need to get data from an existing web service. I found that by using a simple ajax request, this should be working. Am I not using the ajax request correctly?
The web service I'm trying to call can be found here: http://ws.swinggift.com/SGServices.asmx
EDIT: I tested it on http://wsdlbrowser.com/ and I'm getting my xml file back, how does this site work ?
I'm working in the ripple emulator so I have a cross domain proxy.
I'm suspecting that my request header may be off ?
error that I'm getting:
Failed to load resource: the server responded with a status of 400 (Bad Request) (10:26:26:851 | error, network)
at https://rippleapi.herokuapp.com/xhr_proxy?tinyhippos_apikey=ABC&tinyhippos_rurl=http%3A//ws.swinggift.com/SGServices.asmx%3Fop%3DGetVouchers
(I can't make my logon code public)
my test html file:
<html>
<head>
<title>Calling Web Service from jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#btnCallWebService").click(function(event) {
var wsUrl = "http://ws.swinggift.com/SGServices.asmx?op=GetVouchers";
var soapRequest =
'<?xml version="1.0" encoding="utf-8"?>' +
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
'<soap:Body>' +
'<GetVouchers xmlns="http://tempuri.org/">' +
'<logoncode>ICantGiveYouThis</logoncode>' +
'</GetVouchers>' +
'</soap:Body>' +
'</soap:Envelope>';
$.ajax({
type: "POST",
url: wsUrl,
contentType: "text/xml; charset=utf-8",
dataType: "xml",
crossDomain: true,
data: soapRequest,
beforeSend: function(XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
XMLHttpRequest.setRequestHeader("SOAPAction", "http://tempuri.org/GetVouchers");
XMLHttpRequest.setRequestHeader("Accept", "application/xml, text/xml, */*");
},
success: processSuccess,
error: processError
});
});
});
function processSuccess(data, status, req) {
if (status === "success")
$("#response").text($(req.responseXML));
}
function processError(data, status, req) {
console.log(req.responseText + " " + status);
}
</script>
</head>
<body>
<h3>
Calling Web Services with jQuery/AJAX
</h3>
<input id="btnCallWebService" value="Call web service" type="button" />
<div id="response" >
</div>
</body>
</html>
Thanks!
EDIT:
I don't know if it helps but if I do a 'GET' with the this code, I get the webpage in HTML format if I ask for the responseText
<html>
<head>
<title>SOAP JavaScript Client Test</title>
<!-- jQuery / jQueryMobile Scripts -->
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/jquery.mobile-1.3.1.min.js"></script>
<script type="text/javascript">
function soap() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'http://ws.swinggift.com/SGServices.asmx?op=GetVouchers', true);
// build SOAP request
var sr =
'<?xml version="1.0" encoding="utf-8"?>' +
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
'<soap:Body>' +
'<GetVouchers xmlns="http://tempuri.org/">' +
'<logoncode>something</logoncode>' +
'</GetVouchers>' +
'</soap:Body>' +
'</soap:Envelope>';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
console.log('done' + xmlhttp.responseText);
$("#response").text($(xmlhttp.responseXML));
}
};
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.setRequestHeader("Accept", "application/xml, text/xml, */*");
xmlhttp.setRequestHeader("SOAPAction", "http://tempuri.org/GetVouchers");
xmlhttp.send(sr);
// send request
// ...
}
</script>
</head>
<body>
<form name="Demo" action="" method="post">
<div>
<input type="button" value="Soap" onclick="soap();" />
<div id="response" >
</div>
</div>
</form>
</body>
</html>

Try setting processData: false. This flag is true by default and jQuery is converting your XML to string.
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
$.ajax({
type: "POST",
url: wsUrl,
contentType: "text/xml; charset=utf-8",
dataType: "xml",
crossDomain: true,
data: soapRequest,
processData: false,
beforeSend: function(XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
XMLHttpRequest.setRequestHeader("SOAPAction", "http://tempuri.org/GetVouchers");
XMLHttpRequest.setRequestHeader("Accept", "application/xml, text/xml, */*");
},
success: processSuccess,
error: processError
})

It was an emulator problem ... Working now with the code above.

Related

Bootstrap alert won't show after AJAX call in ASP.Net Razor Pages

I'm trying to display a Bootstrap Alert after an AJAX call within an ASP.Net Core Razor Pages application. The AJAX call to the Page Model handler works and returns the expected data, but the Success Function within the AJAX call never displays the Bootstap Alert.
Any ideas?
Thanks.
Cshtml
<style type="text/css">
.alert {
display: none;
}
</style>
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$('button').on('click', function(){
const token = $('[name="__RequestVerificationToken"]').val();
var data = { "MyVar": "Test"};
$.ajax({
url: '?handler=SaveOrder',
method: "post",
contentType: "application/json",
dataType: 'application/json; charset=utf-8',
headers: {
"RequestVerificationToken" : token
},
data: JSON.stringify(data),
success: function(data){
alert(data.success);
$('.alert').show();
}
}); //Close AJAX
})//Close Btn Click
});//Close function
});//Close document ready
</script>
<div id="msg" class="alert alert-danger alert-dismissible" role="alert">
<div class="alert-message">
Put message here.
</div>
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="alert" aria-label="Close"></button>
</div>

SOAP webservice call to a method using jquery ajax that sends 2 parameters, how to catch the responses in a loop

I have a SOAP webservice created in c# (hosted on localhost) called soapService.aspx . It has a method called displayClass(String id, String theDate)
it returns. This returns following json
[{"lesson_id":2,"customer_id":4,"instructor_id":8,"dance_style_id":2,"hourly_rate":20,"lesson_time":"Afternoon","lesson_date":"03/12/2015","start_time":"11:22","end_time":"14:22 ","notes":"test test","payment_status":0,"status":0,"lesson_slot":null,"duration":3},{"lesson_id":3,"customer_id":4,"instructor_id":8,"dance_style_id":2,"hourly_rate":20,"lesson_time":"Afternoon","lesson_date":"03/12/2015","start_time":null,"end_time":null,"notes":null,"payment_status":0,"status":0,"lesson_slot":null,"duration":3},{"lesson_id":4,"customer_id":4,"instructor_id":8,"dance_style_id":2,"hourly_rate":20,"lesson_time":"Afternoon","lesson_date":"03/12/2015","start_time":null,"end_time":null,"notes":null,"payment_status":0,"status":0,"lesson_slot":null,"duration":3}]
I found this using web service invoke method given on the web service description page.
I want to catch the response using ajax.
So far I wrote this
$(document).ready(function () {
function displayClass() {
var instructorInputID = $('#instructorIdText').val();
var instructorInputDate = $('#instructordateText').val();
//send this id to web service
$.ajax({
url: "http://localhost/soapService.asmx/displayClasses",
type: POST,
dataType:"json",
data:instructorInput,
contentType:"application/json; charset:utf-8",
success:function(msg){
//process the msg
}
});
}
});
1) How do I invoke the web service method by passing parameters
2) How do i display all these json data in a table? Please help
Edit : Tried to post
data: "{'id': '" + instructorInputID + "','theDate': '" + instructorInputDate + "'}",
THis is the response I get from console
XMLHttpRequest cannot load http://localhost:18324/soapService.asmx/displayClasses. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:17182' is therefore not allowed access.
EDIT Two :
complete code : Still Error.. msg not defined
<pre>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#findClassBtn").click(function () {
displayClass();
});
function onSuccess(msg) {
$.each(msg, function(i, item) {
var tds = "";
$.each(item, function(i, item) {
tds += "<td>" + item + "</td>";
});
$('#table').append("<tr>" + tds + "</tr>");
});
}
function displayClass() {
var instructorInputID = $('#instructorIdText').val();
var instructorInputDate = $('#instructordateText').val();
//send this id to web service
$.ajax({
url: "soapService.asmx/displayClasses",
type: "POST",
dataType:"json",
data: {
'id': instructorInputID,
'theDate': instructorInputDate
},
contentType: "application/json; charset:utf-8",
success: onSuccess(msg)
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:Label ID="Label1" runat="server" Text="Add Your Id"></asp:Label>
<p>
<asp:TextBox ID="instructorIdText" runat="server"></asp:TextBox>
</p>
<asp:Label ID="Label2" runat="server" Text="Add date (dd/mm/yyyy)"></asp:Label>
<p>
<asp:TextBox ID="instructordateText" runat="server"></asp:TextBox>
</p>
<asp:Button ID="findClassBtn" runat="server" OnClick="findClassBtn_Click" Text="Find Classes" />
<p>
<asp:Label ID="Label3" runat="server" Text="Label"></asp:Label>
</p>
</form>
<table id="table">
</table>
<pre>
Error: msg is not defined.
$(document).ready(function () {
function displayClass() {
var instructorInputID = $('#instructorIdText').val();
var instructorInputDate = $('#instructordateText').val();
//send this id to web service
$.ajax({
url: "http://localhost/soapService.asmx/displayClasses",
type: POST,
dataType:"json",
data: {
'id': instructorInputID,
'theDate': instructorInputDate
},
contentType: "application/json; charset:utf-8",
success: function (msg) {
$.each(msg, function(i, item) {
var tds = "";
$.each(item, function(i, item) {
tds += "<td>" + item + "</td>";
});
$('#table').append("<tr>" + tds + "</tr>");
});
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
</table>

Call remote asmx service by JQuery always fail

I want to use below service throw JQuery:
http://www.webservicex.net/globalweather.asmx/GetCitiesByCountry
But it only execute the error function, I tried below :
function serviceCall() {
var txtInput = $("#txtInput").val();
var webMethod = 'http://www.webservicex.net/globalweather.asmx/GetCitiesByCountry';
var datap = {"CountryName":JSON.stringify("Italy")};
$("#divResult").html('loading...');
$.ajax({
type: "POST",
url: webMethod,
data: datap,// { "CountryName" : JSON.stringify("Italy")},
contentType: "application/json; charset=utf-8",
dataType: "jsonp", //for Firefox change this to "jsonp"
success: function (response) {
alert("reached success");
$("#divResult").html(response.d);
},
error: function (e) {
$("#divResult").html("Unavailable: " + txtInput);
}
});
}
SO I receive Unavailable: Italy
Below is full page code :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
function serviceCall() {
var txtInput = $("#txtInput").val();
var webMethod = 'http://www.webservicex.net/globalweather.asmx/GetCitiesByCountry';
var datap = {"CountryName":JSON.stringify("Italy")};
$("#divResult").html('loading...');
$.ajax({
type: "POST",
url: webMethod,
data: datap,// { "CountryName" : JSON.stringify("Italy")},
contentType: "application/json; charset=utf-8",
dataType: "jsonp", //for Firefox change this to "jsonp"
success: function (response) {
alert("reached success");
$("#divResult").html(response.d);
},
error: function (e) {
$("#divResult").html("Unavailable: " + txtInput);
}
});
}
</script>
<title></title>
</head>
<body>
<form id="form1" runat="server">
<input type="text" id="txtInput" value="Italy"/>
<br />
<div style="width: 100px; height: 30px; background-color: yellow;" onclick="serviceCall();">
Click me</div>
<div id="divResult" runat="server">
</div>
</form>
</body>
</html>
Any help to fix that?
I can see several mistakes here:
the dataType has to be json, not jsonp
your payload (the value of data) has to be a json-object entirely serialized
is your WebMethod a ScriptMethod?
Can't exactly tell what is wrong though. I need to see the error message from the server.
use the following example to call asmx method and any web method from any where else
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'PageName.aspx/SaveData',
data: "{'radio':'" + input 1+ "', 'min':'" + input 2 + "', 'sec':'" + input 3 + "'}",
async: false,
success: function (response) {
},
error: function ()
{ console.log('there is some error'); }
});

JSONP callback successful but javascript not updating .html when jQueryMobile included

I am building a PhoneGap app using jQuery Mobile. My JSONP cross domain communication works, but have an issue when jQuery Mobile is included. Without it everything works as expected, included, it stops working.
I've reduced code to simplest form - Serialize data, encode and call CrossDomain PHP file using JSONP. Execute success function. I thought it might be bad JS but "alert" works and no JS errors. But the $('#section1').html("SECTION 1 - " + data.message); doesn't update. Note: When I remove jQM it all works!
Below is the HTML and the PHP code it calls. It's as though the jQueryMobile AJAX call is interfering with the update of the .html code. Any ideas? I'm stumped.
Ajax4d.htm
<html><head><title>First jQueryMobile Example</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>
<script>
$(document).ready(function() {
$("#foo").submit(function(event) {
event.preventDefault();
var $form = $(this),
$inputs = $form.find("input, select, button, textarea"),
serializedData = $form.serialize();
var postData = serializedData;
var urlStr = "http://www.fohost.co/testURLd.php?";
alert (urlStr + encodeURI(postData));
$.ajax({
url: urlStr,
data: encodeURI(postData),
dataType: "jsonp",
success: function(data){
alert("SUCCESS callback before HTML update: " + data.message);
$('#section1').html("SECTION 1 - " + data.message);
}
});
});
});
</script>
</head>
<body>
<section id="register_page" data-role="page" data-theme="b">
<div data-role="content">
<form id="foo" method="get" action="">
<fieldset data-role="fieldcontain">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="Chris" placeholder="Username"/>
</fieldset>
<fieldset class="ui-grid-a"><input type="submit" value="Send" /></fieldset>
</form>
</div>
<div id="section1">SECTION</div>
</section>
</body>
</html>
testURLd.php
<?php
header("content-type: application/json");
$user = $_GET['username'];
$rtnjsonobj->success = "true";
$rtnjsonobj->user = $user;
$rtnjsonobj->message = "Stored User: " . $user;
echo $_GET['callback']. '('. json_encode($rtnjsonobj) . ')';
?>
When you use the submit() method, but fire an ajax call, you aren't prohibiting the form from submitting.
Add a return false; to the end of the $("#foo").submit method. This will prohibit the page from reloading onclick.
Use pageinit instead of document ready..
check this link..
http://jquerymobile.com/test/docs/api/events.html
try this one..
$( document ).delegate("#register_page" ,"pageinit", function() {
$("#foo").submit(function(event) {
event.preventDefault();
var $form = $(this),
$inputs = $form.find("input, select, button, textarea"),
serializedData = $form.serialize();
var postData = serializedData;
var urlStr = "http://www.fohost.co/testURLd.php?";
alert (urlStr + encodeURI(postData));
$.ajax({
url: urlStr,
data: encodeURI(postData),
dataType: "jsonp",
success: function(data){
alert("SUCCESS callback before HTML update: " + data.message);
$('#section1').html("SECTION 1 - " + data.message);
}
});
});
});

Why Ajax Jquery form click not working vs div that works?

Ajax Jquery form not working vs div why its happen and how can i fix my error?
view.html-Code with form
not working
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
</head>
<body>
<form id="parse-form" action="#" method="post">
<button type="submit" id="submit-html">submit ajax request without parameters</button>
</form>
<div>array values: <div id="array-values"></div></div>
<script type="text/javascript">
$(document).ready(function() {
$('#submit-html').click(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType:'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function (i, elem) {
$('#array-values').append('<div>'+elem+'</div>');
});
}
});
});
});
</script>
</body>
</html>
view.html -form replaced by div
working
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
</head>
<body>
<div id="parse-form">
<button type="submit" id="submit-html">submit ajax request without parameters</button>
</div>
<div>array values: <div id="array-values"></div></div>
<script type="text/javascript">
$(document).ready(function() {
$('#submit-html').click(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType:'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function (i, elem) {
$('#array-values').append('<div>'+elem+'</div>');
});
}
});
});
});
</script>
</body>
</html>
controller.php -simple php file that return json array:
<?php
$arr=array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>
Thanks
The form has a default action with a type="submit" button, which is submitting, so you'll need to stop that from happening by adding return false or event.preventDefault() , like this:
$(document).ready(function() {
$('#submit-html').click(function(e) {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType:'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function (i, elem) {
$('#array-values').append('<div>'+elem+'</div>');
});
}
});
return false;
//or e.preventDefault();
});
});
Without this, the form is submitting as it normally would with no JavaScript, leaving the page. So effectively it's doing a refresh, instead of AJAX submitting your form (which doesn't have time to complete...because you left :)
An element of type=submit inside a <form> will perform the form request when clicked on.
You need to abort the default behavior by running event.preventDefault() inside the click callback.
My guess is that the form is submitting and refreshing the page before the ajax has a chance to respond.
Try putting return false; at the end of the click handler.
$('#submit-html').click(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType: 'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function(i, elem) {
$('#array-values').append('<div>' + elem + '</div>');
});
}
});
return false;
});
Of course you'll have the same issue if the user hits Enter in one of the fields. Unless you're preventing the Enter key from submitting the form, you may want to the handle the event using the submit() handler.
$('#parse-form').submit(function() {
$.ajax({
url: 'controller.php',
type: 'POST',
dataType: 'json',
success: function(data) {
alert("response begin");
alert(data);
$.each(data, function(i, elem) {
$('#array-values').append('<div>' + elem + '</div>');
});
}
});
return false;
});
Try using submit() http://api.jquery.com/submit/ , this should work with keyboard events as well as clicks. You can use serialize() to get any form data into the ajax objects data variable.

Resources