So I'm trying to show validation errors after jquery ajax call, but for some reason instead of printing the actual messagge I'm getting either +value+ or +data.success+, am I appending the values wrong?
This is my code:
$.ajax({
url: '/contactar',/*{{ action('ContactController#contactar') }}*/
type: 'POST',
data:
{
'message_body': $("textarea[name='message']").val()
},
dataType: 'JSON',
success: function (data) {
$('.form_valid_container').append('<span class="form_valid_text">data.success</span>');
form.trigger("reset");
console.log(data.success, data.errors);
},
error: function (data){
var errors = data.responseJSON;
console.log(errors);
$.each(errors , function(key , value){
console.log('error pin');
$('.form_error_container').append('<span class="form_error_text">+ value +</span>')
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Yes you are appending the values incorrectly as shown by the syntax coloring: the whole text is in dark red.
Your String is starting with a single quote ' so you need to end the string with ' too before your + value + :
$('.form_error_container').append('<span class="form_error_text">' + value + '</span>')
Answer given by #pyb and original code will almost always work. However, I can see that the DIV will keep appending the errors even though the form has been reset or triggered multiple times.
Below is the code which I prefer:
NOTE: I have used html function in the success block container which will NOT append the success message always.
NOTE: I have cleared the form_error_container using html function before printing the error messages, so that it will not keep appending the error messages even though the form is reset or triggered multiple times.
$.ajax({
url: '/contactar',/*{{ action('ContactController#contactar') }}*/
type: 'POST',
data:
{
'message_body': $("textarea[name='message']").val()
},
dataType: 'JSON',
success: function (data) {
$('.form_valid_container').html('<span class="form_valid_text">data.success</span>');
form.trigger("reset");
console.log(data.success, data.errors);
},
error: function (data){
var errors = data.responseJSON;
console.log(errors);
$('.form_error_container').html("");
$.each(errors , function(key, value) {
console.log('error pin');
$('.form_error_container').append('<span class="form_error_text">' + value + '</span>')
});
}
});
Thanks.
Related
I have a problem using ajax,
I have a controller get who gives me a simple object (in my case is just one name) but I have this error ( SyntaxError: Unexpected end of JSON input ) and I don't know why.
This is the code:
$(function a() {
var $hello = $('#hello'); //Here #hello is a id which is inside a div
$.ajax({
url: uri_3,
type: 'GET',
dataType: 'json', // if i put text here also don't work, gives sucess but don't appear the
//name
success: function (data) { //have a problem get the name , also I try just $hello.append
//alone and using h2 rather than li but don't work
$.each(data, function c(i, name) {
$hello.append('<li>Name: ' + name + '</li>');
});
},
error: function (xhr, textStatus, errorThrown) { //it always gives me this error, it
//doesn't reach the top success
console.log('Error in Operation');
$hello.append('<h4> User Not Found: ' + errorThrown + '</h4>');
}
});
});
Since the backend function is working (I tested it using swagger and it gives me the right name), I assume the error must be in this ajax function. What more do I have to add?
Any answer is welcome
I am trying to write a .ajax request through a form to log in. When I submit my form, nothing happens with either the success or error functions. I notice that if I put an alert box after the .ajax call it does not work either. I would expect, that if I am just incorrectly putting the data, I would at least expect the error alert box to show up? Here is my code:
var clientType = "clienttype";
$(document).ready(function(){
$("#login-form").submit(function(e){
$.ajax({
type: "POST",
url: "myurl",
data: $(this).serialize() + "&client_type=" + clienttype,
success: function(data) {
alert("sent" + data);
},
error: function(){
alert("Did not work");
}
});
e.preventDefault();
});
});
I noticed you're already using JQuery. So perhaps use the built in post function. Example below:
Also side note: You've got a slight type in your variable: data: $(this).serialize() + "&client_type=" + clienttype, clienttype was declared with a capital T: clientType
var clientType = "clienttype";
$(document).ready(function(){
$("#login-form").submit(function(e){
e.preventDefault();
$.post("myurl",{data:$(this).serialize(),client_type:clientType},function(data){
console.log("Date returned from request:",data);
// Returns JSON Data. So data.clientType.
},'json');
});
});
If you add in a trigger to cancel the page from being submitted, it should work (return false;), take a look below.
var clientType = "clienttype";
$(document).ready(function(){
$("#login-form").submit(function(){
$.ajax({
type: "POST",
url: "myurl",
data: $(this).serialize() + "&client_type=" + clienttype,
success: function(data) {
alert("sent" + data);
},
error: function(){
alert("Did not work");
}
});
return false;
});
});
Here i am using AJAX ,I am passing like this url:"http://www.domain.com/api/get/searchProperties?area="+area+"&city="+city+"&listingType="+listing_type, URL means it is working fine, but i want to pass data so i am trying like this data = 'area='+ area + '&city='+ city + '&listingType='+ listing_type;,now i am getting error:
Uncaught SyntaxError: Unexpected identifier.
<script>
$(document).ready(function(){
$.ajax({
type:'GET',
//url:"www.domain.com/api/get/searchProperties?area=Marathahalli&city=Bangalore&listingType=RENT",// this working
url:"http://www.domain.com/api/get/searchProperties?"
data = 'area='+ area + '&city='+ city + '&listingType='+ listing_type;
success: function(data) {
console.log(data); // Suucess
},
error:function(exception){
console.log('Exeption:'+exception);
}
});
});
</script>
<script>
$(document).ready(function(){
$.ajax({
type:'GET',
//url:"www.domain.com/api/get/searchProperties?area=Marathahalli&city=Bangalore&listingType=RENT",// this working
url:"http://www.domain.com/api/get/searchProperties?",
data :{ area: area,
city:city,
listingType: listing_type
},
dataType:"JSON",
success: function(data) {
console.log(data); // Suucess
},
error:function(exception){
console.log('Exeption:'+exception);
}
});
});
</script>
dont forget that $.ajax({}) which have {} that means you need to provide an object which fulfilled the parameter like Jquery Ajax Doc , because object format is {key1:value, key2: value2, key3: value3} that means you must use data: instead of data= and each key:value pair must be separated by comas ,.
Make sure you close off the previous statements with ;.
I am trying to send a form data, converted to JSON, to another page with jQuery, . However, I believe my POST method is not working as I am always getting the error message- which only says "error". Can anyone help me catch the exact error or tinker the code for making it correct?
I have checked that the data is properly getting JSONed (the first alert is showing the correct form data).
$('#submit').click(function () {
var rows = [];
$('#Tinfo tbody tr').each(function () {
var tds = $(this).children('td'); /* taking all the td elements of the current tr */
rows.push({
'sl': tds.eq(0).find('input').val(),
'tname': tds.eq(1).find('input').val(),
'ttype': tds.eq(2).find('select').val(),
'tduration': tds.eq(3).find('input').val()
});
});
rows = JSON.stringify(rows);
alert(rows);
/* Using the post function to send data over to the database handler page */
$.ajax({
type: "POST",
url: "/Insert",
data: rows,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data, status) {
alert(status);
},
error: function (xhr, textStatus, error) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
});
I think there is a problem with your URL. It should be:
url: "Webpage/function"
you are just using the function part. See this example:
http://weblogs.asp.net/karan/archive/2010/09/12/calling-server-side-method-using-jquery-ajax.aspx
I have an ajax call which will return a set<E>. I need to process this set from the JavaScript function from which I call this ajax.
<script type="text/javascript">
function mySr(id){
$.ajax({
type: 'POST',
url: '../controller/action',
data: 'id=' + id,
success: function(data) {
var length= data.length
var size = data.size
alert(data[0]+'----'+length+'--'+size+'----'+data)
},
error: function () {
alert('error')
}
});
</script>
This is the way i used,
The alert will display like this
["37",
"40","80","90"]----22--undefined----[
I understood the data is clearly reached in the script but i don't know how to iterate through it.
How to iterate here?
How to get the length?
How to get each elements?
You need to parse the data. Try putting data = $.parseJSON(data); after the line success: function(data) {
See http://api.jquery.com/jQuery.parseJSON/ for more details.