cannot get the results to be displayed on the page - javascript

I cannot display the results which I got from database:
{"results": ["USA", "Canada"]}
{"message":"Could not find any countries."} //else
I got this error from console:
Uncaught TypeError: Cannot read property 'length' of undefined.
Could you please check my code to find out what is my mistake.
Here is my view:
My Travel Plans
<div id="my_div">
<div id="country_list_is_got"></div>
<div id="country_list_is_not_got"></div>
</div>
Controller:
if ($this->my_model->did_get_country_list($user_id)) {
$country["results"]= $this->model_users->did_get_country_list($user_id);
echo json_encode($country);
}
else {
$country = array('message' => "Could not find any countries." );
echo json_encode($country);
}
JS file:
$("#load_country_list").click(function() {
$.post('cont/get_country_list', function (country) {
if (country.message !== undefined) {
$( "#country_list_is_not_got").text(country.message);
} else {
$.each(country.results, function(i, res) {
var item = $('<div>'),
title = $('<h3>');
title.text(res);
item.append(title);
item.appendTo($("#country_list_is_got"));
});
}
});
});

You need to tell jQuery what content type is coming back from the server (json)
It defaults to 'string' and it has no reason to think that's incorrect.
See the documentation for the correct parameter order.
Your .each iterator is trying to loop over a string, and - obviously - failing.
Edit: As a point of pedantry, why are you using POST to GET data? "Get" is literally in your URL.

I think it should be $.get or the $.getJSON shortcut, instead of $.post
$.getJSON("cont/get_country_list", function( data ) {
console.log(data);
// something like this for list construction and append to body
var countries = [];
// maybe you need data.results here, give it a try or see console
$.each( data, function( key, val ) {
countries.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "country-list",
html: countries.join( "" )
}).appendTo( "body" );
});

Live Demotry this, issue is results contain array.but you try to use key,value
if (country.message !== undefined) {
$( "#country_list_is_not_got").text(country.message);
} else {
for(i=0;i<country.results.length;i++){
var item = $('<div>'),
title = $('<h3>');
title.text(country.results[i]);
item.append(title);
item.appendTo($("#country_list_is_got"));
}
}

Related

How can I validation a form with AJAX in laravel with request file?

shere is my request codes
public function authorize()
{
return true;
}
public function rules()
{
return [
'code'=>'required',
'title'=>'required',
'level'=>'required',
'related'=>'required',
'active'=>'required',
];
}
I want show the errors with AJAX. There are many solutions for this problem in the stackoverflow but none of them can solve my problem
because they describe static method to handle this problem I want use request file for putting rules and show errors in my view with AJAX
please help me
var errors = data.responseJSON;
$.each(errors, function(key, value){
$('#' + key)
.closest('.form-group')
.addClass('has-error')
.append('<span class="help-block">' + value + '</span>');
});
Have you tried updating your Handler.php or manage to response?
My suggestion is to modify the file App\Exceptions\Handler.php. On the method render() you can add or replace with this code:
public function render($request, Exception $exception)
{
$parent = parent::render($request, $exception);
if(!$request->is('api*'))
{
return $parent;
}
$messages = null;
if(isset($parent->original) && isset($parent->original["errors"]))
{
$messages = $parent->original["errors"];
}
return response()->json(
[
'errors' => [
'status' => 401,
"messages" => $messages
]
], 401
);
}
This code will response a json when your route is under api.
Here is my solution :
I added this codes to my Ajax :
$.ajax({
url:myUrl,
type:method,
data : form.serialize(),
success:function(data)
{
// if success run these codes
},
error: function(xhr){
var data = xhr.responseJSON;
if($.isEmptyObject(data.errors) == false) {
$.each(data.errors, function (key, value) {
$('#' + key)
.closest('.form-group')
.addClass('has-error')
.append('<span class="help-block">' + value + '</span>');
});
}
}
});

How to combine two similar scripts and run it with slight variations

