Please help me to solve my problem.
$("#kategori_laporan").change(function() {
$("#loaderIcon").show();
$("#imgLoader").show();
var id = $(this).val();
$.ajax({
type: "POST",
dataType: "html",
url: "_views/getAjaxSubKategori.php",
data: "id="+id,
success: function(data) {
$(".select-skategori").select2({
ajax: {
url: "_views/getAjaxSubKategori.php",
dataType: 'json',
data: function(term, page) {
search = term.toUpperCase();
},
results: function(datas, page) {
return {
results: data
};
}
},
formatResult: function(option) {
return "<div>" +option._sub_kategori_laporan+ "</div>";
},
formatSelection: function(option) {
return option._sub_kategori_laporan;
}
});
}
});
});
Data not showing to subcategory select. Thanks before.!
Screenshot >> http://i.imgur.com/FlCeGpo.jpg
Why are you firing an ajax request before you initialize the select2 box?
I ask this, because your select2 box is requesting the search results via ajax as well. But maybe there is a reason. Please explain.
Then I can see in your screenshot, that your data returned from the json ajax request has not defined values id and text. If you are using other values ('_sub_kategori_id' and '_sub_kategori_laporan') in your json result, you have to tell the select2 box, what is your id and text field. I think you can do this with the processResults method as described here:
How to load JSON data to use it with select2 plugin
Related
I am writing a very simple web form where i am sending data from a text box to the PHP with jQuery AJAX and want to populate a label in the html page with the response (manipulated in php)
I am working without a form in the HTML page, but instead using multiple objects, since the page should contain 3 steps, and I do not want to use action.
Here are the relevant pieces of code:
HTML/JS
function funcGetBatches() {
CatNum = document.getElementById("CatNumber");
console.log(CatNum.value);
$.ajax({
type: "GET",
url: "./php/conn.php",
data: CatNum.value,
datatype: "text",
success: function(data) {
console.log("Succeeded!!!" + CatNum.value);
$("#partName").text('__________');
},
Error: function(jqXHR, textStatus, error) {}
});
}
var button1 = document.getElementById("getBatches");
button1.addEventListener("click", funcGetBatches);
PHP
if(isset($_GET)){
$myCatNum = $_GET['CatNum.value'] + " success!";
console.log("MyCatNum: " + $myCatNum);
'________________'
}
I am logging the process in the php code and indeed see it running
I do believe that i am missing one or two pieces of code, I have marked both places in the code with ____________.
Please help,
Thanks.
I would advise you do not mix Native JavaScript and jQuery. Consider the following jQuery Script:
function funcGetBatches() {
var CatNum = $("#CatNumber").val();
console.log(CatNum);
$.ajax({
type: "GET",
url: "./php/conn.php",
data: { catnum: CatNum },
datatype: "text",
success: function(data) {
console.log("Succeeded!!!", CatNum, data);
$("#partName").text(data);
},
error: function(x, s, e) {
console.log(x, s, e);
}
});
}
$("#getBatches").click(funcGetBatches);
This will post the CatNum to the PHP Script and any Text data that is returned will be added to the #partName element.
In regards to PHP, this must echo data out.
$parts = array(
"Elbow",
"Conduit",
"Nipple",
"Coupler"
);
if(isset($_GET['catnum'])){
$cNum = (int)$_GET['catnum'];
echo $parts[$cNum];
}
As you can see, this might be a way to return new data based on the submitted GET request.
My script won't load any data in the Select2. I made a test.php with JSON data (which will be provided external after everything works. (test.php is my internal test)).
Output of test.php
[{"suggestions": ["1200 Brussel","1200 Bruxelles","1200 Sint-Lambrechts-Woluwe","1200 Woluwe-Saint-Lambert"]}]
jQuery script:
$("#billing_postcode_gemeente").select2({
minimumInputLength: 2,
tags: [],
ajax: {
url: 'https://www.vooronshuis.nl/wp-content/plugins/sp-zc-checkout/test.php',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (data) {
alert(data);
},
processResults: function(data) {
return {
results: $.map(data.suggestions, function(obj) {
return {
id: obj.key, text: obj.value
}
})
};
}
}
});
I have been searching and checking all other solutions. It it not working for me. I'm stuck.
Update: jQuery script so far
$("#billing_postcode_gemeente").select2({
minimumInputLength: 2,
placeholder: "Voer uw postcode in..",
ajax: {
url: 'https://www.vooronshuis.nl/wp-content/plugins/sp-zc-checkout/checkaddressbe.php',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (data) {
return {
ajax_call: 'addressZipcodeCheck_BE',
zipcode: '1200'
};
},
processResults: function(data) {
alert(data);
correctedData = JSON.parse(data)[0]suggestions;
alert(correctedData);
return {
results: $.map(correctedData, function(obj) {
return {
id: obj.key,
text: obj.value
}
})
};
}
}
});
Here is a working fiddle for your example.
I have done if on a local JSON object but you can replicate the same results on your response or maybe change your response accordingly.
Your data.suggestions is nothing. Because data is a JSON array whose first element is a JSON object with key suggestions and value an array of suggestions.
Run this code in your JQuery enabled browser console and you will undestand.
var data = '[{"suggestions": ["1200 Brussel","1200 Bruxelles","1200 Sint-Lambrechts-Woluwe","1200 Woluwe-Saint-Lambert"]}]';
JSON.parse(data)[0];
JSON.parse(data)[0].suggestions;
Also check this answer to see how a proper response should look like.
Updated answer:
Sending additional data to back-end:
$('#billing_postcode_gemeente').DataTable(
{
......
"processing" : true,
"serverSide" : true,
"ajax" : {
url : url,
dataType : 'json',
cache : false,
type : 'GET',
data : function(d) {
// Retrieve dynamic parameters
var dt_params = $('#billing_postcode_gemeente').data(
'dt_params');
// Add dynamic parameters to the data object sent to the server
if (dt_params) {
$.extend(d, dt_params);
}
}
},
});
Here dt_params is your additional parameter (the zipcode
that you wish to send to the server to get an appropriate response). This dt_params gets added to the datatable parameters and can be accessed in your back-end to appropriate the response.
There must be a place where you are taking the zipcode entry. On the listener of that input box you can add the below code to destroy and recreate the datatable to reflect the changes. This code will add key-value (key being zip_code) pair to the dt_params key in your request JSON:
function filterDatatableByZipCode() {
$('#billing_postcode_gemeente').data('dt_params', {
ajax_call: 'addressZipcodeCheck_BE',
zip_code : $('#some_imput_box').val()
});
$('#billing_postcode_gemeente').DataTable().destroy();
initDatatable();
}
Try this way
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return data.items;
},
cache: true
},
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
How can I load data from my PHP response via ajax into a panel?
My PHP outputs correctly and I can see a table in the response, but I can;t get it to build the data on my webpage.
Here is my jquery/ajax so far. It passed the value to PHP correctly and PHP builds the table via its echo, but what am I missing for AJAX to display the table?
PHP:
<?php
foreach ($lines as $value) {
echo "<input name='data[]' value='$value'><br/>";
}
?>
JQUERY:
$(function () {
$('#rotator').change(function (e) {
var rotator = $("#rotator").val();
$.ajax({
type: "POST",
url: "tmp/JFM/National/national.php",
data: {
rotator: rotator
},
success: function (result) {
$('#panel').load(result);
}
})
return false;
});
});
The answer to this was two fold.
I was attempting to append to my main div, which apparently can't happen. I created a new empty div and was able to load the results there.
Beyond that, the comments to change .load(results) to .html(results) were needed.
The correct jquery code is below.
$(function () {
$('#rotator').change(function (e) {
var rotator = $("#rotator").val();
$.ajax({
type: "POST",
url: "tmp/JFM/National/national.php",
data: {
rotator: rotator
},
success: function (result) {
console.log(result);
$('#test').html(result);
}
})
return false;
});
});
move your function from:
$.ajax({...,success: function(){...}});
to
$.ajax({..}).done(function(){...});
if it doesn't work, try to add async:false into the ajax object...
$.ajax({...,async:false}).done(function(){...});
Hope it helps... =}
Content is not displaying is autocomplate list as you can see in screenshot below.
I am getting this response.
[{"emp_number":1,"fname":"Arslan","lname":"Hassan"},{"emp_number":2,"fname":"Muneeb","lname":"Janjua"
},{"emp_number":3,"fname":"hr","lname":"user"},{"emp_number":4,"fname":"test","lname":""} .......... REMOVED TO MAKE IT LOOK BETTER HERE .......]
My JS Code:
$( "#search-emp" ).autocomplete(
{
source: function (request, response)
{
var form_data = {
ajax : '1',
name : $("#search-emp").val(),
actioncall : 'search-emp'
};
$.ajax({
//contentType: "application/json",
type: "POST",
dataType: 'json',
url: "_ajax.php",
data: form_data,
success: function( data )
{
response( data );
}
});
},
minLength:3,
select:function(evt, ui)
{
alert(ui.item.emp_number);
}
});
I want to display fname and lname on selected into input field.
The problem it's because jQuery autocomplete wants to have 2 fields named label and value. The content from label will be displayed in the autocomplete.
Because your server return other name for the keys you have 2 options:
Change the server to return a json like:
[{"emp_number":1,"fname":"Arslan","lname":"Hassan", "label":"Arslan Hassan", "value": "Arslan Hassan"},....]
Or on the success callback from ajax create an array with this fields (label and value) and pass this array to response() callback.
You can find more informations here: http://api.jqueryui.com/autocomplete/#option-source
Im trying to retrieve some data from JSON object which holds location information such as streetname, postcode etc. But nothing is being retrieved when i try and put it in my div. Can anybody see where im going wrong with this?
This is my ajax code to request and retrieve the data
var criterion = document.getElementById("address").value;
$.ajax({
url: 'process.php',
type: 'GET',
data: 'address='+ criterion,
success: function(data)
{
$('#txtHint').html(data);
$.each(data, function(i,value)
{
var str = "Postcode: ";
str += value.postcode;
$('#txtHint').html(str);
});
//alert("Postcode: " + data.postcode);
},
error: function(e)
{
//called when there is an error
console.log(e.message);
alert("error");
}
});
When this is run in the broswer is just says "Postcode: undefined".
This is the php code to select the data from the database.
$sql="SELECT * FROM carparktest WHERE postcode LIKE '".$search."%'";
$result = mysql_query($sql);
while($r = mysql_fetch_assoc($result)) $rows[] = $r;
echo json_encode($rows), "\n"; //Puts each row onto a new line in the json data
You are missing the data type:
$.ajax({
dataType: 'json'
})
You can use also the $.getJSON
EDIT: example of JSON
$.getJSON('process.php', { address: criterion } function(data) {
//do what you need with the data
alert(data);
}).error(function() { alert("error"); });
Just look at what your code is doing.
First, put the data directly into the #txtHint box.
Then, for each data element, create the string "Postcode: "+value.postcode (without even checking if value.postcode exists - it probably doesn't) and overwrite the html in #txtHint with it.
End result: the script is doing exactly what you told it to do.
Remove that loop thing, and see what you get.
Does your JSON data represent multiple rows containing the same object structure? Please alert the data object in your success function and post it so we can help you debug it.
Use the
dataType: 'json'
param in your ajax call
or use $.getJSON() Which will automatically convert JSON data into a JS object.
You can also convert the JSON response into JS object yourself using $.parseJSON() inside success callback like this
data = $.parseJSON(data);
This works for me on your site:
function showCarPark(){
var criterion = $('#address').val();
// Assuming this does something, it's yours ;)
codeAddress(criterion);
$.ajax({
url: 'process.php',
type: 'GET',
dataType: 'json',
data: {
address: criterion
},
success: function(data)
{
$("#txtHint").html("");
$.each(data, function(k,v)
{
$("#txtHint").append("Postcode: " + v.postcode + "<br/>");
});
},
error: function(e)
{
alert(e.message);
}
});
}