I am getting an error when I post my ajax call to the reCAPTCHA verification API. I get a "ReferenceError: success is not defined" error on correct input and "ReferenceError: incorrect is not defined" on incorrect insertion of the CAPTCHA. Here is my code:
$.ajax({
type: 'POST',
contentType: "application/json",
dataType: 'jsonp',
url: "http://www.google.com/recaptcha/api/verify",
data: {
privatekey: 'XXXXXXXXXXXXXXXXX',
remoteip: document.getElementById("ipaddress").innerHTML,
challenge: Recaptcha.get_challenge(),
response: Recaptcha.get_response()
},
async: false,
success: function (resp) {
if (resp == "false") {
alert('Please enter captcha words correctly');
reloadRecaptcha();
}
else {
alert('Yeah');
}
}
});
Well I solved my own problem by sending the post data to the page controller.
JS:
$.ajax({
type: 'GET',
contentType: "application/json",
url: "/Register/veriCAPTCHA",
data: {
privateKey: 'XXXXXXXXXXXXXXXX',
remoteip: document.getElementById("ipaddress").innerHTML,
challenge: Recaptcha.get_challenge(),
response: Recaptcha.get_response()
},
success: function (data) {
if (data == false) {
valiCAPTCHA = false;
ALERT("The CAPTCHA code you entered is invalid. Please try again.");
Recaptcha.reload();
}
else {
valiCAPTCHA = true;
}
}
});
CS controller:
[HttpGet]
public JsonResult veriCAPTCHA(string privateKey, string remoteip, string challenge, string response)
{
string postData = String.Format("privatekey={0}&remoteip={1}&challenge={2}&response={3}",
privateKey, remoteip,
challenge, response);
JsonResult result = new JsonResult();
byte[] postDataBuffer = System.Text.Encoding.ASCII.GetBytes(postData);
Uri serviceUri = new Uri("http://api-verify.recaptcha.net/verify", UriKind.Absolute);
try
{
HttpWebRequest webRequest = (HttpWebRequest)System.Net.WebRequest.Create(serviceUri);
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postDataBuffer.Length;
webRequest.Method = "POST";
//incase you are using a proxy server
IWebProxy proxy = WebRequest.GetSystemWebProxy();
proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
webRequest.Proxy = proxy;
Stream requestStream = webRequest.GetRequestStream();
requestStream.Write(postDataBuffer, 0, postDataBuffer.Length);
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
string jsonResponse = string.Empty;
using (StreamReader sr = new StreamReader(webResponse.GetResponseStream()))
jsonResponse = sr.ReadToEnd();
string[] tokens = jsonResponse.Split(new char[] { '\n' });
if (tokens.Length == 2)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
else
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
Related
I have been having a lot of trouble sending a post request to a server. It expects a form data type.
This is the error I get after my input.
`image: [The image must be an image.]}}
Most of my data are strings except for an int and a file Image which is selected from gallery by user.
This is my code:
dart code
if(_image!=null){
setState(() {
_isLoading = true;
});
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
var uri = NetworkUtils.host +
AuthUtils.updateSessionRequest;
Map<String, String> data = {"_method": "PATCH",
"first_name": widget.first_name,
"last_name": widget.last_name,
"phone": widget.phone,
"industry":widget.industry,
"country": widget.country,
"state": widget.state,
"fav_quote": widget.fav_quote,
"bio_interest": widget.bio_text,
"terms": "1",
"company": widget.company,
"position": widget.job_position,
"linked_in":widget.linkedin_profile,
"institution": widget.institution,
"degree": widget.degree,
"preference[0]": widget.industry};
String authToken = sharedPreferences.getString("token");
try {
final response = await http.post(
uri,
body: data,
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer ' + authToken,
},
);
final responseJson = json.decode(response.body);
print(responseJson.toString());
if (response.statusCode == 200 || response.statusCode == 201) {
//upload image to server after success response
uploadImage(_image);
NetworkUtils.showToast("Profile successfully update!");
});
} else{
setState(() {
_isLoading = false;
});
NetworkUtils.showSnackBar(_scaffoldKey, 'An error occurred. Please try again');
}
return responseJson;
} catch (exception) {
print(exception.toString());
setState(() {
_isLoading = false;
});
NetworkUtils.showSnackBar(_scaffoldKey, 'An error occurred. Please try again');
}
}
uploadImage(File image) async{
var request = http.MultipartRequest(
"POST",
Uri.parse(NetworkUtils.host +
AuthUtils.endPointUpdateProfile));
request.files.add(await http.MultipartFile.fromPath(
'image',
image.path,
));
try {
var streamedResponse = await request.send();
var response = http.Response.fromStream(streamedResponse);
return response;
} catch (e) {
rethrow;
}
}
}
You need to pass your image like this
request.files.add(await http.MultipartFile.fromPath(
'image',
_image,
));
Here an example how to pass File and String using http
var request = http.MultipartRequest(
"POST",
Uri.parse("http://....."));
request.fields['first_name'] = widget.first_name;
request.fields['last_name'] = widget.last_name;
.....
request.files.add(await http.MultipartFile.fromPath(
'image',
path,
));
try {
var streamedResponse = await request.send();
var response = http.Response.fromStream(streamedResponse);
return response;
} catch (e) {
rethrow;
}
From the above only, with a little modification
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void executePostMethod(String title) async {
var request = http.MultipartRequest("POST", Uri.parse("https://localhost:44377/API/GetStateList"));
request.fields['CountryID'] = "1";
// .....
//request.files.add(await http.MultipartFile.fromPath('image',path,)
//);
// send request to upload image
await request.send().then((response) async {
//print(response);
response.stream.transform(utf8.decoder).listen((value) async {
print(value);
// print("ResponseVal: $value");
if (response.statusCode == 200) {
var imgUploadData = json.decode(value);
print(imgUploadData);
} else {
throw Exception("Faild to Load!");
}
});
}).catchError((e) {
print(e);
});
}
I have some problems with an ajax call.
Here is the function:
function jsFunction(value) {
var selectedCompany = document.getElementById("CompanyId");
var selectedCompanyId = selectedCompany.options[selectedCompany.selectedIndex].value;
$.ajax({
type: "POST",
data: { companyId: selectedCompanyId, supplierId: value },
url: "#Url.Action("CheckContract", "PaidWork")",
dataType: 'json',
traditional: true,
contentType: 'application/json; charset=utf-8',
processData: false,
success: function (response) {
if (response != null && response.success) {
document.getElementById("errorMessage").style.display = 'hidden';
alert(response.responseText);
} else {
// DoSomethingElse()
document.getElementById("errorMessage").style.display = 'visible';
alert(response.responseText);
}
},
error: function (response) {
alert("error!"); //
}
});
}
This is the div for the message
<div id="errorMessage" style="display:none"><strong class="alert-danger">#ViewBag.MessageContractNotExist</strong></div>
In my view I have a message which I want to display or not, depends on what response Json send me from controller.
This is the method in controller:
public ActionResult CheckContract(int companyId, int supplierId)
{
bool result = true;
if (!spService.ContractExists(companyId, supplierId, ContractType.SupplierSilviPrio))
{
result = false;
}
if(!result)
{
ViewBag.MessageContractNotExist = "Not exist!!!";
return Json(new { success = false, responseText = "The attached file is not supported." }, JsonRequestBehavior.AllowGet);
}
return Json(new { success = true, responseText = "Your message successfuly sent!" }, JsonRequestBehavior.AllowGet);
}
The problem is that I keep getting this error: invalid json primitive object
Can you please help me what I miss here? Thanks
I am trying to use a Json request to get data from a login screen. But no matter if the login request is valid or not, I am always getting returned to my home screen. I think I am checking the result incorrectly?
Basically, in my Twitter-Bootstrap enabled site, I have a modal popup that takes the user to a login form.
The values are passed via a json query, to my MVC4 controller. A breakpoint shows I am getting good data.
Here's the scrip that sends the data:
<script type="text/javascript">
$(document).ready(function () {
$('.btnSubmit').on('click', function () {
var data = { username: $('.txtUsername').val(), password: $('.txtPassword').val(), rememberMe: $('.cbRemember').val() };
$.ajax({
url: '#Url.Action("LoginUser", "User")',
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
cache: false,
async: true,
success: function (result) {
if (result['success'] == 'true') {
alert("true");
window.location = '#Url.Action("Index", "Home")';
} else {
alert("BAD");
}
},
error: function () {
alert("Error in input");
}
});
});
});
</script>
And here is the controller method:
[HttpPost]
public JsonResult LoginUser(string username, string password, string rememberMe)
{
string success = "false";
string message = "Not set";
if (username == string.Empty || password == string.Empty)
{
success = "false";
message = "Invalid Username/Password";
}
else
{
if (ModelState.IsValid)
{
var us = new UserService();
var reply = us.Authenticate(username, Security.EncryptText(password));
if (reply == 0)
{
success = "false";
message = "Invalid Username/Password";
}
if (reply != 0)
{
var p = us.GetPerson(reply);
FormsAuthentication.SetAuthCookie(p.Id.ToString(CultureInfo.InvariantCulture), rememberMe == "on");
Session["UserDisplay"] = string.Format("{0} {1} - ({2})", p.Firstname, p.Surname, p.Email);
success = "true";
message = "Login Success";
}
}
}
var result = new { Success = success, Message = message };
var r = new JsonResult
{
Data = result
};
return r;
}
However, I always get the 'BAD' alert. Never the 'true'.
Can I check the result the way I am? Am I attempting to do this the right way? Basically, if I get 'BAD', I don't want the screen to refresh. Infact, I will want to show a message saying what ever is in the 'message' parameter.
Edit: I think 'result' is NULL.
From mvc 4 action:
[HttpPost]
public ActionResult DoStuff(string str)
{
// Do some things
Response.ContentType = "application/json;charset=utf-8";
Response.StatusCode = someCondition == true ? HttpStatusCode.OK : HttpStatusCode.NotFound);
Response.TrySkipIisCustomErrors = true;
return Json(
new {
object1 = 1,
object2 = someArray[0],
object3 = someArray[1],
object4 = someValue == 4 ? 1 : 0
}
);
}
In jquery ajax:
ajax({
url: '/Ctrler/DoStuff/',
data: { str: someString },
type: 'POST',
dataType: 'json'
}).then(function (data) {
var _response = $.parseJSON(data);
}, function (data) {
var _response = $.parseJSON(data.responseText);
});
data.responseText is empty ("") and statusText is "error". It is not always happening. I have observed that it is happening randomly. Why?
Your data is already being converted to an object from JSON, so you do not need to parse it again. Try this:
ajax({
url: '/Ctrler/DoStuff/',
data: { str: someString },
type: 'POST',
dataType: 'json'
}).then(function (data) {
// use data here...
alert(data.object1);
}, function () {
alert('request failed');
});
I have the following web service;
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
I am pointing to the latest jquery library.
<script type="text/JavaScript" src="Scripts/jquery-1.6.4.js"></script>
I have this jQuery method;
$.ajax({
type: "POST",
url: "../Service/AFARService.asmx/HelloWorld",
// this._baseURL + method,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: fnSuccess,
error: fnError,
crossDomain: true,
dataFilter: function (data) {
var response;
if (typeof (JSON) !== "undefined" && typeof (JSON.parse) === "function")
response = JSON.parse(data);
else
response = val("(" + data + ")");
if (response.hasOwnProperty("d"))
return response.d;
else
return response;
}
});
When I execute I get a "No transport" error returned. I added crossDomain: true still no success.
Thanks in advance
BB
to enable cross domain calls, you can try
jQuery.support.cors = true;
if this doesn't works you can go through(JSONP) :
http://www.west-wind.com/weblog/posts/2007/Jul/04/JSONP-for-crosssite-Callbacks
https://en.wikipedia.org/wiki/JSON
http://remysharp.com/2007/10/08/what-is-jsonp/
you can follow any of these
try using
url: "AFARService.asmx/HelloWorld",
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string HelloWorld()
{
return "Hello World";
}