Ajax: obtain input text using get function from a web api - javascript

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

Related

Uncaught ReferenceError: function is not defined : Can not call my function with onclick button [solved]

I have got the weird errors from browser when I was trying to add individual events to each buttons that I have created in table.
It has never happened before till now. Can someone tell me where is my blind spot? thanks
Here is how I generate the table with callback function from response data:
$("#bulletin .card-body tbody").html("")
$.each(data.content, function(index, item){
var type = $("#bulletin .card-header button").eq(item.type-1).text()
var res =
'<tr>'+
'<td>'+parseInt(index+1)+'</td>'+
'<td>'+item.announcement+'</td>'+
'<td>'+type+'</td>'+
'<td>'+item.announcement+'</td>'+
'<td>'+item.createdTime+'</td>'+
'<td><button class="btn btn-dark" onclick="openBulletinDetails(\'' + item.id + '\')">details</button</td>'+
'</tr>';
$("#bulletin .card-body tbody").append(res)
})
And there you go the callback:
function openBulletinDetails(id){
console.log(id)
}
I can only got this error
Uncaught ReferenceError: openBulletinDetails is not defined
I request the data from restful API using ajax to get that JSON if it helps.
function generateTable(){
// XHR
$.ajax({
url: url,
type: "GET",
dataType: "json",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "bearer " + globalAuthToken);
},
success: function(data) {
// generate the table here....
},
error: function(data) {
alert(data.status);
}
});
}
function openBulletinDetails(id){
console.log(id)
}
Problem solved!!!
The reason why I got this error is because >> I set my external js file as module type. None of logic were wrong. But why is that stopping the onclick events? no clue...if anyone knows the reason, kindly give me some response.

Cant print validation errors values into view with jquery

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.

Symfony2: How to get the current route in javascript?

I'm using Ajax to change data in a page. So, I want to know that what is the current route in order to call to different functions. I have read many solutions used to retrieve the current url and also to get the current route in Controller and Twig. However, is there any possible way to achieve this in javascript or jQuery?
$(document).ready(function(){
$('#form_patient').change(function(){
var id = $(this).val();
// Get the current route
var route = ??; // <----------------Want to get the current route
if(route === 'route1'){
functionForRoute2(id,route)
}
else{
functionForRoute2(id,route);
}
});
});
** Function for the Route1 **
function functionForRoute1(id,route){
$.ajax({
type: "POST",
url: Routing.generate(route),
data: JSON.stringify({id:id}),
dataType: "json",
success: function(data){
// Execute some specific data for route1
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('Error : ' + errorThrown);
}
});
}
** Function for the Route2 **
function functionForRoute2(id,route){
$.ajax({
type: "POST",
url: Routing.generate(route),
data: JSON.stringify({id:id}),
dataType: "json",
success: function(data){
// Execute some specific data for route2
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('Error : ' + errorThrown);
}
});
}
What I would do is to output route (any route you want) in a html tag for example (twig version):
<div id="my-route" data-route"{{ path("my_route") }}"></div>
Then in your code I would retrive that route via jquery like this:
$(document).ready(function(){
$('#form_patient').change(function(){
var id = $(this).val();
var route = $('my-route').data('route');
});
});
You can also change path("my_route") to a string with a name of the route and then you are doing your if/else statement. However I dont think its a good idea as if your route name changes then your code will be affected as well
You will not get current route using just Javascript or JQuery. You can, however, get current URL with Javascript or current route using Twig.
Another possible solution is to issue one more AJAX call to server passing current URL, then match it to the correct route and send it back. However, if I were you, I would just get the current route from Twig.
var route = "{{ app.request.attributes.get('_route') }}";

Ajax post working but not callback message in Android browser

im implementing sign up with ajax on my site its working perfectly on desktop but causing problem in Android Browser The problem is after i click on signup button in android browser it post data to database but do not replace the html message.And alert native code error.
function postdata(){
var chkfrm = checkdata();
if(chkfrm == 0){
var url = '<?php echo base_url();?>index.php/Signup/signin';
$.ajax({
type: "POST",
url: url,
data: $("#formI").serialize(), // serializes the form's elements.
beforeSend:function(){
$("#signupdiv").html('<h1>Loadinng...........</h1>');
},
success:function(data)
{
$("#signupdiv").html(data);
},
error:function () {
alert(console.log);
}
});
e.preventDefault();
}
else {
$("#msgjava").html('<p>We need a little bit information from you.Please fill it.</p>');
return false;
}
You can't do e.preventDefault(); where you are because e is not passed into this function (thus it is undefined). This will cause an error and stop JS execution.
In what you posted, you are also missing a closing brace at the end of the postdata() function.
Your alert says "native code" because that's what this line of code:
alert(console.log)
will do. console.log is a native function so alerting a native function won't do anything useful. You need to make that alert a lot more useful. To see in more detail what error is coming back from the ajax function, change your error handler to something like this:
error: function(jqXHR, textStatus, errorThrown) {
alert("status = " + textStatus + ", errorThrown = " + errorThrown);
}
And, then see what it says.

Posting form values with jQuery ASP.NET Webpages Error

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

Categories