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, ...));
Related
I want to pass an array to my AJAX function within the success function of an AJAX call. This array is data from my database using a global $wpdb; because this is easy to use and I know how to. Is there a way to pass this array to the AJAX function? Or is there a way to just get the data in AJAX?
I got this in my script tag and it is working:
jQuery(document).ready(function(){
jQuery('#date-select').on('change',function(){
var seldate= jQuery(this).val();
if(seldate!=''){
var seldateEdited = seldate.replace("T", " ");
jQuery.ajax({
type:'POST',
url:'http://esr-berlin.de/wp-admin/admin.php?page=einteilung_erstellen',
data:'var='+seldate,
success:function(html){
var output = '<option value="">Wähle HSR1</option>';
jQuery.each(html.data, function(i,s){
var newOption = s;
output += '<option value="' + newOption + '">' + newOption + '</option>';
});
jQuery('#hsrPop').empty().append(output);
}
});
}
});
});
EDIT
I forgot something important. For the array or especially for the sql query I need a variable that I have in javascript. So I basically need another AJAX Call, right? How would I do that?
You can encode the array in the PHP file and return this. It will just return a string to your AJAX function
json_encode($array)
https://www.php.net/manual/en/function.json-encode.php
You can then use to convert it into a Javascript array for processing
JSON.parse(json)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Assuming Your server side code(admin.php) something like:-
$result = array();
//your code here to fetch data dynamically
$result['status'] = True; //based on your conditions optional
$result['data'] = array(0=>"option1",1=>"option2",2=>"option3") ;
echo json_encode($result);
Hope this will help.
jQuery(document).ready(function()
{
jQuery('#date-select').on('change',function()
{
var seldate= jQuery(this).val();
if(seldate!='')
{
var seldateEdited = seldate.replace("T", " ");
jQuery.ajax({
type:'POST',
dataType:'json', //added to receive json format data
url:'http://esr-berlin.de/wp-admin/admin.php?page=einteilung_erstellen',
data:'var='+seldate,
success:function(html)
{
//here you can check if html.status is True/False .. optional
var output = '<option value="">Wähle HSR1</option>';
jQuery.each(html.data, function(i,s)
{
var newOption = s;
output += '<option value="' + newOption + '">' + newOption + '</option>';
});
jQuery('#hsrPop').empty().append(output);
}
});
}
});
});
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 :(
I'm developing a ps module which let you classify the product attachment in categories an display them in the front product page.
I'm using a draggable list with the attachment, and when you drop them to the category it turns to an option tag, each category has a select tag where to drop the attachment.
I want to save the attachments and the category where they was dropped, so I thought make an ajax call to bring the data to my module class but I'm new with ajax and cant approach it.
this is what I've made:
the js code (inside the proper .tpl):
<script>
$( ".droptrue" ).droppable({
drop: function( event, ui ) {
//add <option> tag when an attachment is dropped to category's select
$(event.target).append('<option value="' + ui.draggable.attr('id') + '" selected>'+ui.draggable.text()+'</option>');
//remove the <li> wich contained the attachment data
ui.draggable.fadeOut("slow").remove();
var val = $('#categoryAttachmentArr').val();
//var tab = val.split(',');
//for (var i=0; i < tab.length; i++)
//if (tab[i] == $(this).val())
// return false;
//create an array with the next format: 'id_category(1)'-'id_attachment(1)','id_category(2)'-'id_attachment(2)'[....]
//the comma will be the main character that will be splitted
$('#categoryAttachmentArr').val(val + ui.doppable.attr('id') + '-' + ui.draggable.attr('id') +',');
}
});
$('#submitAddProduct').click(function(e){
$.ajax({
type: 'POST',
url: baseDir + 'modules/adjuntos/classes/CategoryAttachment.php',
data: {
ajax: true,
action: \'CategoryArray\',
cat_array: $('#categoryAttachmentArray').val(),
}
dataType: 'json',
success: function(json) {
console.log($('#categoryAttachmentArray').val());
}
});
})
$( ".ui-state-default" ).draggable({
revert: "valid",
});
</script>
And my class:
class CategoryAttachment extends Objectmodel
{
//other functions
public function ajaxProcessCategoryArray()
{
$CategoryAttachmentArr = Tools::getValue('cat_array')
}
}
you can't connect directly to any class. you have to use the controller to do this.
Ajax send data to controller
Controller save data using class
Controller return result to browser (javascript)
Finaly I got the solution, maybe one of you guys will have this problem in the future.
My code in the .tpl:
$( ".ui-state-default" ).draggable();
$( ".droptrue" ).droppable({
drop: function( event, ui ) {
//add <option> tag when an attachment is dropped to category's select
$(event.target).append('<option value="' + ui.draggable.attr('id') + '" selected>'+ui.draggable.text()+'</option>');
$('#selectAttachment1').append('<option value="' + ui.draggable.attr('id') + '" selected>'+ui.draggable.text()+'</option>')
//remove the <li> wich contained the attachment data
ui.draggable.fadeOut("slow").remove();
var val = $('#categoryAttachmentArr').val();
//make a serialize() type array
$('#categoryAttachmentArr').val(val + $(this).attr('id') + "=" + ui.draggable.attr('id') +"&");
var value = $('#arrayAttachments').val();
var tab = value.split(',');
for (var i=0; i < tab.length; i++)
if (tab[i] == ui.draggable.attr('id')){
return false;
}
$('#arrayAttachments').val(value+ui.draggable.attr('id')+',');
}
});
$('#submitCategories').click(function(e){
var array = $('#categoryAttachmentArr').val()
$.ajax({
url: '../modules/adjuntos/ajax-call.php',
data: {
action: 'handlearray',
token:new Date().getTime(),
cat: array
},
method: 'POST',
success:function(data){
$('#result').html(data);
}
});
});
the ajax call goes to my ajax-call.php file:
<?php
//load ps config
require_once(dirname(__FILE__).'../../../config/config.inc.php');
require_once(dirname(__FILE__).'../../../init.php');
require_once('adjuntos.php');
//adjuntos.php is the name of my module main file
if(Tools::getIsset('token') && Tools::getIsset('action'))
{
$mp = new Adjuntos;
echo $mp->handleArray();
}
The handleArray function in my module main file:(it make a call to my custom class)
public static function handleArray()
{
$html = '';
$array = Tools::getValue('cat');
$arrayExplode = explode("&", $array);
foreach($arrayExplode as $value)
{
$finalArr = explode("=", $value);
if (!CategoryAttachment::postProcess($finalArr))
{
$html .= '<p style="color:red;>Fallo</p>"';
}
}
$html .= '<p style="color:green;>Correcto</p>"';
return $html;
}
The function in my custom class:
public static function postProcess($finalArr)
{
return Db::getInstance()->execute(
'UPDATE ps_attachment SET id_category = '.$finalArr[0].' WHERE id_attachment = '.$finalArr[1]
);
}//end
This way is working like a charm, and make the code more scalable
I have this html:
<select id="test"></select>
And This ajax code:
<script>
function get(name){
if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
//url: localhost/web/index.php?name='whatever'
var value = get('name');
$(document).ready(function(){
$('select').select2();
$.ajax({
type: "POST",
url: 'getValues.php',
data: {'test': $("#test").val(),'isAjax':true},
dataType:'json',
success: function(data) {
var select = $("#test"), options = '';
select.empty();
for(var i=0;i<data.length; i++)
{
options += "<option value='"+data[i].id+"'>"+ data[i].name +"</option>";
}
select.append(options);
}
});
});
</script>
I need to set the value of select as taken from the url,which is (var value).
The value is working fine,as I tested it in alert.
Any help is appreciated
1) You can use .val() after appending options:
select.append(options);
select.val(value);
2)
or add attribute selected to option having same value while building the options html string.
options += "<option value='"+data[i].id+"' "+(data[i].id == value ? "selected" : "") +">"+ data[i].name +"</option>";
Chances are its the AJAX that is causing the issue. you need to trim() the response to remove a whitespace at the end of the returned data. Try the following :
success: function(data) {
var response = data.trim(), select = $("#test"), options = '';
select.empty();
for(var i=0;i<response.length; i++)
{
options += "<option value='"+response[i].id+"'>"+ response[i].name +"</option>";
}
select.append(options).val(value);
}
My problem is solved.
The problem was that the returned value has space,which is taken from url as +
So I replaced "+" by " "
Thanks all !
I am getting the results of a db query in php and return it thru ajax in a json array, but when I try to access the data it gives me data as 'undefined'
why is that happening?
Here is my php code:
<?php
$tipo_prod= $_POST['tipo_prod'];
$conn = oci_connect("admin", "admin", "localhost/XE");
$query = "SELECT COD_PRODUCTO, NOMBRE FROM PRODUCTO WHERE COD_TIPO_PROD=" . $tipo_prod;
$exec= oci_parse($conn, $query);
oci_execute($exec);
//Check connection!!!
$exec= oci_fetch_array($exec);
echo json_encode($exec);
?>
And my ajax code:
$.ajax({
url : "trae_producto.php",
type : "POST",
data: {"tipo_prod" : tipo_prod},
success : function(data){
data = JSON.stringify(data);
$.each(data, function(index, value){
$('#producto').append("<option value='" + value.COD_PRODUCTO + "'>" + value.NOMBRE + "</option>");
});
}});
try doing::
$.ajax({
url : "trae_producto.php",
type : "POST",
data: {"tipo_prod" : tipo_prod},
dataType: "json",
success : function(data){
$.each(data, function(index, value){
$('#producto').append("<option value='" + value.COD_PRODUCTO + "'>" + value.NOMBRE + "</option>");
});
}});
try adding Content-Type header in your PHP code, like:
header('Content-Type: application/json');
echo json_encode($exec);
Added:
do something like
while($data = oci_fetch_array($exec)) {
$out[] = $data;
}
echo json_encode($out);
$.ajax({
url : "trae_producto.php",
type : "POST",
dataType: "json",
data: {"tipo_prod" : tipo_prod},
success : function(data){
/* data = JSON.stringify(data); */
$.each(data, function(index, value){
$('#producto').append("<option value='" + value.COD_PRODUCTO + "'>" + value.NOMBRE + "</option>");
});
}});
I don't know what's your real return from PHP script but if it assumed as correct, the AJAX seems have some flaws.
JSON.stringify will make your object to string type so the jQuery iterator won't work.
use "dataType" attribute to inform AJAX it will getting JSON object
You're trying to turn the result that it gives you into JSON. jQuery parses it already for you, just remove the line for JSON.stringify.
$.ajax({
url : "trae_producto.php",
type : "POST",
data: {"tipo_prod" : tipo_prod},
success : function(data){
$.each(data, function(index, value){
$('#producto').append("<option value='" + value.COD_PRODUCTO + "'>" + value.NOMBRE + "</option>");
});
}
});
At first, debug through firebug whether you are getting a JSON object, as well as your server is sending data. Then, instead of data = JSON.stringify(data);, you can use data = JSON.parse(data);