I'm getting mad: I'm working with angular js and I don't know how to post data correctly.
I've filled some html input fields, whose values are stored in (ex.) $scope.prodotto, and I must send the json structure of $scope.product to a webservice I've written.
Unfortunately using the inspector, I' can't see anything.
I mean: I've written this:
$scope.salva = function() {
console.log($scope.prodotto);
$http.post('./service/prodotti/create', $scope.prodotto).error(function(data, status, headers, config){
console.log($scope.prodotto);
});
};
Salva is binded to a button. through ng-click argument. When I click the button, "salva" is triggered.
I see that $scope.prodotto is populated with the right values (thanks to console.log), but...the server receives nothing, and the browser doesn't send anything (inspecting the req with chrome's inspector, shows an empty array)
So what am I doing wrong?
Thanks in advance!
I've found the solution.
Unfortunately the variable "$scope.prodotto" has been initialised as an array:
$scope.prodotto = [];
The solution is simple. Initialize it as an object:
$scope.prodotto = {};
That's it.
You are only checking the ajax call if there is an error with your original post. you need to use the success callback like this:
$scope.salva = function() {
console.log($scope.prodotto);
$http.post('./service/prodotti/create', $scope.prodotto)
.success(function(data, status, headers, config){
console.log($scope.prodotto);
});
.error(function(data, status, headers, config){
console.log($scope.prodotto);
});
};
Related
I have some content returned via ajax, and that content contains some links, but if I click them nothing happens (they don't respond to the JS written for them). Then, If i refresh the page, the first time I click, it works, and then it doesn't again.
How can I make it work normally?
This is basically my ajax call:
$('a.add').click(function() {
var data = {
action: 'ADD_PROD'
};
// make the request
$.get(ajax_object.ajax_url, data, function(response) {
// $('#vru_div').html(data);
$('div.left').html(response);
});
// $('div.left').html('<img src=712.gif>');
// alert('code');
return false;
});
The new links won't have any event handlers attached to them.
try using
$('.left').on('click','a',function(){
//your logic
});
How to call the ajax auto complete when particular time?
here this is my code
function auto(x){
x.autocomplete('ajax/getFriends',{
max:500,
width:300,
minChars:2,
autoFill: false,
formatItem: formatItem,
formatResult: formatResult
});
function formatItem(row) {
return row[0];
//return row[0] + " (<strong>id: " + row[1] + "</strong>)";
}
function formatResult(row) {
return row[0].replace(/(<.+?>)/gi, '');
}
$("#comment").result(function(event, data, formatted) {
$("#test1").val(data[1]);
$("#test2").val(data[2]);
});
}
but it says error x.autocomplete is not a function
i am calling the above is like
auto("string");
can any one help me how to solve this one
Thanks in advance
i am not good in english if any mistakes excuse me
I think you are confusing the way jQuery autocomplete works alltogether. It seems to me that you are attaching autocomplete to your string and building up the HTML elements for the suggestions. This is not how the autocomplete functionality works.
What you want to do is attach the autocomplete functionality to your input box. Then whenever something is entered in there the autocomplete function fires automatically on the input. That's just how it's built.
So let's say for instance you have an input box with an ID equal to myAwesomeInputBox in your HTML code:
<input type="text" id="myAwesomeInputBox"/>
To bind autocomplete (with ajax) to this input field just do this in Javascript:
$("#myAwesomeInputBox").autocomplete({
source: function( request, response ) {
// request.term is the input in the textbox, encode for security reasons
var input = encodeURI(request.term);
$.ajax({
// your ajax endpoint
url: 'ajax/getFriends',
// the request method, modify to your actual method
type: 'GET',
// whatever data you want to pass to your endpoint.
// I'm assuming at least the input (with key userInput here)
// and maybe the limit of the elements in the response array
// the server should send back
data: {userInput: input, limit: 500},
// what to do on success (process the response)
success: function(data){
// assuming your ajax endpoint returns a JSON encoded array with the suggestions as a response
var responseArray = $.parseJSON(data);
// pass the decoded response array to the jquery defined response method for autocomplete
response(responseArray);
},
// what to do if the server returns an error
error: function(jqXHR, textStatus, errorThrown){
// pass an empty suggestions array maybe?
response(new Array());
}
}, 'json');
}
});
The tricky part for me was
response(responseArray);
but once you examine it it's quite understandable. You're just passing an array to the jQuery autocomplete handler for further processing.
I'm not sure how previous versions of jQuery handled ajax autocomplete but this is how version 1.8.0 (and up) handles it.
I have several HTML elements (buttons) that fire the same JQuery AJAX request. When the AJAX request returns successfully, I need to make some updates to the HTML element that triggered the AJAX request. I understand how to do this if I were to hardcode the id of the element to update, such as an item with an id of myDiv as shown in the code below, but I am unsure of how to handle a dynamic id that corresponds to the element that triggered the event.
$('body').on(
'click',
'#yt25',
function(){
jQuery.ajax({
'type':'POST',
'data':$("#custom-hazard-form").serialize()+"&ajaxRequest=hazard-form",
'success':function(data) {
$('#myDiv').html('This is the new text'),
}
'url':'#',
'cache':false
});
return false;
});
I figure one option is to send the id of the HTML element that triggered the event as a key-value pair in the ajax request 'data' option and then have it passed back to the client as part of the AJAX response. I could then grab the id and know which HTML element to update. Is that the best way to handle this or am I missing something more obvious? Thanks.
$('body').on(
'click',
'#yt25',
function(){
var _this = this;
jQuery.ajax({
'type':'POST',
'data':$("#custom-hazard-form").serialize()+"&ajaxRequest=hazard-form",
'success':function(data) {
$(_this).html('This is the new text'),
}
'url':'#',
'cache':false
});
return false;
});
You don't need to sent it along with the ajax request.
This is one variation. You can also do this be assinging some classes to the element and get those elements by that class will do.
Here is the problem:
By default jQuery Mobile is using GET requests for all links in the application, so I got this small script to remove it from each link.
$('a').each(function () {
$(this).attr("data-ajax", "false");
});
But I have a pager in which I actually want to use AJAX. The pager link uses HttpPost request for a controller action. So I commented the above jQuery code so that I can actually use AJAX.
The problem is that when I click on the link there are two requests sent out, one is HttpGet - which is the jQuery Mobile AJAX default (which I don't want), and the second one is the HttpPost that I actually want to work. When I have the above jQuery code working, AJAX is turned off completely and it just goes to the URL and reloads the window.
I am using asp.net MVC 3. Thank you
Instead of disabling AJAX-linking, you can hijack clicks on the links and decide whether or not to use $.post():
$(document).delegate('a', 'click', function (event) {
//prevent the default click behavior from occuring
event.preventDefault();
//cache this link and it's href attribute
var $this = $(this),
href = $this.attr('href');
//check to see if this link has the `ajax-post` class
if ($this.hasClass('ajax-post')) {
//split the href attribute by the question mark to get just the query string, then iterate over all the key => value pairs and add them to an object to be added to the `$.post` request
var data = {};
if (href.indexOf('?') > -1) {
var tmp = href.split('?')[1].split('&'),
itmp = [];
for (var i = 0, len = tmp.length; i < len; i++) {
itmp = tmp[i].split('=');
data.[itmp[0]] = itmp[1];
}
}
//send POST request and show loading message
$.mobile.showPageLoadingMsg();
$.post(href, data, function (serverResponse) {
//append the server response to the `body` element (assuming your server-side script is outputting the proper HTML to append to the `body` element)
$('body').append(serverResponse);
//now change to the newly added page and remove the loading message
$.mobile.changePage($('#page-id'));
$.mobile.hidePageLoadingMsg();
});
} else {
$.mobile.changePage(href);
}
});
The above code expects you to add the ajax-post class to any link you want to use the $.post() method.
On a general note, event.preventDefault() is useful to stop any other handling of an event so you can do what you want with the event. If you use event.preventDefault() you must declare event as an argument for the function it's in.
Also .each() isn't necessary in your code:
$('a').attr("data-ajax", "false");
will work just fine.
You can also turn off AJAX-linking globally by binding to the mobileinit event like this:
$(document).bind("mobileinit", function(){
$.mobile.ajaxEnabled = false;
});
Source: http://jquerymobile.com/demos/1.0/docs/api/globalconfig.html
Given so much different options to submit sth to the server, I feel a little confused.
Can someone help me to clear the idea when I should use which and why?
1> $.ajax()
2> $('#myForm').ajaxForm
3> ajaxSubmit
4> $('#myForm').submit
Thank you
I personally prefer creating a function such as submitForm(url,data) that way it can be reused.
Javascript:
function submitForm(t_url,t_data) {
$.ajax({
type: 'POST',
url: t_url,
data: t_data,
success: function(data) {
$('#responseArea').html(data);
}
});
}
HTML:
<form action='javascript: submitForm("whatever.php",$("#whatevervalue").val());' method='POST'> etc etc
edit try this then:
$('#yourForm').submit(function() {
var yourValues = {};
$.each($('#yourForm').serializeArray(), function(i, field) {
yourValues[field.name] = field.value;
});
submitForm('whatever.php',yourvalues);
});
Here is my understanding
$.ajax does the nice ajax way to send data to server without whole page reload and refresh. epically you want to refresh the segment on the page. But it has it's own limitation, it doesn't support file upload. so if you don't have any fileupload, this works OK.
$("#form").submit is the javascript way to submit the form and has same behaviour as the input with "submit" type, but you can do some nice js validation check before you submit, which means you can prevent the submit if client validation failed.
ajaxForm and ajaxSubmit basically are same and does the normal way form submit behaviour with some ajax response. The different between these two has been specified on their website, under FAQ section. I just quote it for some lazy people
What is the difference between ajaxForm and ajaxSubmit?
There are two main differences between these methods:
ajaxSubmit submits the form, ajaxForm does not. When you invoke ajaxSubmit it immediately serializes the form data and sends it to the server. When you invoke ajaxForm it adds the necessary event listeners to the form so that it can detect when the form is submitted by the user. When this occurs ajaxSubmit is called for you.
When using ajaxForm the submitted data will include the name and value of the submitting element (or its click coordinates if the submitting element is an image).
A bit late, but here's my contribution. In my experience, $.ajax is the preferred way to send an AJAX call, including forms, to the server. It has a plethora more options. In order to perform the validation which #vincent mentioned, I add a normal submit button to the form, then bind to $(document).on("submit", "#myForm", .... In that, I prevent the default submit action (e.preventDefault() assuming your event is e), do my validation, and then submit.
A simplified version of this would be as follows:
$(document).on("submit", "#login-form", function(e) {
e.preventDefault(); // don't actually submit
// show applicable progress indicators
$("#login-submit-wrapper").addClass("hide");
$("#login-progress-wrapper").removeClass("hide");
// simple validation of username to avoid extra server calls
if (!new RegExp(/^([A-Za-z0-9._-]){2,64}$/).test($("#login-username").val())) {
// if it is invalid, mark the input and revert submit progress bar
markInputInvalid($("#login-username"), "Invalid Username");
$("#login-submit-wrapper").removeClass("hide");
$("#login-progress-wrapper").addClass("hide");
return false;
}
// additional check could go here
// i like FormData as I can submit files using it. However, a standard {} Object would work
var data = new FormData();
data.append("username", $("#login-username").val());
data.append("password", $("#login-password").val()); // just some examples
data.append("captcha", grecaptcha.getResponse());
$.ajax("handler.php", {
data: data,
processData: false, // prevent weird bugs when submitting files with FormData, optional for normal forms
contentType: false,
method: "POST"
}).done(function(response) {
// do something like redirect, display success, etc
}).fail(function(response) {
var data = JSON.parse(response.responseText); // parse server error
switch (data.error_code) { // do something based on that
case 1:
markInputInvalid($("#login-username"), data.message);
return;
break;
case 2:
markInputInvalid($("#login-password"), data.message);
return;
break;
default:
alert(data.message);
return;
break;
}
}).always(function() { // ALWAYS revert the form to old state, fail or success. .always has the benefit of running, even if .fail throws an error itself (bad JSON parse?)
$("#login-submit-wrapper").removeClass("hide");
$("#login-progress-wrapper").addClass("hide");
});
});