I have DataTables table with row details which are opening by clicking on row. The row details are displayed in 3 different languages which are selected by checkbox. When the row is clicked, the language is send to details.php script (langy:chLanguage) which returns json values for this selected language.
Initialy the language is set to chDe and everything is working fine until I click on another language. When the language is changed to EN or RU, or even back to DE, the returned json is empty.
index.php :
<h5>Language</h5>
<input type="checkbox" id="chDe" name="languages" checked>DE
<input type="checkbox" id="chEn" name="languages">EN
<input type="checkbox" id="chRu" name="languages">RU
<script>
var chLanguage = "chDe";
$('input[name=languages]').click(function() {
$('input[name="' + this.name + '"]').not(this).prop('checked', false);
chLanguage = [];
$('input[name=languages]:checked').each(function() {
chLanguage.push($(this).attr('id'));
});
if (chLanguage == '') {
chLanguage = 5;
}
$('#example').DataTable().ajax.reload();
});
function format ( rowData, row, $chLanguage ) {
// FOLLOWING CONSOLE.LOG RETURNS THE ACTUALLY SELECTED LANGUAGE CORRECTLY
console.log("chLanguage in format function: " + chLanguage);
var div = $('<div/>')
.addClass( 'loading slider' )
$.ajax( {
url: 'scripts/details.php',
data: {
name: rowData[0],
langy: chLanguage,
},
dataType: 'json',
type: 'post',
success: function ( json ) {
// FOLLOWING CONSOLE.LOG RETURNS [Object object] unless the language is changed, then it returns nothing
console.log("json: " + json);
var childTable = '<div id="rowdetails" class="slidera"><ul class="slider">';
childTable = childTable.concat(
'<div class="row rdstyle">' +
'<table class="detailstable detailserrors">' +
'<tr><td><b>Error class:</b></td><td>' + json[0].ERRTRIEDA + '</td></tr>' +
'<tr><td><b>Error group:</b></td><td>' + json[0].ERRSKUPINA + '</td></tr>' +
'<tr><td><b>Error:</b></td><td>' + json[0].ERRPOPIS + '</td></tr>' +
'</table>' +
'</div>
);
});
}
details.php :
$language = $_POST['langy'];
if ($language == 'chDe' ) {
$setLang = 'DE';
}else if($language == 'chEn') {
$setLang = 'EN';
} else{$setLang = 'RU';}
and $setLang is used in SQL query to filter data by language.
I hope I'm not far away from working solution, because it's working already, just the language switch don't work. Sorry not to attach working sample. I don't know how to implement all these parts including mysql db and several differenct php scripts :(
Related
This is my render code function which is working
{
"data": "assignedTo",
"render": function (data) {
var btnDetail = "<a href='/Ticket/TicketDetail?ticketId=" + data + "'>" + data + "</a>";
return btnDetail;
}
},
However I want something like
var btnDetail = "<a href='/Ticket/TicketDetail?ticketId=" + data + "'>" + data + "</a>";
where user can see assignedTo but when they click it should got to the ticketId. In short i want both ticketId and assignedTo value in single colum. Please guide me.
You need to make use of row parameter from render function. It contains all values available for current row.
row The full data source for the row (not based on columns.data)
Read more about column rendering here.
{
data: 'assignedTo',
render: function (data, type, row) {
var btnDetail = "<a href='/Ticket/TicketDetail?ticketId=" + row.TicketId + "'>" + data + "</a>";
return btnDetail;
}
}
or you can ignore data completely if you want to use render function.
{
data: null,
render: function (data, type, row) {
var btnDetail = "<a href='/Ticket/TicketDetail?ticketId=" + row.TicketId + "'>" + row.assignedTo + "</a>";
return btnDetail;
}
}
All other values returned from server will be available through row parameter.
I am new to Coding and I got stuck for hours solving this problem:
The response from AJAX is a Json two-dimesional array jqXHR[][] the first index
describes each product id, the second one holds product details like prices etc.
So all i want to is to iterate through the first index by using the button "New_Suggestion" and to update the html content in the "result_wrapper".
The response works fine, but updating the html content doesn't work at all.
Thank you for your help.
$.ajax({
type: "POST",
url: "productsuggestion.php",
data: "criteria1=" + crit1 + "&criteria2=" + crit2 + "&criteria3=" + crit3 + "&criteria4=" + crit4 + "&criteria5=" + crit5,
dataType: "json",
success: function(jqXHR) {
var sug = 0;
$('#New_Suggestion').on('click', function() {
sug = sug + 1
});
$("#result_wrapper").html(
'<div id="prod_name">' + jqXHR[sug][0] + '</div> <br>' +
'<img id="prod_pic" src="' + jqXHR[sug][4] + '">' +
'<div id="prod_price">' + jqXHR[sug][2] + '</div> <br>'
);
}
});
Firstly, your "click" handler just increments a variable when it's clicked. It doesn't touch the output at all.
Secondly, every time the ajax runs, you add another click event handler to the button, without removing the previous one(s). It's easier to declare this outside the ajax context, and set a global variable for the suggestion count.
Something like this, I think (untested):
var sugCount = 0;
var sugData = null;
$.ajax({
type : "POST",
url : "productsuggestion.php",
data : "criteria1="+crit1+"&criteria2="+crit2+"&criteria3="+crit3+"&criteria4="+crit4+"&criteria5="+crit5,
dataType: "json",
success: function(data){
//reset global data after each ajax call
sugCount = 0;
sugData = data;
writeSuggestions(sugCount, sugData); //output the initial set of suggestions
}
});
$('#New_Suggestion').on('click',function(){
sugCount = sugCount + 1;
writeSuggestions(sugCount, sugData); //output updated suggestions
});
function writeSuggestions(count, data)
{
$("#result_wrapper").html('<div id="prod_name">'+data[count][0]+'</div> <br>'+
'<img id="prod_pic" src="'+data[count][4]+'">'+
'<div id="prod_price">'+data[count][2]+'</div> <br>');
}
I have this ajax request that's working on pulling the data I need but I would like to make this a search function that lets the user pull in data as requested. Is there away to take my working code and repurpose it to work with the search box? Not sure how to go about this...
function foodQuery(){
var foodURL = "http://api.example.com/items?key=123456789";
$.ajax({
url: foodURL,
type: 'GET',
contentType: "text/plain",
dataType: 'json',
success: function(json) {
$.each(json.products, function(index, product) {
// build product block
var htmlString = '<div class="product large-3 columns">';
//open imgwrap
htmlString += '<div class="imgwrap">';
//get img src
htmlString += ' <img class="item_img" src="http://api.example.com/assets/images/' + product.itemCode + '#2x.jpg" />';
// close imgwrap
htmlString += '</div>';
// open textwrap
htmlString += '<div class="textwrap">';
// get productName
htmlString += '<h1 class="product_headline">' + product.productName + '</h1>' ;
// get itemCode
htmlString += '<h4 class="item_id" >#' + product.itemCode + '</h4>';
// get description
htmlString += '<p class="product_desc">' + product.description + '</p>';
// open price
htmlString += '<div class="price">';
// get price & close div
htmlString += '<span class="dollar"><span class="usd">$</span>' + product.price + '</span> <span class="product_desc">per weight</span></div>'
// close divs
htmlString += '</div>';
//console.log(htmlString);
$('.listing').append( $(htmlString) );
}); //end each
}, // end success
error: function(e) {
console.log(e.message);
$('.listing').append( '<h1 class="errmsg" >Sorry, there was an unkown error.</h1>' );
} // end error
}); // end ajax request
}
It depends on the API that you are using, but assuming the API has a way to search using text, you could have something that looks like the following:
function foodQuery(searchTerm) {
var foodUrl = '/path/to/api?query=' + searchTerm;
$.ajax({
// fill in AJAX call here and callback handling like you are doing
})
}
$('#searchBox').on('keypress', function() {
foodQuery($(this).val());
});
So every time the user types, the function foodQuery() will be run with the current search term. You may want to add some delay so that the API is not hit every time the user types a new character.
First create a text input,
<input type="text" id="search">
Then listen for the keyup event of that input. Get the value of the input as the user is typing (if this is the behavior you want) and call the foodQuery function sending the value of the input as a parameter. Then use this value as the key parameter of the foodURL. Then perform the ajax request the same way you did.
$(function() {
/**
Whenever user types a letter and release the key, its value is passed to the
foodQuery function
**/
$("#search").keyup(function() {
var value = $(this).val();
foodQuery(value);
});
function foodQuery(key) { // key is passed as a parameter
var foodURL = "http://api.example.com/items?key=" + key;
/** Send you ajax request here and manipulate the DOM the same way yo do. Since we are
fetching new products continuously, it is better to clear the .listing element
every-time before you update it. **/
$(".listing").html("");
/**
$.ajax({
url: foodURL,
type: 'GET',
contentType: "text/plain",
dataType: 'json',
success: function(json) { **/
}
});
I have a search function that is suppose to search a name from the database, and then when the user clicks add, the item choosen has to appear below the search field, in short it has to be posted back so that the user can re-select his/her second option from the search element so that all the selected options can be saved in the database. The problem im facing is that after I click add im getting undefined value back instead of the one I choose and my response is a name instead of an Id number, here is my code and a picture below.
MODEL
public function getName($id)
{
$select = $this->select()
->where('service_provider_id LIKE "' . $id . '%"')
->order('service_provider_name');
return $this->fetchAll($select);
}
CONTROLLER
{
$id = $this->getRequest()->getParam('id');
$mdlserviceprovider = new Model_ServiceProviders();
$serviceprovider = $mdlserviceprovider ->getName($id);
$arr_rtn = array();
if (count($results) > 0){
foreach($results as $result)
{
$myarr = array( 'label' => $result->service_provider_name,
'value' => $result->service_provider_name,
'id' => $result->service_provider_id
);
array_push($arr_rtn, $myarr);
}
}
echo Zend_Json::encode($arr_rtn);
}
PHTML/AJAX
$('#add1').click(function(){
var data = {};
data['sp'] = $("#search").val();
$.ajax({
url:'<?php echo $this->baseUrl()?>/ajax/postserviceprovider/id',
type:'post',
dataType: "json",
data: data,
success:function(data){
var row = '<tr><td>' + data["serviceprovider"] + '</td></tr>';
$('#t1').append(row);
//alert();
}
});
});
Thanks in advance
You can use data["value"] instead of data["serviceprovider"]:
var row = '<tr><td>' + data["value"] + '</td></tr>';
Since you've encoded the array which contains three keys: label, value and id. So there's no serviceprovider key at this moment for Zend to encode.
You are looking for a key that doesn't exist in the array you are returning try this
var row = '<tr><td>' + data['label'] + '</td></tr>';
Or this
var row = '<tr><td>' + data['value'] + '</td></tr>';
As those are the two keys you defined in your PHP page
Try
var row = '<tr><td>' + data[0].value + '</td></tr>';
Also try to put an alert() in the success function like,
alert(JSON.stringify(data));
and see what is included in it..
From what I see I think you are ruturning a multidimensional array from php so I would try something like this in javascript:
$('#add1').click(function(){
var data = {};
data['sp'] = $("#search").val();
$.ajax({
url:'<?php echo $this->baseUrl()?>/ajax/postserviceprovider/id',
type:'post',
dataType: "json",
data: data,
success:function(data){
data.each(function(index, el){
var row = '<tr><td>' + el.label + '</td></tr>';
$('#t1').append(row);
//alert();
}
}
});
});
In your controller try:
$this->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
return $this->_helper->json(array('key1' => $val1, 'key2' => $val2, ...));
I have a web page which fill's form data based on some json data sent from a web service. Once the form is ready to be submitted a function is called which takes all the form data turns it into a xml-formatted string then parses the xml so it becomes a valid xml object. This is where the problem happens, once this data is turned into an xml I would like to post this data back to the web service so the database can be updated. However using the $.ajax() function to post this data, neither the success nor error function within are ever called. This lead's me to believe the ajax function is never being called or run. Below are the code snippets:
submit button for form:
<input type="submit" name="submitbutton" id="submitbutton" value="Submit" onclick="postData()"/>
postData function:
function postData()
{
//gathering all inputs
var cb = document.getElementById('paymentList');
var selected_cb = cb.options[cb.selectedIndex].text;
var pguid = getParameterByName('guid');
var xmlString = '<string>' +
addField('approver', $('#approver').val()) +
addField('companyName', $('#companyName').val()) +
addField('emailAddress', $('#emailaddress').val()) +
addField('address1', $('#address1').val()) +
addField('address2', $('#address2').val()) +
addField('city', $('#city').val()) +
addField('province', $('#province').val()) +
addField('country', $('#country').val()) +
addField('postalCode', $('#postalcode').val()) +
addField('phoneNumber', $('#phone').val()) +
addField('paymentMethod', selected_cb);
//gathering all table data now
xmlString+='<contractData>';
$('#table tbody tr:has(img[src="images/checkmark.png"])').each(function() {
xmlString += '<contract>' + addField('vendorPart', $('td:eq(1)', this).text()) +
addField('description', $('td:eq(2)', this).text()) +
addField('price', $('td:eq(3)', this).text()) +
addField('quantity', $('td:eq(4) input', this).val()) + '</contract>';
});
xmlString += '</contractData></string>';
//hard coded var for purpose of this example, as web service name will be
var properid = 'somedata';
xmlDoc = $.parseXML( xmlString );
$xml = $( xmlDoc );
//this function I believe is never run as neither alerts below are posted
$.ajax({
type: "POST",
url: "http://www.webservice.com/service.asmx/sendMeMyData",
data: {properdata:properid, xml: $xml},
dataType: "text",
success: function() {
alert("posted");
},
error: function ()
{
alert("error");
}
});
}
addField function (just so you know what it does when it's called in postData()):
function addField(name, value) { // Add a single element and value
value = value.replace(/&/g, '&').replace(/</g,'<').replace(/>/g,'>');
return '<' + name + '>' + value + '</' + name + '>';
}