my problem is, i can't retrieve data using AJAX (post) on my NodeJS and MongoDB. Im using body-parser. i use post request because the data will be dependent on what the value of my 1st dropdown is.
Here is my code
NodeJS
app.get('/test', function(req, res){
City.findOne({'thecity': 'Auckland'}).populate('coolplaces').exec(function(err, thecoolplace){
if(err){
console.log(err);
} else {
res.send(thecoolplace);
}
});
});
app.post('/testpost', function(req, res){
City.findOne({'thecity': req.body.thecityname}).populate('coolplaces').exec(function(err, thecoolplace){
if(err){
console.log(err);
} else {
res.send(thecoolplace);
}
});
});
EJS
<select id="cities" name="thecityname">
<% City.forEach(function(city){ %>
<option val="<%= city.thecity %>"><%= city.thecity %></option>
<% }); %>
</select>
<select id="coolplace" name="thecities">
</select>
So basically, i have 2 dropdown list, my goal is, on my 1st dropdown, it contains the city name, then when i selected a city name on it, it should fillup the second dropdown with the places based on that city (i've handled that data on database).
As you can see on my NodeJS code, at first, i tried using GET request then query the database based on its name and i used hardcoded one which is 'Auckland', the ajax call works find, it fills up the second drop down of the places in Auckland.
Now since my goal is to populate the second form based on the selected value on 1st dropdown, i create a post request, same code, except the query value will depend on the 'req.body.thecityname' which is the 'name' of my tag.
Now this is my Ajax Code
$('#cities').change(function(){
theAjax();
});
function theAjax(){
console.log($('#cities').val())
$.ajax({
type: 'POST',
url: '/testpost',
data: $('#cities').val(),
success: function(data){
console.log(data);
},
error: function(){
alert('No data');
}
});
}
function fillupPlaces(){
var $coolplaces = $('#coolplace');
$.ajax({
url: '/test',
type: 'GET',
dataType: 'json',
success: function(data){
data.coolplaces.forEach(function(thecoolplaces){
$coolplaces.append('<option>' + thecoolplaces.theplacename + '</option>');
});
}
});
}
Whenever the value on the 1st dropdown change, the Ajax will trigger, on the 1st line, i console.log the value of it and it returns the value of the data that i selected, but on the Ajax success, the console.log(data) returns nothing.
The second function works, but what i want is, to fillup the second dropdown with the places based on the city
Here's the screenshot
What am i doing wrong? thank you guys!
Try changing the post data to an object with the key 'thecityname' and the value as the city name.
function theAjax(){
console.log($('#cities').val())
$.ajax({
type: 'POST',
url: '/testpost',
data: {
thecityname: $('#cities').val(),
},
success: function(data){
console.log(data);
},
error: function(){
alert('No data');
}
});
}
Adding a console.log like below may be helpful. If only the city is sent as post data, instead of an object with key 'thecityname', then req.body.thecityname will be undefined.
app.post('/testpost', function(req, res){
console.log('req.body.thecityname is ' + req.body.thecityname);
City.findOne({'thecity': req.body.thecityname}).populate('coolplaces').exec(function(err, thecoolplace){
if(err){
console.log(err);
} else {
res.send(thecoolplace);
}
});
});
Related
Have some problems to populate a Select2 with json data retrieved by ajax.
I check all samples from Select2-Github-AjaxData and other from StackOverFlow so always have same problem... the Json retrieved can't update next select2.
Some tries i use Jquery.Ajax to retrieve and assign:
function loadvariedad() {
var productIDVal= $("#frb_producto").val();
$.ajax ({
url: "http://www.fruitbull.info/api/json/es/v",
data: {idv: productIDVal, key:"123456"},
delay: 250,
dataType: 'json',
success: function(theResponse) {
$("#frb_variedad").select2({
data: theResponse.items
});
}
});
};
Other solution checked was the sample on Github form Ajax:
var productIDVal= $("#frb_producto").val();
$('#frb_variedad').select2({
ajax: {
url: 'http://www.fruitbull.info/api/json/es/v?key=123&idv='+productIDVal,
processResults: function (data) {
return {
results: data.items
};
}
}
});
Any idea or help to check?
My sample and tries on Fiddle
Solved by json origin data was formatted incorrectly
I'm currently trying to make an ajax POST request to send a testimonial simple form to a Django view. The problem is this request is returning a GET instead of a POST.
This is my ajax:
<script>
$(document).ready(function(){
$("form.testimonial-form").submit(function(e){
e.preventDefault();
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "/testimonials",
data: dataString,
success: function(_data) {
if (_data[0]){
$('.modal-text').css({display: "none"});
}
else{
$('.unsuccess').css({display: "block"});
}
}
});
});
});
</script>
Any idea what could I be doing wrong?
replace type by method
method: 'post',
also you may need send headers:
headers: {
'X-CSRFToken': getCSRFToken()
},
where getCSRFToken is:
function getCSRFToken() {
return $('input[name="csrfmiddlewaretoken"]').val();
}
I am not really sure why this is happening, but i would write the function in a bit different way. since ajax();'s default type is "GET", i suspect somewhere it is being set to default.
first set the type="button" of submit button (whose id is e.g. "submit_button_id"), so it doesnot submits if you click on it. or put the button outside of <form>
then try this code
<script>
$(function(){ // same as "$(document).ready(function()"..
$("#submit_button_id").on('click',function(){
var dataString = $('form.testimonial-form').serialize();
$.ajax({
type: "POST",
url: "/testimonials",
data: dataString,
success: function(_data) {
if (_data[0]){
$('.modal-text').css({display: "none"});
}
else{
$('.unsuccess').css({display: "block"});
}
}
});
});
});
</script>
i am new in this ajax . i got a problem that is in my ajax coding i get a multiple data in loop so how can print that multiple data in ajax success
here is my code :
$.ajax({
url: 'ajaxdate',
data: {ending:ending},
type: 'POST',
success: function(data) {
$('#info1').text(data);
console.log(data.length);
alert(data);
/*for(var item in data){
console.info(item);//print key
console.info(data[item]);//print value
}*/
}
});
function ajaxdate()
{
$data=array();
foreach ($guestbookdetail as $guestbookdetail)
{
echo $data['full_name'] = $detail['list']['full_name']."\n";
}
}
How i print that multiple data in ajax success
What you can do with is expect JSON as response.
I see the problem in your function if you are printing the full_name in loop and expecting HTML response, all it will be just a string.
What you can do is something like this
function ajaxdate()
{
$data=array();
foreach ($guestbookdetail as $guestbookdetail)
{
$data[]['full_name'] = $detail['list']['full_name'];
}
die(json_encode($data));
}
This will return a json array with collection of object of full_name eg [{full_name: 'ABC'},{full_name: 'cde'}]
Then add dataType : 'json' in you ajax.
Now you can iterate thorough the response you get in ajax success.
For an example you have this <ul id="showResultHere"></ul> tag, where you would like to show the result, then TRY this in your "success" AJAX :
success: function (data){
$.each(data, function(index) {
//alert(data[index]);
$("#showResultHere").append("<li>" + data[index] + "</li>");
});
}
Or, another way to show your "full_name" from your guestbook array, here is another option too :
success: function (data){
data.forEach(function(data) {
$("#showResultHere").append("<li>" + data + "</li>");
});
}
Two Ajax calls. They both execute the calls but the first one returns a drop down values in the text input field and the second one with extraParam fails to show the drop down with the matching values in text input field. I have checked, the right values are returned from the Spring Controller. Any reason why this is not working? What the difference between both the calls other than passing an extra parameter?
$(document).ready(function() {
$( ".oid" ).autocomplete({
source: "${pageContext. request. contextPath}/app/X.htm"
});
});
$(document).ready(function() {
$( "#fifa" ).autocomplete({
source: function (request, response) {
$.ajax({
url: '${pageContext. request. contextPath}/app/Y.htm',
data: {
term: request.term,
extraParam: OneMoreParamValue
},
success: function (data) {
console.log('response=', data);
}
});
}
});
});
You didn't call the response function, http://api.jqueryui.com/autocomplete/#option-source
Something like
success: function (data) {
console.log('response=', data);
response(data);
}
you might have to set the data type to 'json' as well.
I'm retrieving the number of rows contained by a table in my database with the following function using JSON.
function rowCount()
{
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
datatype:"json",
type: "GET",
url: "/wagafashion/ajax/CmsRowCount.htm",
success: function(response)
{
$("#rows").val(response);
},
error: function(e)
{
alert('Error: ' + e);
}
});
}
In the success handler, the response is arriving as expected. There is no problem on the server side.
The response is just mapped with the long type of Java which represents the number of rows in a database table.
I'm putting this response in a hidden field whose id is rows using $("#rows").val(response); in the success handler.
The above function is invoked when the form is submitted using the following jQuery function.
$(function() {
$('#dataForm').submit(function() {
rowCount(); //Invokes the above function that makes a JSON request.
var rows=$("#rows").val();
alert("rows = "+rows);
return false;
});
});
The alert box attempts to alert the value contained by the hidden field (which is the JSON response as described above) but it is empty for the first time. It alerts the actual value only when I press the submit button once again (without a page refresh).
Also tried to replace the preceding function with the following.
$(function() {
$('#dataForm').submit(function() {
rowCount(); //Invokes the first function that makes a JSON request.
var form = $(this),
url = form.attr('action'),
rows = form.find('input[name="rows"]').val();
alert("rows = "+rows);
return false;
});
});
But it didn't work either. Why does this happen? What is the way of retrieving the correct value of that hidden field into the preceding jQuery function?
The alert box attempts to alert the value contained by the hidden field (which is the JSON response as described above) but it is empty for the first time.
Ajax calls are asynchonrous. When you call rowCount, you start the call, but then rowCount returns and your code continues. The call doesn't complete until later (which is why ajax accepts a callback).
If you trigger the next step in what you're doing from the callback, you'll have the value. You typically do this by having rowCount accept a callback of its own, like this:
function rowCount(callback) // <==== Accept the callback
{
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
datatype:"json",
type: "GET",
url: "/wagafashion/ajax/CmsRowCount.htm",
success: function(response)
{
$("#rows").val(response);
callback(); // <==== Call the callback
},
error: function(e)
{
alert('Error: ' + e);
callback(); // <==== Probably want to give it a value telling it things failed
}
});
}
Then using it:
$(function() {
$('#dataForm').submit(function() {
var form = $(this); // <== Grab this outside the callback
rowCount(function() {
var url = form.attr('action'),
rows = form.find('input[name="rows"]').val();
alert("rows = "+rows);
});
return false;
});
});
If you want to decide whether to allow the form to be submitted on the basis of the callback, you'll have to always cancel the submission, and then trigger submitting it programmatically from the callback if you want to allow it.