I have a WSDL web service http://portal.strongtech.com/i/services/ivos?wsdl and I want to send request to functions using AJAX. I know how to send request using AJAX or JQuery though I am not sure how to write SOAP envelope for the function I want to request for.
Can you please help me writing SOAP envelop for the login function from the given service URL? That would be really appreciated.
check call-soap-xm-web-services-with-jquery-ajax and jQuery Plugin SOAP
here is an example from http://www.icloud.com/wiki/index.php/Getting_started_-_jquery_ajax_guide
<html>
<head>
<script type="text/javascript" src="http://os.icloud.com/live/jqueryloader.js"></script>
<script type="text/javascript">
function printResult(doc, status, xhr) {
var p = document.getElementById("output");
if( status == "error" ) {
p.innerHTML = doc.responseText.replace(/</g, "<");
login("/", "/"); // reset username
} else {
p.innerHTML = xhr.responseText.replace(/</g, "<");
}
}
function createSoapEnvelope(contents) {
return '<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ' +
'SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' +
'<SOAP-ENV:Body>' + contents + '</SOAP-ENV:Body></SOAP-ENV:Envelope>';
}
function login(username, password, callback, errback) {
icloud.ajax({
type: "POST",
async: true,
cache: false,
contentType: "text/xml; charset=utf-8",
dataType: "xml",
processData: false,
url: "http://os.icloud.com/v1/",
username: username,
password: password,
data: createSoapEnvelope("<login/>"),
beforeSend: function(xhr) {
xhr.setRequestHeader("SOAPAction", "login");
},
success: callback,
error: errback
});
}
function buttonClicked() {
login(document.getElementById("username").value, document.getElementById("password").value, printResult, printResult);
}
initIcloudAPI();
</script>
</head>
<body>
<h2>Login example</h2>
username:<input type="text" name="username" id="username"/>
password:<input type="password" name="password" id="password"/>
<input type="submit" name="login" value="Login" onclick="buttonClicked()"/>
<p id="output"/>
</body>
</html>
Related
I'm trying to convert some C# to JavaScript as I'm building a JavaScript application to do Computer Vision!
The C# "Quick start" is here, https://learn.microsoft.com/nb-no/azure/cognitive-services/Computer-vision/QuickStarts/CSharp-analyze
What I want to do with the endpoint is to send an image to it by HTTP POST.
And my code so far is:
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script>
$(function () {
});
$(':button').on('click', function () {
var uriBase = "https://westcentralus.api.cognitive.microsoft.com/vision/v1.0";
var authorizationToken = "-";
var requestParameters = "visualFeatures=Categories,Description,Color";
var computerVisionEndpoint = uriBase + "?" + requestParameters;
$.ajax({
url: computerVisionEndpoint,
type: 'POST',
beforeSend: function (request) {
request.setRequestHeader("Content-Type", "application/octet-stream");
request.setRequestHeader("Ocp-Apim-Subscription-Key", authorizationToken);
},
data: new FormData($('form')[0]),
}).done(function (data) {
console.log("DONE!");
debugger;
}).fail(function (xhr, status, error) {
console.log("FAIL!");
debugger;
});
});
</script>
The problem here is that I'm getting error "jquery-3.4.1.min.js:2 Uncaught TypeError: Illegal invocation".
you have to add processData: false to your ajax-request.
I am trying to implement the newest ReCaptcha (aka "invisible" ReCaptcha) within an form using jQuery and an "ajax" request.
ReCaptcha documentation: https://developers.google.com/recaptcha/docs/invisible
My form:
<form id="myForm" >
<input type="email" name="email" /><br />
<input type="password" name="password" /><br/>
<!--<input type="submit" value="log in" />-->
<button class="g-recaptcha" data-sitekey="6LdK..." data-callback="onSubmit">log in</button>
</form>
<div id="status"></div>
My javascript (jQuery):
<script>
function onSubmit(token){
document.getElementById("myForm").submit();
}
$(document).ready(function(){
$("#myForm").submit(function(event){
event.preventDefault();
var datas = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "test.php",
data: datas,
dataType: "json",
beforeSend: function(){
$("#status").html("logging in...");
},
success: function(response){
$("#status").html(response.text);
if(response.type=="success"){
window.location.replace("/myaccount");
}
},
error: function(){
$("#status").html("Failed.");
}
});
});
});
</script>
ReCaptcha requires to set a "data-callback", which I am not sure how to bind with my already existing ".submit(function(event)" function.
My "onSubmit()" trick did not work, it ignores the "ajax" and refreshes the page.
How do I send the "g-recaptcha-response" value within my "datas" variable to POST it to test.php?
So here is how I solved it after digging further in Invisible reCAPTCHA's doc, and learning a bit of jQuery obviously since I was not very familiar with JS (cool stuff):
My head tag with the javascript (and a bit of css to remove the ugly Google badge):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit&hl=fr" async defer></script>
<style>
.grecaptcha-badge{
display:none;
}
</style>
<script>
var onloadCallback = function(){
grecaptcha.render("emplacementRecaptcha",{
"sitekey": "YOUR_RECAPTCHA_SITEKEY_HERE",
"badge": "inline",
"type": "image",
"size": "invisible",
"callback": onSubmit
});
};
var onSubmit = function(token){
var userEmail = $("#userEmail").val();
var userPassword = $("#userPassword").val();
var userTfaOtp = $("#userTfaOtp").val();
$.ajax({
type: "POST",
url: location.href,
data:{
userEmail: userEmail,
userPassword: userPassword,
userTfaOtp: userTfaOtp,
userJetonRecaptcha: token
},
dataType: "json",
beforeSend: function(){
$("#statutConnexion").html("Traitement de votre requête d'authentification en cours...");
},
success: function(response){
$("#statutConnexion").html(response.Message);
if(response.Victoire){
$("#formulaireConnexion").slideUp();
window.location.replace("/compte");
}
else{
grecaptcha.reset();
}
},
error: function(){
$("#statutConnexion").html("La communication avec le système d'authentification n'a pas pu être établie. Veuillez réessayer.");
grecaptcha.reset();
}
});
};
function validate(event){
event.preventDefault();
$("#statutConnexion").html("Validation de votre épreuve CAPTCHA en cours...");
grecaptcha.execute();
}
function onload(){
var element = document.getElementById("boutonConnexion");
element.onclick = validate;
}
</script>
HTML:
<div id="formulaireConnexion">
<input type="email" name="userEmail" id="userEmail" placeholder="Courriel" title="Courriel" required="required" /><br />
<input type="password" name="userPassword" id="userPassword" placeholder="Mot de passe" title="Mot de passe" required="required" /><br/>
<input type="text" name="userTfaOtp" id="userTfaOtp" placeholder="Double authentification (optionnelle)" autocomplete="off" pattern="[0-9]{6}" title="Six caractères numériques" maxlength="6" /><br />
<div id="emplacementRecaptcha"></div>
<button id="boutonConnexion">Connexion</button>
</div>
<div id="statutConnexion"></div>
<script>onload();</script>
Let me know if you need the whole PHP as well since it's out of the scope of this question. You will probably need to change "url: location.href," within the JS above since in my case the script rendering the HTML form and the JS and dealing with the POST vars is the same (not great, testing purpose). Basically I just verify the POST vars then finally return a json like:
$jsonVictoire = true; // boolean
$jsonMessage = 'anything you want to tell your visitor'; // string
$return =
json_encode(
array(
'Victoire'=>$jsonVictoire,
'Message'=>$jsonMessage
)
);
die($return);
<script defer>
function onSubmit(token) {
var f = $("#myForm");
$.ajax({
type: "POST",
url: "test.php",
data: f.serialize(),
dataType: "json",
beforeSend: function(){
$("#status").html("logging in...");
},
success: function(response){
$("#status").html(response.text);
if(response.type=="success"){
window.location.replace("/myaccount");
} else {
$("#status").html("Captcha failed.");
}
},
error: function(){
$("#status").html("Failed.");
}
});
}
</script>
In test.php you need to verify captcha on server side:
<?php
if(isset($_POST['g-recaptcha-response'])) {
$result = json_decode(file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret=[YOUR_SECRET_KEY]&response=$_POST["g-recaptcha-response"]&remoteip=$_SERVER["REMOTE_ADDR"]'), TRUE);
if($result['success'] == 1) {
// Captcha ok
} else {
// Captcha failed
}
}
?>
<script src="https://www.google.com/recaptcha/api.js?render=explicit&onload=onScriptLoad" async defer></script>
<div id="login_page" class="g-recaptcha" data-size="invisible" data-sitekey="your sitekey" data-callback="login_page"></div>
<script>
window.onScriptLoad = function () {
// this callback will be called by recaptcah/api.js once its loaded. If we used
// render=explicit as param in script src, then we can explicitly render reCaptcha at this point
// element to "render" invisible captcha in
var htmlEl = document.querySelector('.g-recaptcha');
// option to captcha
var captchaOptions = {
sitekey: 'your site key...',
size: 'invisible',
// reference to an actual function
callback: window.onUserVerified
};
// Only for "invisible" type. if true, will read value from html-element's data-* attribute if its not passed via captchaOptions
var inheritFromDataAttr = true;
// now render
recaptchaId = window.grecaptcha.render(htmlEl, captchaOptions, inheritFromDataAttr);
};
window.onUserVerified = function (token){
Your ajax code....
}
$("#blog_inquiry").click(function(e){
//var gg = grecaptcha.getresponse();
var token = window.grecaptcha.getResponse(recaptchaId);
// if no token, mean user is not validated yet
if (!token) {
window.grecaptcha.execute(recaptchaId);
return;
}
});
</script>`
I am trying to call data from a PHP file where it takes the data entered and tells if it is validated or not. How do you do this in the javascript file using an AJAX call?
$("#PersonForm").submit(function()
{
$.ajax({
url: 'backend.php', type: 'post', data: { act:'validate'},
dataType: 'json',
function(result) {
if($validateData==1){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
}
//});
});
return false;
});
Here is the PHP file
<?php
if ($_REQUEST['act'] == 'validate')
{
$validateData = array();
if (preg_match("/^[A-Za-z]{3,20}$/",$_REQUEST['name'])) $validateData['name'] = 1;
else $validateData['name'] = 0;
if (preg_match("/^[0-9]{10}$/",$_REQUEST['phone'])) $validateData['phone'] = 1;
else $validateData['phone'] = 0;
if (preg_match("/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/",
$_REQUEST['postal'])) $validateData['postal'] = 1;
else $validateData['postal'] = 0;
if (preg_match("/^[0-9]{3} [A-Za-z]{3,10} Street$/",
$_REQUEST['address'])) $validateData['address'] = 1;
else $validateData['address'] = 0;
echo json_encode($validateData);
}
else echo "Should not happen";
?>
HTML file:
<html>
<body>
<h1>Form Validation</h1>
<form id="PersonForm">
Name: <input type="text" id="name" name="name"> <br>
Postal Code: <input type="text" id="postal" name="postal"> <br>
Phone Number: <input type="text" id="phone" name="phone"> <br>
Address: <input type="text" id="address" name="address"> <br>
<input id="sub" type="submit">
</form>
Refresh
<a id="InsertDefault" href="">Insert Default Data</a>
<br>
<ul id="errors"></ul>
<p id="success"></p>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</html>
First, you're not sending the any of the inputs in your data: parameter. So $_REQUEST['name'], $_REQUEST['phone'], etc. won't exist.
Second, you can't access PHP variables in Javascript. The JSON that the PHP echoes at the end will be decoded into the result variable in the success: callback function.
Third, your syntax is wrong, the callback function needs to be in the success: option.
So it should be:
$("#PersonForm").submit(function()
{
$.ajax({
url: 'backend.php',
type: 'post',
data: 'act=validate&' + $(this).serialize(),
dataType: 'json',
success: function(result) {
if(result.name && result.phone && result.post && result.address){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
}
});
return false;
});
You should use the success and error callbacks so that you are waiting for the promise from the ajax call to come back. I am assuming you are trying to figure out how to get to the data that comes back. If you need further assistance with then validating the real data, I can help with that as well.
$.ajax({
url: 'backend.php', type: 'post', data: { act:'validate'},
dataType: 'json',
success: function (data) {
if($validateData==1){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
},
error: function (request, status, error) {
// Error occurred calling API
}
});
This is simple login page created in asp.net but jQuery doesn't work here. I am getting this error again and again, please help me solve this.
This is my HTML markup:
<html>
<body>
<form id="form1" runat="server">
<div>
User Name :<input type="text" name="UserName" placeholder="Enter User Name" /> <br />
Password :<input type="password" name= "Password" placeholder="Enter password" /></br>
<input type="button" value="Login" id="SubmitLogin" />
</div>
</form>
<script type="text/javascript">
$('#SubmitLogin').click(function () {
alert("I am in Submit Button click");
Login_User();
});
Login_User = function () {
postData = {UserName:'UserName1',Password:'Password1'};
debugger;
$.ajax({
//async:'false',
type: 'POST',
url: 'LoginForm.aspx/Login_validate',
datatype: 'json',
data: JSON.stringify({ "dbparameters": postData }),
contentType: 'application/json; charset=utf-8 ',
success: function (outputresult) {
alert("i am in Success " + outputresult + " .");
},
error: function (XMLHttpRequest, status, error) { alert("Error In System : " + status + " " + error); }
})
}
</script>
</body>
</html>
and my code-behind:
[WebMethod]
[ScriptMethod]
public string Login_validate(Dictionary<string, string> dbparameters) {
string UserName, Password;
UserName = dbparameters["UserName"];
Password = dbparameters["Password"];
return UserName + Password + " ";
}
I Have come to an Answer that Data sent in this request is in-coded in Double Cotes, this gives error
data sent as
`{"dbparameters ":{"UserName":"UserName1","Password":"_Password1"}}`
but this should be sent as
{"dbparameters ":{"UserName":UserName1,"Password":_Password1}}
how to do this ? this will solve Internal Server Error.
I have very very little knowledge of javascript but somehow I managed to post form data to a php file.
Now I am facing a little problem, there are some validations on php file, what I want is if there is any validation fails and the php file returns $error = 'Invalid data'; I want this ajax request to simply display the error message.
Or, if it returns no error, or $error = ''; this ajax request redirect to thankyou.php page.
HTML file:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function (e){
$("#frmContact").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "data.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
if (data == 'true') {
window.location.href="thankyou.php";
};
if (data !== 'true') {
$("#status").html(data);
};
},
error: function(){
}
});
}));
});
<form id="frmContact" action="" method="post">
<div id="status"></div>
<div>
<label>Email</label>
<span id="userEmail-info" class="info"></span><br/>
<input type="text" name="userEmail" id="userEmail" class="demoInputBox">
</div>
<div>
<input type="submit" value="Send" class="btnAction" />
</div>
</form>
data.php
<?php
// PHP code above...
//Lets add $error variable for test purpose...
$error = 'Invalid data';
?>
Change only success function like this
success: function(data){
if (data === 'Invalid data') {
$("#status").html(data);
}
else {
window.location.href="thankyou.php";
}
}
and in php you should echo $error
Echo out "Success" if everything goes according to what you wanted in the posted data i.e all validations passed or echo out any specific validation error. The echoed response will be the response according to which our JS will act accordingly.
$(document).ready(function (e){
$("#frmContact").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "data.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false
})
.done(function(response){
if(response=="Success")
window.location.href="thankyou.php";
else
$("#status").html(response);
});
}));
});