I am using google recaptcha and what I am trying to do is put the response into a observable and then send it to the backend server. I am trying but I am failing. Here are the codes.
<div class="form-group">
<div class="col-sm-8">
<div class="g-recaptcha" data-sitekey="############"></div>
</div>
</div>
Next piece of code is in the js file with knockout
self.recaptchaCode = ko.observable($('.g-recaptcha-response').val()); // Does not work
Here is the ajax sending to the backend
$.ajax({
type: 'POST',
url: BASEURL + 'index.php/login/loginUsingAjax/' + auth,
contentType: 'application/json; charset=utf-8',
data: ko.toJSON({
email : self.eMail(),
password : self.passWord(),
recaptcha : self.recaptchaCode()
})
})
I guess I am not getting the right way to get the response into the observable
This line:
self.recaptchaCode = ko.observable($('.g-recaptcha-response').val());
Sets the observable with the value your element holds at the time the observable is created. When you request the observable's value (self.recaptchaCode()), it is not re-evaluated; you receive a cached response.
This means your code will only work if the element's value is available at the time you instantiate your viewmodel. Knockout cannot magically watch a non data-bound DOM element.
I'd suggest creating a method instead of an observable:
self.getRecaptchaCode = function() {
return $('.g-recaptcha-response').val();
};
Better would be to create a value binding on the element, but I'm not sure if you have access to the .g part of the DOM... In that case, you could use a "real" knockout approach:
<input data-bind="value: recaptchaCode">
With self.recaptchaCode = ko.observable() in your viewmodel.
Related
I want to pass select2 multiple select values to database using ajax in my laravel project. Before using ajax, I passed the values using get requests. All values are shows as url parameters, but when it checks with a request -> all() it gets the token value and the last value only, other values are not shown. Why are some other values missing? How can I get all values? I also want to store them in a database. Additionally how can I send those values using ajax.
full URL example:
http://127.0.0.1:8000/send_services?_token=oo6hLRavd6mPczbsgjwQ8RXSNUohhktO5NyNGxCN&services_select=6&services_select=8&services_select=7
Here is my ajax request(send data using ajax instead of normal form submission):
$('#submit-service').click( function() {
var terms = $("#service-select").val();
$.ajax({
type: "GET",
url: '/send_services',
data: terms
})
.done(function(result) {
console.log(result);
})
.fail(function(error) {
console.log(error);
});
});
I want to send this data mainly using ajax.
you just need to add array in name attribute of select tag
for e.g
<select multiple="" name="multiple_values[]" id="service-select">
Sending values using ajax and GET is the same, you simply use the URL:
$.ajax({
type: "GET",
url: '/send_services?data1=value1&data2=value2&data3=value3'
});
I've got a page that on $(document).ready, calls a javascript function that creates some input controls dynamically based on context of page request via a ajax call to the server.
I need to set one of the dynamically created controls (input checkbox) to be checked by default.
I've tried setting it via $(#id).prop('checked', true); after the call to the server but it does not work. My guess is that the field does not exist yet...
How can I modify a html control dynamically created from an ajax call?
Instead of using prop to have it checked initially, set checked in the HTML.
<input type="checkbox" id="#" value="sample" checked>
This can be done static or dynamically. Simply add checked as part of your dynamic generation. Then you bring in prop to suit your needs.
You can use attr and removeAttr methods to check/uncheck a checkbox/radio input.
// to check a checkbox or radio button
$(selector).attr("checked","checked");
// to uncheck a checkbox (radio button will be cleared on another check)
$(selector).removeAttr("checked");
and if you're creating the input from AJAX, you can put this on the AJAX success or complete function after the DOM is updated. But #Aaron is right, setting the value on generation on the server side is more effective.
The answers provided are good and could work but not with my problem. This is because the javascript that generates these html elements is a abstracted file that generates html input controls for many different applications. I can't modify that file to specifically check a checkbox for one case.
What I did was, inside of this generic javascript file, call a setDefaults() method IF IT EXISTS in the current context. So the callers of this script can choose to implement a setDefaults() that will be called by the generic script, after the html has been generated.
function initReport(reportID) {
//request the data needed to create the dynamic html from the server:
$.ajax({
type: "GET",
url: "/report.aspx/GetReportDetails?reportID=" + reportID,
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (result) {
reportFormData = JSON.parse(result.d);
//request our generic html template:
$.ajax({
type: "GET",
url: "/assets/modules/report/Templates/Form.html"
}).done(function (result) {
$("#Form").html(result);
//generate html from server data:
buildViewModel(reportFormData);
buildPage(reportFormData);
kendo.bind($("#Form"), viewModel);
//call "setDefaults" function only if it has been defined (in the current report template)
if (typeof setDefaults === "function")
{
setDefaults();
}
});
}).fail(function (jqXHR, textStatus, err) {
console.log("An error has occurred: " + err);
});
...
}
I am learning Angluarjs's $resource. I set a button on HTML for deleting a record from a json file,and hope to delete one record from testForm.json file. Unfortunately, I failed to do so and can't solve the problem.
The codes are here: my Angularjs code
The deleting function in controller codes is shown as follows
$scope.deleteRecord = function () {
var id = 1;
var arecord = new singleResource();
arecord.$get({userId:id},function () {
$log.info(arecord);
arecord.$delete();
});
The HTML part of the deleting function is shown here:
<div class="form-group">
<div class="col-sm-6 col-sm-push-2">
<button type="button" class="btn btn-primary" ng-click="deleteRecord()">Delete information</button>
</div>
</div>
"$scope.deleteRecord" is the function that when clicking the Delete information button, the record with id=1 in json file should be removed. The error says:"DELETE http://localhost:3000/contactInfo 404 (Not Found) :3000/contactInfo:1 ", while the "arecord" is shown as an object in the log "m {email: "333#333", password: 321, method: "Internet", id: 1, $promise: undefined…}", which should be fine.
$http
$http.get('/someUrl', config).then(successCallback, errorCallback);
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
$http is built into Angular, so there’s no need for the extra overhead of loading in an external dependency. $http is good for quick
retrieval of server-side data that doesn’t really need any specific
structure or complex behaviors. It’s probably best injected directly
into your controllers for simplicity’s sake.
$resource
The action methods on the class object or instance object can be invoked >with the following parameters:
HTTP GET "class" actions: Resource.action([parameters], [success], [error])
non-GET "class" actions: Resource.action([parameters], postData, [success], [error])
$resouce is good for situations that are slightly more complex than $http. It’s good when you have pretty structured data, but you
plan to do most of your crunching, relationships, and other operations
on the server side before delivering the API response. $resource
doesn’t let you do much once you get the data into your JavaScript
app, so you should deliver it to the app in its final state and make
more REST calls when you need to manipulate or look at it from a
different angle.
Alternatively you could use: restangular https://github.com/mgonto/restangular
Restangular is a perfect option for complex operations on the client side. It lets you easily attach custom behaviors and interact
with your data in much the same way as other model paradigms you’ve
used in the past.
Angularjs guide: https://docs.angularjs.org/api/ng/service/$http#delete
try with the delete method:
$scope.deleteRecord = function () {
var id = 1;
var arecord = new singleResource();
arecord.$delete({userId:id},function () {
$log.info(arecord);
//arecord.$delete();
});
or
$http({
method: 'DELETE',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
I hope it helps.
What is the bestHi everyone, a MVC3 newbie here! please take a look at these:
in my View page, i have there:
<div id = "AccounStatusDiv" class="display-field">
#Html.DisplayFor(m => m.AccountStatus)
<input id="btnBool" type="button" class="btnGrid ActStatBtn" value="#(Model.AccountStatus ? "Deactivate" : "Activate")" onclick="ChangeStatus()"/>
</div>
and a script:
<script type="text/javascript">
function ChangeStatus() {
$.post('#Url.Action("SetAccountStatus", "User")',
{ UserName: "#(Model.UserName)",
accountStatus: "#(Model.AccountStatus)" });
// change the display of the AccounStatusDiv elements, or maybe just reload the div element if possible. is it?
}
</script>
while in my Display Template, i have there:
<div id = "AccountStatusDiv" style="display:inline-block;">
<img src="#Html.Custom().ResolveImage((bool)Model ? imgPositive : imgNegative)" alt="#Model" />
<label> #ResourceManager.Localize(resource, display)</label>
</div>
in the controller:
public ActionResult SetAccountStatus(string userName, bool accountStatus)
{
SecurityManager.GetMembershipProvider().SetStatus(userName, !accountStatus);
return AjaxResult.JsonRedirect("/User/ViewUser?username=" + userName);
}
The results are shown only after I reload the page.
I want to display the updated img, label and btnBool elements right after clicking the btnBool without reloading the whole page. What is the best way in such case?
Please post your code suggestions, it would be a great help for me!
Thanks in advance!
You're only using $.post() to send data (request) to the server. AJAX can be two-fold: send a request, and receive the corresponding response. In your code, you're not receiving data back (or, at least, making the necessary arrangements so that you are).
If the SetAccountStatus action of your UserController is set to return some data back (maybe through return Json(), or similar), you can modify the $.post() call to receive it, and have your Javascript react accordingly using a callback function.
var data = {
UserName: "#Model.UserName",
accountStatus: "#Model.AccountStatus"
};
var call = $.post(
'#Url.Action("SetAccountStatus", "User")',
data
);
// set the success callback here
call.success(function (m) {
// the [m] variable contains the data returned by the server
// during the resolution of your call
// this will be called when your AJAX call succeeds,
// and you can use this opportunity to update the HTML DOM with new data
});
this is to event click in button and without refresh page
$("#btnBool").click(function(e){
e.preventDefault();
//to do your code, you can use `$.ajax` to request and get response from server
$.ajax({
url: '#Url.Action("SetAccountStatus", "User")',
type:"GET",
dataType: 'json',
data: { UserName: "#(Model.UserName)",accountStatus: "#(Model.AccountStatus)" },
async:'true',
success:function (data) {
alert(data);
//success to parsing json if you data type of your response is json
}
});
}
you can use web service to send request and get response from server , and to request,get response from server you can use $.ajax() in jquery http://api.jquery.com/jQuery.ajax/
I am struggling with the post() method.
I've been reading several posts on here and the jquery forums, and just trying to get a simple piece of code working is proving difficult. My ultimate goal is to pass a div #exportData and all it's children to test.php.
I started with:
$.post("ajax/test.php", $("body").html());
To my mind this should return the entire contents of the current page to test.php (unless test.php requires a holding div or element to receive the content). Currently it only returns the blank page.
I then tried looking at the parameters for post() if I need to manipulate these:
$.ajax({
type: 'POST',
url: ajax/test.php,
data: data,
success: success,
dataType: dataType
});
Also declared a variable:
var data = {
html: #exportData
};
That bit failed of course. I don't know how to define the data in the parameters, or if this is the right place to do it.
Although I would have thought if:
$.post("ajax/test.php", $("body").html());
would have worked then presumably I can substitute "body" for any class, id or selector I like.
Also does the submit button need certain parameters to tie it to the post function. At the moment it is purely:
<input type="submit" id="submit" value="send" name="submit">
Sorry this is such a basic question.
You could do
var html = $("body").html();
var data = {
html: html
};
$.post("ajax/test.php", data);
as the second parameter of $.post() is an object wich contains the data you want to send to the server.
To send the data you could do:
<input type="submit" id="submit" value="send" name="submit">
js
$('input#submit').click(function(e){
//prevent submitting the form (if there is a form)
e.preventDefault();
var html = $("body").html();
var data = {
html: html
};
$.post("ajax/test.php", data);
});
server side you receive the data
$html = $_POST['html']
$.post() expects an object to be passed to transfert data along with the post request:
jQuery.post( url [, data] [, success(data, textStatus, jqXHR)] [, dataType] )
url: A string containing the URL to which the request is sent.
data: A map or string that is sent to the server with the request.
success(data, textStatus, jqXHR): A callback function that is executed if the request succeeds.
dataType: The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).
var content = $ ('body').html(),
data = { content: content };
$.post('ajax/test.php', data);
Sending html in the post doesn't sound like a good idea. All elements type of input or select will be empty in the Html. You would need to use .serialize in order to get the values.
$('#submit').submit(function () {
$.ajax({
type: 'POST',
url: 'ajax/test.php',
data: {
html: $('body').html()
}
});
});