I have a problem in my code, I call the php by an ajax call, I have the right answere (I tested the json answere by some alerts), my problem is when I append the data to my list-view, I have no data in my list even using the "refresh". Can you help me to find the bug please.
He gives me this error:
Uncaught Error: cannot call methods on listview prior to initialization; attempted to call method 'refresh'
Here the code in HTML and jQuery
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$.ajax({url: "SubCategory.php",
dataType: "json",
jsonpCallback: 'successCallback',
async: true,
success: function (result) {
ajax.parseJSONP(result);
},
error: function (request,error) {
alert('Network error has occurred please try again!');
}
});
var ajax = {
parseJSONP:function(result){
$.each(result, function(i, row) {
$('#select-subCategory').append('<option value="'+row.id+'">Annuncio: '+row.name+'</option>');
});
$('#select-subCategory').listview('refresh');
}
}
});
</script>
<body>
<form method="post" action="SubCategory.php">
<select id="select-subCategory" data-native-menu="false">
</select>
</form>
</body>
And this is my php file
class SCategory
{
public $id;
public $name;
}
$SubCategories = array();
$SubCategories[0] = new SCategory;
$SubCategories[0]->id = 0;
$SubCategories[0]->name = 'first';
$SubCategories[1] = new SCategory;
$SubCategories[1]->id = 1;
$SubCategories[1]->name = 'second';
$SubCategories[2] = new SCategory;
$SubCategories[2]->id = 2;
$SubCategories[2]->name = 'third';
$SubCategories[3] = new SCategory;
$SubCategories[3]->id = 3;
$SubCategories[3]->name = 'fourth';
echo json_encode($SubCategories);
SOLUTION
Delete 'data-native-menu="false"' from HTML, (maybe is true by
default), so the select in HTML become simply
<select id="select-subCategory" ></select>
then the listview will refresh and
appear!! :)
You are using $('#select-subCategory').append(
and id is selectsubCategory
but should be used
$('#selectsubCategory').append(
this should work fine
$.each(result, function(key, row) {
$.each(row, function(id, name) {
$("<option>").val(id).text(name).appendTo($('#selectsubCategory'));
});
});
$('#select-subCategory').listview();
if you are loading the entire list you will need to initialize it not to refresh it
I fixed the problem :
Delete 'data-native-menu="false"' from HTML, (maybe is true by default), so the select in HTML become simply
<select id="select-subCategory" ></select>
then the listview will refresh and appear!! :)
Related
When some one clicks the category button an AJAX request send to category.php in this php file i am encoding a JSON response.
Jquery Onclick Function
$('#Category').change(function(){
var j;
$.ajax({
url:'categories.php',
success: function(results){
var obj = JSON.parse(status);
alert(obj);
}
});
});
category.php File
<option value="" selected="">Select Sub Category</option>
<option value="Cars">Cars</option>
<option value="Motorbikes & Scooters">Motorbikes & Scooters</option>
$status = array('type' => 'yes');
echo json_encode($status);
Now how to assign yes to a JQuery variable on AJAX success? i tried some codes (in Above JQuery codes) but that didn't work please suggest me a solution.
According to your, you are getting the response from php page in results not in status and results itself is a jquery variable. So change status to results.
$('#Category').change(function () {
var j;
$.ajax({
url: 'categories.php',
success: function (results) {
var obj = JSON.parse(status);
alert(obj);
}
});
});
Fixed this problem.. thanks for the effort guys..
$('#Category').change(function () {
$.ajax({
url: 'categories.php',
success: function (results) {
if (results.indexOf("yes") >= 0) {
var j = 'yes';
alert(j);
}
}
});
});
Recently i am facing an unknown problems. I am using customized dropdown list in MVC4 and populating data by ajax. It is working fine but problem is, it is not clearing data after successfully sending data to the controller.
Here i tried the example..
<select data-placeholder="Select a Brand..." style="width:254px;" name="brand" id="brand">
<option value=""></option>
</select>
$("#brand").select2({
width: 254
});
For clearing drop down list i have tried like this..
$("#brand").val("");
I have search many example refreshing data in drop down list but i failed. Please help me to solve the problem.
Here i have shared my long code
<script type="text/javascript">
$(document).ready(function () {
$("#brand").select2({
width: 254
});
$.get('/Settings/Brands/', function (data) {
$.each(data, function (index, c) {
$('#brand').append('<option value="' + c.id + '">' + c.name + '</option>');
});
});
$('#btnAdd').live("click", function () {
if (confirm("Do you want to Save?") == true) {
$.ajax({
cache: false,
async: false,
type: "POST",
url: "/Settings/ItemAdd/",
dataType: "json",
data: adata,
success: function (data) {
alert(data.msg);
$('#list').trigger('reloadGrid');
},
error: function (data) {
alert(data.msg);
$('#list').trigger('reloadGrid');
}
});
}
$("#itemname").val("");
$("#batchNo").val("");
$("#desp").val("");
$("#brand").find("option").val("");
$("#ctg").val("");
$("#supplier").val("");
$("#unittype").val("");
$("#qty").val("");
$("#bprice").val("");
$("#sprice").val("");
$("#Edate").val("");
$("#qlimit").val("");
$("#vat").val("");
$("#icode").val("");
});
});
</script>
This should work:
$("#brand").empty();
More info about jQuery's empty function:
https://api.jquery.com/empty/
Example: https://jsfiddle.net/mjc7302v/
Like all jquery plugin for select controls, the plugin hides the original <select> tag and replaces it with its own html. Changing properties of the original select has no impact. Instead your need to use he methods of the plugin.
Although you question asks How to clear dropdown options value, from the comments I assume you mean reset it to the default null option, in which case it would be
$("#brand").select2("val", "");
Side notes:
Its not clear why you would load the values after the page is loaded
using an ajax call. You could simply strongly bind it to your model
using #Html.DropDownListFor(m => m.Brand, model.BrandList, "Select a Brand...") where you view model contains public SelectList
BrandList { get; set; } (or use a ViewBag property for
BrandList) and avoid the unnecessary ajax call.
.live has been depreciated. Use .on instead (although in your
case your not using event delegation so its simply
$('#btnAdd').click(function() { ..)
Use url: '#Url.Action("ItemAdd", "Settings")',, not url: "/Settings/ItemAdd/", so your url are always correctly generated
You can remove all your code for resetting individual controls (e.g.
$("#itemname").val(""); etc.) with $('form').get(0).reset();
$( "#brand").empty();
See the jQuery API docs for the .empty() method.
I am using the well known ajaxForm Jquery Form Plugin (http://jquery.malsup.com/form/). I 'll present to you my code:
HTML code:
<script type="text/javascript">
$(document).ready(function() {
$('#users_form1').ajaxForm({
dataType: 'json',
success: processJson
});
});
function processJson(data) {
$("#first").val(data[1].elem1);
$("#second").val(data[1].elem2);
}
</script>
PHP code:
...
$result=$db->query($query);
if ($result->num_rows>=1)
{
$counter=0;
while ($row = $result->fetch_assoc()) {
$counter++;
$data1=$row["req_created"];
$data2=$row["subject"];
$temp[$counter] = array(
'elem1' => $data1,
'elem2' => $data2,
);
}
echo json_encode($temp);
}
As you may see from the above code, $temp is passed to var data inside function processJson. I'd like to know if array $temp is accessible outside processJson? For example, I want to choose $temp[3]["elem2"] upon a button click, however is it possible to get this data without searching again the database? If yes, how?
Thank you very much
You can have the data in variable, this will be like temporary storage.
<script type="text/javascript">
$(document).ready(function() {
$('#users_form1').ajaxForm({
dataType: 'json',
success: processJson
});
});
var tem_data;
function processJson(data) {
$("#first").val(data[1].elem1);
$("#second").val(data[1].elem2);
tem_data = data;
}
// Use tem_data anywhere;
</script>
But only last requested data will be the tem_data.
If you want all data then do it in array with array push method
How can I make this code work, the problem is that I can't seem to be able to acces the data returned, I know that it connects to the server, but for somereason it wont work, for example, I tried extracting the title but nothing appears.
$.ajax({
url : "https://www.googleapis.com/books/v1/volumes?q=harry+potter",
dataType : "jsonp",
async : true,
//if ajax call succeeds perform this action
success : function(result) {
ajax.parseJSONP(result);
},
//if there is an error to the ajax call perform this action
error : function(request, error) {
alert('Network error has occurred please try again!');
}
});
//parseJsonP and add new elements to list-view
var ajax = {
parseJSONP : function(result) {
//iterate each returned item
$.each(result, function(i, row) {
$('#listview_test').append('<li><h3>' + row.volumeInfo.title + '</h3></a></li>');
}); //end iteration of data returned from server and append to the list
$('#listview_test').listview('refresh'); // refresh the list-view so new elements are added to the DOM
}
}
My confusion is on the callback method, in their example Books API has a code like is shown down, but I dont get it this part q=harry+potter&callback=handleResponse, how can I make this while using the $.ajax method. Tried understanding all the pieces but still very confusing?
<body>
<div id="content"></div>
<script>
function handleResponse(response) {
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
// in production code, item.text should have the HTML entities escaped.
document.getElementById("content").innerHTML += "<br>" + item.volumeInfo.title;
}
}
</script>
<script src="https://www.googleapis.com/books/v1/volumes?q=harry+potter&callback=handleResponse"></script>
</body>
Try replacing your following code:
$.each(result, function(i, row) {
for this one:
$.each(result.items, function(i, row) {
As per the google example code the data is located in an array called items within the returned object.
I have the following view inside my asp.net mvc , which display a ajax-loading imag, which i am trying to hide after starting a jquery function as follow:-
<div id= "geturl" data-url="#Url.Action("ListPackages", "Home")">
<h1>All Processes</h1>
<img id="tobehide" src="~/Content/ajax-loading2.gif" />
<ul id="products">
</ul>
Then the following JavaScript file:-
$(document).ready(function () {
$.ajax({
url: $('#geturl').data('url'),
type: 'GET',
cache: false,
success: function (result) {
$('#tobehide').hide();
$.each(result.data, function (key, val) {
var str = val.packageName;
$('<li/>', { text: str })
.appendTo($('#products'));
});
}
});
});
Currently the data will be filled in the but the loading-imag will not be hiden.so how i can force the imag to hide when the java script starts executing?.
Best Regards
Your code is correct, and should work fine!
Try using FireBug or Chrome developer tools to see what's the javascript error you are getting back from the ajax call.
If that still doesn't help, and you want the image to be hidden regardless, then use the 'complete' callback on the jquery ajax call you are using.
$(document).ready(function () {
$.ajax({
url: $('#geturl').data('url'),
type: 'GET',
cache: false,
complete: function (result) {
$('#tobehide').hide();
$.each(result.data, function (key, val) {
var str = val.packageName;
$('<li/>', { text: str })
.appendTo($('#products'));
});
}
});
});
It should work fine. No mistake in your code Brother.
try adding async option. Set it to false. and try again