JQuery AJAX retrieving an Array of Objects - javascript

I am trying to use json_encode so that my jquery ajax function can retrieve data from my php script however the array I am attempting to encode and retrieve is an array of objects
$la_uselessinfo = array();
$lv_cnt = 0;
$uselessinfo = pg_execute($gv_dbconn, "uselessinfo_cur", array());
while($la_row = pg_fetch_row($uselessinfo)) {
$la_uselessinfo[$lv_cnt]["uinf_idno"] = $la_row[0];
$la_uselessinfo[$lv_cnt]["uinf_desc"] = $la_row[1];
$lv_cnt = $lv_cnt + 1;
}
echo json_encode($la_uselessinfo);
I am trying to retrieve this using the jquery ajax function
$.ajax({
url : 'scripts/phpfunctions.php',
type : 'GET',
data : {'action':'sel_uselessinfo'},
success : function(data) {
//console.log(data);
console.log(data["uinf_desc"][0]);
},
error : function(log) {
console.log(log.message);
}
});
I am getting the following error
Uncaught TypeError: Cannot read property '0' of undefined
I can't tell if it's going wrong in the php code or the jquery code, what is the correct way to retrieve an array of objects?

Change your PHP to:
$la_uselessinfo = array();
$lv_cnt = 0;
$uselessinfo = pg_execute($gv_dbconn, "uselessinfo_cur", array());
while($la_row = pg_fetch_row($uselessinfo)) {
$la_uselessinfo[$lv_cnt]["uinf_idno"] = $la_row[0];
$la_uselessinfo[$lv_cnt]["uinf_desc"] = $la_row[1];
$lv_cnt = $lv_cnt + 1;
}
echo json_encode($la_uselessinfo); //$la_uselessinfo is already an array, no need to wrap it again, and doing so causes you to misjudge the depth of your array
Then change your jQuery to :
$.ajax({
url : 'scripts/phpfunctions.php',
type : 'GET',
data : {'action':'sel_uselessinfo'},
success : function(data) {
//console.log(data);
console.log(data[0]["uinf_desc"]); // this line changed
},
error : function(log) {
console.log(log.message);
}
});
To loop over your results do this:
// sample data
var data = [{
"uinf_idno": "1",
"uinf_desc": "website db "
}, {
"uinf_idno": "2",
"uinf_desc": "local apache "
}]
$.each(data,function(i,e){
var uinf_idno = e.uinf_idno;
var uinf_desc = e.uinf_desc;
$('#result').append('uinf_idno= '+uinf_idno+' and uinf_desc= '+uinf_desc+' <br>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>

$.ajax({
url : 'scripts/phpfunctions.php',
type : 'GET',
data : {'action':'sel_uselessinfo'},
dataType: "json",
success : function(data) {
console.log(data[0]["uinf_desc"]);
console.log(data[0]["uinf_desc"]);
},
It should be data[0]["uinf_desc"] as written in your PHP

Related

Format Json returned by AJax call and assign it to javascript variable

I have script that return this from the server using ajax call
//ajax call
var comment_frm = $('#comment_form');
comment_frm.submit(function (ev) {
$.ajax({
type: comment_frm.attr('method'),
url: comment_frm.attr('action'),
data: comment_frm.serialize(),
success: function (data) {
if (data == 1){
$("#success_message").show();
$('#comment_form').trigger("reset");
}
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
//prevent the page from loading
ev.preventDefault();
});
[{"commentID":"5","name":"name 1","comment":"comment 1","comment_time":"1460652379","blog_unique_id":"19","comment_status":"1"},{"commentID":"6","name":"name 2","comment":"comment 2","comment_time":"1460652387","blog_unique_id":"19","comment_status":"1"},{"commentID":"7","name":"name 3","comment":"comment 3","comment_time":"1460652416","blog_unique_id":"19","comment_status":"1"},{"commentID":"8","name":"name 4","comment":"comment 4","comment_time":"1460652425","blog_unique_id":"19","comment_status":"1"},{"commentID":"9","name":"name 5","comment":"comment 5","comment_time":"1460652433","blog_unique_id":"19","comment_status":"1"}]
I want to format it to look like this and assign the json result to a javascript variable
var comment_array = {"Comments": [{"commentID":"5","name":"name 1","comment":"comment 1","comment_time":"1460652379","blog_unique_id":"19","comment_status":"1"},{"commentID":"6","name":"name 2","comment":"comment 2","comment_time":"1460652387","blog_unique_id":"19","comment_status":"1"},{"commentID":"7","name":"name 3","comment":"comment 3","comment_time":"1460652416","blog_unique_id":"19","comment_status":"1"},{"commentID":"8","name":"name 4","comment":"comment 4","comment_time":"1460652425","blog_unique_id":"19","comment_status":"1"},{"commentID":"9","name":"name 5","comment":"coment 5","comment_time":"1460652433","blog_unique_id":"19","comment_status":"1"}]}
//php code
$operation = $_POST['operation'];
if($operation == 'add_comment'){
$name = $_POST['name'];
$comment = $_POST['comment'];
$blog_id = $_POST['blog_id'];
$comment_status = 1;
if ($me->add_comment($name, $comment, $blog_id)){
//get the comment
$comment_array = $me-> fetch_moderated_comment($blog_id);
echo json_encode($comment_array);
}else{echo 10;}
}
I will also love to know how to read get that from the call... Can someone please help me
Working Example
You could assign a variable to hold your new 'Comments' array and then push to it:
var a = [{"commentID":"5","name":"name 1","comment":"comment 1","comment_time":"1460652379","blog_unique_id":"19","comment_status":"1"},{"commentID":"6","name":"name 2","comment":"comment 2","comment_time":"1460652387","blog_unique_id":"19","comment_status":"1"},{"commentID":"7","name":"name 3","comment":"comment 3","comment_time":"1460652416","blog_unique_id":"19","comment_status":"1"},{"commentID":"8","name":"name 4","comment":"comment 4","comment_time":"1460652425","blog_unique_id":"19","comment_status":"1"},{"commentID":"9","name":"name 5","comment":"comment 5","comment_time":"1460652433","blog_unique_id":"19","comment_status":"1"}]
var b = {"Comments": []};
for (var prop in a) {
b.Comments.push(a[prop]);
}
echo json_encode(['Comments' => $comment_array]);
If I understand correctly, just wrap the result in an object literal:
vat result = {"Comments": comment_frm};

Difficulties using AJAX to pass input value to controller

I have this PHP CodeIgniter code where in the view I am getting input from a text field. Using AJAC I am trying to pass this value to the controller using GET request. The controller will then call a function from my model to retrieve a database record matching the search criteria.
For some reason it doesn't work. I tried to do a var dump in the controller to see if the value is passed by AJAX, but I am not getting anything. Any ideas what I am doing wrong and why I can't receive the form value in the controller?
View:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.13.3/jquery.min.js"</script>
<script language="Javascript">
$(document).ready(function () {
$('#submitbutton').click(function () {
$.ajax({
url: "../../index.php/testcontroller/getdatabasedata",
data: {
'searchvalue' : $('#inputtext').val()
},
method: 'GET'
}).done(function (data) {
var dataarray = data.split('##');
$('#question').html(dataarray[ 1 ]);
$('#answer1').html(dataarray[ 2 ]);
});
return false;
});
});
</script>
</body>
Controller
public function getdatabasedata()
{
$this->load->model('testmodel');
$year = $this->input->get('searchvalue');
//I TRIED TO DO A VARDUMP($YEAR) BUT I DON'T GET ANYTHING!
$movie = $this->testmodel->findquestion($year);
$moviesstring = implode(",", $movie);
echo $moviesstring;
}
Model
function findquestion($searchvalue)
{
$this->db->where('answer1', $searchvalue);
$res = $this->db->get('questions');
var_dump($res)
if ($res->num_rows() == 0)
{
return "...";
}
$moviearray = $res->row_array();
return $moviearray;
}
Script:
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script language="Javascript">
$(document).ready(function ()
{
$("#submitbutton").bind("click",function()
{
var target_url = '<?php echo(base_url()."testcontroller/getdatabasedata") ; ?>';
var data = {'searchvalue' : $('#inputtext').val() };
$.ajax ({
url : target_url,
type: 'GET',
data: data,
cache: false,
success: function(controller_data)
{
var dataarray = controller_data.split('#');
$('#question').html(dataarray[1]);
$('#answer1').html(dataarray[3]);
},
});
return false;
});
});
</script>
.bind("click",function() - add quotes to click event.
var dataarray = controller_data.split('#'); - split
data caracter must match character in implode function in controller.
Controller:
public function getdatabasedata(){
$this->load->model('testmodel');
$year = $this->input->get('searchvalue');
$movie = $this->testmodel->findquestion($year);
$separated = implode("#", $movie);
echo $separated;
}
Hope this helped.
I will share my usual ajax code that I use in my views , make sure your base url is correct
$("#submitbutton").bind("click",function()
{
var target_url = '<?php echo(base_url()."testcontroller/getdatabasedata") ; ?>';
$.ajax
(
{
url : target_url,
type: "GET",
// data: {'searchvalue' : $('#inputtext').val()},
cache: false,
success: function(data)
{
alert(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("error during loading ....");
}
});
});// end loading via ajax
and in your controller just echo something
public function getdatabasedata()
{
//$this->load->model('testmodel');
//$year = $this->input->get('searchvalue');
//I TRIED TO DO A VARDUMP($YEAR) BUT I DON'T GET ANYTHING!
//$movie = $this->testmodel->findquestion($year);
//$moviesstring = implode(",", $movie);
//echo $moviesstring;
echo "hello";
}

how to separate the json_encode value in javascript

i get the json data from the php to ajax how can i separate the value of the console data just like that
i have to set in my id only the agent name not the hole "name" : "Testing"
This is my console value
[{"agent_module_id":"1","agent_module_number":"101","name":"Testing","description":";;;","agent_mobile":"0123456789","email":"d#gmial.com","category":"","unit_price":null,"cost_price":null,"deleted":"0"}]
This is My PHP Code
$this->load->model("member");
$agent_value = $_POST['agent_value'];
$data["results"] = $this->member->get_agent_data($agent_value);
echo json_encode($data["results"]);
This is my JavaScript Code
function agentForm()
{
var agent_id = document.getElementById("agent_code").value;
if(agent_id !='')
{
document.getElementById("agent_operation_form").style.display ="block";
$.ajax({
url: '<?php echo site_url("members/get_agent_data");?>',
data: { 'agent_value': agent_id},
type: "post",
/* success: function(data){
// document.write(data); //just do not use document.write
var fd_values = data.split(/,/);
document.getElementById("agent_name").value=fd_values[2]; // unique _id
document.getElementById("agent_mobile_number").value=fd_values[1];
console.log(data);*/
success: function(data){
// document.write(data); //just do not use document.write
var fd_values = $.parseJSON(data);
document.getElementById("agent_name").value = fd_values[0].name; // unique _id
document.getElementById("agent_mobile_number").value = fd_values[0].agent_module_number;
console.log(fd_values);
}
}
});
}else
{
document.getElementById("agent_operation_form").style.display ="none";
}
}
Thanx in advance
Try as (Not Tested). You can parse your JSON data using $.parseJSON
success: function(data){
// document.write(data); //just do not use document.write
var fd_values = $.parseJSON(data);
document.getElementById("agent_name").value = fd_values[0].name; // unique _id
document.getElementById("agent_mobile_number").value = fd_values[0].agent_module_number;
console.log(fd_values);
}

Sending data and file with ajax and jquery

I know that there is a topic speaking about this
I followed it but i still have problem with my code
Here is my code
var id_dossier = $('#jform_id').val();
var date_facture = $('#jform_date_facture').val();
var date_paiement_facture = $('#jform_date_paiement_facture').val();
var mode_paiement_facture = $("select#jform_mode_paiement_facture option").filter(":selected").val();
var idBanque = $("select#jform_id_banque option").filter(":selected").val();
var idCompte = $("select#jform_id_compte option").filter(":selected").val();
var cheque_facture = $('#jform_cheque_facture').val();
var montant_cheque = $('#jform_montant_cheque').val();
var numero_facture = $('#jform_numero_facture').val();
var numero_retenu_source = $('#jform_numero_retenu_source').val();
var echeance = $('#jform_valeur_echeance').val();
var document_facture = document.getElementById('facture_document');
the document_facture is the file input
Then I put the data in a other var I called donnee
var donnee ={
'id_dossier' : id_dossier,
'date_facture' : date_facture,
'date_paiement_facture' : date_paiement_facture,
'mode_paiement_facture' : mode_paiement_facture,
'id_banque' : idBanque,
'id_compte' : idCompte,
'cheque_facture' : cheque_facture,
'montant_cheque' : montant_cheque,
'numero_facture' : numero_facture,
'numero_retenu_source' : numero_retenu_source,
'echeance' : echeance,
'document_retenu_source' : document_retenu_source
};
Well in the other question there is this line of code and I dont know what is and how could I replace it in my code
var formData = new FormData($(this)[0]);
so I replace it with this
var formData = new FormData();
formData.append('documents', document_facture.files[0]);
And I add it in the data of the Ajax Request
$.ajax({
type: 'post',
cache: false ,
url: 'index.php?option=com_tktransit&task=dossier.genererFacture',
data: {donnee:donnee,formData:formData },
success: function(resp)
{
if(resp == "1")
{
ajax_result_message("<?php echo JText::_( 'COM_TKTRANSIT_DOSSIER_FACTURE_GENERER' ); ?>",0,'facture');
afficher_button(2);
$('#td_facturation').html("<?php echo JText::_( 'COM_TKTRANSIT_FACTURE_DEJA_FACTURER' ); ?>");
$('#td_check_facturation').hide();
generate_pdf(id_dossier);
}
else if(resp == "2")
{
ajax_result_message("<?php echo JText::_( 'COM_TKTRANSIT_DOSSIER_FACTURE_NUMERO_FACTURE_EXISTE_DEJA' ); ?>",1,'facture');
}
else
ajax_result_message("<?php echo JText::_( 'COM_TKTRANSIT_DOSSIER_FACTURE_ERREUR_GENERER_FACTURE' ); ?>",1,'facture');
$("#ajax-facture-image_loader").hide();
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
ajax_result_message("<?php echo JText::_( 'COM_TKTRANSIT_DOSSIER_FACTURE_ERREUR_GENERER_FACTURE' ); ?>",1,'facture');
$("#ajax-facture-image_loader").hide();
}
});
well When I click on the button to call the ajax function I got this error
TypeError: 'append' called on an object that does not implement interface FormData.
Any help please
You should placed all your variables on the form in the html page, so, the line
var formData = new FormData($(this)[0]);
will become
var formData = new FormData($('#yourFormUniqueId')[0]);
I think you can find more details by this answer

php script echo displays in console instead of text inputs

I have this php script:
<?php
add_action('wp_ajax_nopriv_getuser', 'getuser');
add_action('wp_ajax_getuser', 'getuser');
function getuser($str)
{
global $wpdb;
if(!wp_verify_nonce($_REQUEST['_nonce'], 'ajax-nonce'))
{
die('Not authorised!');
}
$myoption = get_option( 'fixformdata_options' );
$myoptionValue = maybe_unserialize( $myoption );
$result2 = $wpdb->get_row
(
$wpdb->prepare
(
"SELECT * FROM {$myoptionValue[tablename]} WHERE personeelsNummer = %s", 1
)
);
if($result2)
{
echo json_encode( $result2 );
}
}
And this javascript file:
jQuery(document).ready(function($){
jQuery('#input_1_2').change(function()
{
jQuery.ajax({
type : 'post',
dataType : 'json',
_nonce : myAjax.ajaxurl,
url : myAjax.ajaxurl,
data : {action: 'getuser', value: this.value},
succes: function(response){
var parsed = JSON.parse(response);
var arr = [];
for(var x in parsed){ arr.push(parsed[x]);}
jQuery('#input_1_3').val(arr[1]);
jQuery('#input_1_4').val(arr[2]);
}
});
});
});
Purpose of the scripts:
When a text inputs change, use the value of this text input to display some database data in another text input.
Now I have 2 problems:
I can't get the value of the text input to the function getuser()
When I hardcode a value in the sql statement, I get the results, but they display in the console instead of using:
.
success: function(response){
var parsed = JSON.parse(response);
var arr = [];
for(var x in parsed){ arr.push(parsed[x]);}
jQuery('#input_1_3').val(arr[1]);
jQuery('#input_1_4').val(arr[2]);
}
How can I resolve this, I'm new in Wordpress and Ajax.
By the looks of your php _nonce should be inside data. You cant use this.value as this is the jQuery ajax function itself so Try:
jQuery('#input_1_2').change(function()
$value = $(this).val();
jQuery.ajax({
type : 'post',
dataType : 'json',
url : myAjax.ajaxurl,
data : {
action: 'getuser',
value: $value,
_nonce : myAjax.ajaxurl
},
succes: function(response){
var parsed = JSON.parse(response);
var arr = [];
for(var x in parsed){ arr.push(parsed[x]);}
jQuery('#input_1_3').val(arr[1]);
jQuery('#input_1_4').val(arr[2]);
}
});
});
In the php you will find value in
$_POST['value'];
Edit
inside the php add
header('content-type:application/json');
before
echo json_encode( $result2 );
on the js you shoud then not need
JSON.parse(response)
you shoud have the results in the array, ie:
response[0]
etc

Categories