I have the following two scripts:
The first one, on grabs a keyword from input#search and populates a dropdown#search-results with the results from the ajax call for that keyword.
$(document.body).on( 'keyup', '#search', function ( e ) {
//e.preventDefault();
value = $(this).val(); //grab value of input text
jQuery.ajax({
url : ajaxsearch.ajax_url,
type : 'post',
data : {
action : 'search_client',
key : value,
},
success : function( response ) {
response = jQuery.parseJSON(response);
//console.log(response);
$.each(result, function(k, v) {
$('#search-results').append('<li>' + v['Name'] + '</li>');
});
}
});
});
The second script, grabs the value of the clicked dropdown result, does the same action as the first script only this time the ajax result is used to populate fields located on the page.
$(document.body).on('click','#search-results > li', function ( e ) {
//e.preventDefault();
value = $( this ).text(); //grab text inside element
jQuery.ajax({
url : ajaxsearch.ajax_url,
type : 'post',
data : {
action : 'search_client',
key : value,
},
success : function( response ) {
response = jQuery.parseJSON(response);
//console.log(response);
$.each(response, function(k, v) {
$('#clientID').val( v['ClientId'] );
$('#denumire').val( v['Name'] );
$('#cui').val( v['CUI'] );
$('#regcom').val( v['JRegNo'] );
$('#adresa').val( v['Address'] );
$('#iban').val( v['IBAN'] );
$('#banca').val( v['Bank'] );
$('#telefon').val( v['Phone'] );
$('#pers-contact').val( v['Contact'] );
});
}
});
});
Is there a way to combine the second script into the first one so not to make the second ajax call, but be able to populate the fields on the page with the results from the first ajax call depending on the clicked result in the dropdown list?
If the text you insert from v['Name'] into the list item in the first script is the exact same thing you want to use elsewhere in the page in the second script, you can reduce the code way, way down. After all, if you already have the value you want, there's no need to go search for it again.
//first function, just the relevant bits...
$.each(result, function(k, v) {
var newItem = $('<li>' + v['Name'] + '</li>');
$.data(newItem, "value", v);
$('#search-results').append(newItem);
});
//second function, the whole thing
$(document.body).on('click','#search-results > li', function ( e ) {
e.preventDefault();
var v = $.data($( this ), "value"); //grab object stashed inside element
$('#clientID').val( v['ClientId'] );
$('#denumire').val( v['Name'] );
$('#cui').val( v['CUI'] );
$('#regcom').val( v['JRegNo'] );
$('#adresa').val( v['Address'] );
$('#iban').val( v['IBAN'] );
$('#banca').val( v['Bank'] );
$('#telefon').val( v['Phone'] );
$('#pers-contact').val( v['Contact'] );
});
This should let you store the entire result object into the list item, then retrieve it later. If you have some elements in that list that you're not putting there with searches, you'll have to do some more work to get their relevant data too.

Adding options to select field using javascript from a json file

var json = $.getJSON("../category.json", function() {
alert(2);
})
.done(function() {
console.log( "second success" );
var var1 = document.getElementsByClassName('category');
var1.innerHTML = "<option value='" + key + "'>" + val + "</option>";
alert(var1);
})
.fail(function() {
alert( "error" );
});
I want to values from json file as options to my select field. But my code always shows alert error. Please tell me what is wrong with it ?
You're not setting your key and value parameters. In fact it doesn't look like you're getting your JSON results at all.
Change your done method to
.done(function( data ) { /* do stuff */ }
Now your JSON results will be stored in data.
Then you may need to loop through the results. See the example here
try this
var json = $.getJSON("../category.json", function(data) {
alert(2);
})
.done(function(data) {
console.log( "second success" );
var var1 = document.getElementsByClassName('category');
$.each( data, function( key, val ) {
var1.innerHTML += "<option value='" + key + "'>" + val + "</option>";
alert(var1);
});
alert(var1);
})
.fail(function() {
alert( "error" );
});
Your JSON is not valid: You cannot use a number as a JSON key
[
{
"NAME":"chair",
"0":"chair" <-- error
},
{
"NAME":"bed",
"0":"bed" <-- error
},
{
"NAME":"table",
"0":"tabl‌​e" <-- error
},
{
"NAME":"almira",
"0":"almira" <-- error
}
]
Try running your JSON through an online JSON parser and the error will come up.
Alternatively, change your error handler to include more information
.fail(function (jqXhr, status, error) {
alert(status + ':' + error + ':' + jqXhr.responseText) }
});

