Call remote asmx service by JQuery always fail - ajax

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

Related

Laravel Return Response From Ajax

I am trying to learn Laravel9. For this I have Created a Controller, a model and blade view file. Below is my vatprofile.blade.php file code
<script type="text/javascript" src="https://code.jquery.com/jquery-2.0.2.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "get",
url: "/vatprofile",
dataType: "json",
success: function (response) {
alert(response);
}
});
});
</script>
And this is my Rout,
Route::get('/vatprofile',
[VatProfileController::class,'index']);
And Below is my Controller Function
public function index(){
return response()->json(['success'=>'Record is successfully added']);
}
It is not Giving Error, Not printing out any response. Only the Blank Page is Showing up. Can you Correct me Pls
Please try this:
<script type="text/javascript" src="https://code.jquery.com/jquery-2.0.2.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "get",
url: "{{ url('vatprofile') }}",
dataType: "json",
success: function (response) {
alert(response);
}
});
});
</script>

Form validation in codeigniter when ajax used to form submit

Form submit is not happened in this scenario..
$.ajax({
type: "POST",
async: false,
url: base_url+"register/registration_val",
data: "register_first_name="+first_name,
success: function(data){
$('#inferiz').html(data);
},
error: function(){
alert('error');
}
In your view you can add this:
<script type="text/javascript">
var base_url = "<?php print base_url(); ?>";
</script>
Plus try to alert and see the value of final url in ajax i.e alert(url);
Try adding a id to the firstname input
<script type="text/javascript">
$(document).on('submit','#form-reg',function(){ // #form-reg is id on form open tag
$.ajax({
url: "<?php echo base_url('register/registration_val');?>",
type: 'POST',
data: {
firstname: $('#firstname').val(),
},
dataType: 'html', // I perfer to use json
success: function(data){
$('#inferiz').html(data);
},
error: function(){
alert('error');
}
}
});
});
</script>
I would use dataType: json much easier that way to get data from controller
You used data: "register_first_name="+first_name, it's not correct. Correction is data: {register_first_name:first_name},
base_url like this var base_url = <?php echo base_url(); ?>
So, Bellow final code :
<script type="text/javascript">
jQuery(document).ready(function ($) {
var base_url = <?php echo base_url(); ?>
$.ajax({
url: base_url+"register/registration_val", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: {register_first_name:first_name}, // Data sent to server, a set of key/value pairs representing form fields and values
contentType: false, // The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
}).done(function (data) {
$('#inferiz').html(data);
}).fail(function (data) {
console.log('failed');
});
}(jQuery));
</script>
Please verify your view part that whether you provided id same as in ajax function.
view part:
<form id="form-reg">
<input name="firstname" id="firstname" type="text" required placeholder="Enter firstname " >
<span id="name_validation" class="text-danger"></span>
<button name="submit" id="submit_button" onClick="myFunction();" >submit</button>
</form>
Then correct the base url path which has to be given inside php tag.
function myFunction() {
$.ajax({
url: "<?php echo base_url();?>register/registration_val",
type: "POST",
data:'firstname='+$("#firstname").val(),
success: function(msg)
{
alert('done..!');
}
});
}

Ajax function not triggering

Why my 'Ajax' function is not triggering when changing the 'state' please help. even the 'console' is not showing the value. When i comment Ajax function I am getting the stateID in console
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(document).on("change", "#state", function(){
var stateID = $(this).val();
console.log('value of StateID'+stateID);
$.ajax({
url:"user/getCity"
async: false,
type: "POST",
data: {stateID,stateID},
dataType: "html",
success: function(data) {
//$('#city').html(data);
console.log(data);
}
})
});
});

SOAP webservice call by ajax in phonegap error

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.

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