How do I loop through a JSON response and inserting into different elements

I'm very limited in javascript knowledge.. i'd appreciate any suggestions..
I've looked through previous JSON questions and answers, but didn't see anything that was similar to this.
I'm using jQuery. I have a JSON server response in the following format:
{
"aNumBids_1": "4",
"aHighBid_1": "100.00",
"aBidAmount_1": "110.00",
"aBidEnd_1": "09/27/2013 17:00",
"aNumBids_2": "42",
"aHighBid_2": "1,210.00",
"aBidAmount_2": "1,260.00",
"aBidEnd_2": "09/27/2013 17:01",
"aNumBids_3": "12",
"aHighBid_3": "1,100.00",
"aBidAmount_3": "1,150.00",
"aBidEnd_3": "09/27/2013 17:02",
"aNumBids_4": "26",
"aHighBid_4": "1,460.00",
"aBidAmount_4": "1,510.00",
"aBidEnd_4": "09/27/2013 17:03",
"aNumBids_5": "32",
"aHighBid_5": "1,210.00",
"aBidAmount_5": "1,260.00",
"aBidEnd_5": "09/27/2013 17:04"
}
the first element of each pair is the element name on the page ( name='aBidAmount_5' ). The second element of each pair is the content to be placed into that element.
How do i go about looping through this json response ?
I've gotten this far:
AJAX.getPrice = function(){
var request = $.ajax({
url: serverScript,
data: JSON.stringify(aItems) ,
dataType: "json"
});
request.done(function() {
// update the element value
/* i'm lost here */
});
request.fail(function(jqXHR, textStatus) {
// If console is available output the error to console log
if (typeof console == "object") {
console.log( "Request failed: " + textStatus +data );
}
});
}
Assuming "element name" is the id of the element, this should work :
request.done(function(data) {
for(var k in data) {
if(data.hasOwnProperty(k)) {
$('#'+k).html(data[k]);
}
}
});
if these are input names then in the done call back use
request.done(function(data) {
for(i in data) {
$("input[name="+i+"]").val(data[i]);
}
});
Js Fiddle: http://jsfiddle.net/vuQLu/
JS:
var output = '<ul>';
$.each(data, function(key, value){
$.each(value, function(key, value){
output += '<li>' + key + ' => ' + value + '</li>';
});
});
output += '</ul>';
$(".myClass").html(output);
Html:
<div class="myClass"> </div>

Mystery ajax request occurring somehow

Whenever I type in the autocomplete field an ajax request is sent and there is no code I've written to do this. Checking the console I see it's a 400 GET request to the controller that loaded this view with param (json) appended to the url. I'm absolutely stumped.
<head>
<script data-main="<?=base_url()?>public/requirejs/main.js" src="<?=base_url()?>public/requirejs/require-jquery.js"></script>
<script>
requirejs(['a_mod'],
function(a_mod) {
$(document).ready(function() {
var param = [];
param = $('#elem').attr('value');
a_mod.foo(param, "#someElem");
});
});
<script>
main.js
require(["jquery",
"jquery-ui"],
function() {
}
);
The autocomplete function
'foo' : function(param, elementAutocomplete, elementTags) {
console.log("init ac");
$(elementAutocomplete).autocomplete({
source: param,
minLength: 1,
select: function (event, ui) {
event.preventDefault();
//
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $("<li></li>")
.data( "item.autocomplete", item )
.append( '<a>' + item.label + '</a>' )
.appendTo(ul);
}
},
Your source attribute for the autocompleter is a string:
param = $('#elem').attr('value');
And a string source means that it is a URL:
Autocomplete can be customized to work with various data sources, by just specifying the source option. A data source can be:
an Array with local data
a String, specifying a URL
a Callback
Saying var param = []; just means that param is initialized as an empty array, it doesn't mean that param will always be an array. You need to fix your param value to be an array.

Categories

Resources