I am calling a PHP function from a JQuery ajax method. Below is how the response looks from ajax call:
My question is: how to iterate over this array in jquery to get the values?
I am getting "Cannot use 'in' operator to search for 'length' in Array" if I iterate using $.each.
Below is the Code:
$("#member_country").change(function() {
var country = $(this).val();
//alert(country);
var ajax_url_mtypes = ins_membership_ajax.ajax_url;
//alert(ajax_url_mtypes);
jQuery.ajax({
url:ajax_url_mtypes,
data:{country:country,
action: "ins_get_membershiptypes_from_country"},
method:'GET',
contentType: "application/json;charset=utf-8",
success:function(response) {
//var resp = $.trim(response);
alert(response);
$.each(response, function( key, value ) {
alert( key );
alert( value );
});
}
});
PHP Code:
public static function getMembershipTypesNonAdmin($country){
$rtn = array();
global $wpdb;
$table = $wpdb->prefix.self::TABLE_NAME;
$query = "SELECT * FROM {$table} where admin_only = 'false' order by member_type";
$results = $wpdb->get_results($query);
if($results){
foreach($results as $row){
$membership_type = INS_Membership_Types::loadById($row->id);
$membership_type->setDues(INS_Membership_Types::getDuesByEconomy($country, $membership_type->getMemberType()));
$rtn[] = $membership_type;
}
}
return $rtn;
}
private $dues;
public function getDues()
{
return $this->dues;
}
public function setDues($dues)
{
return $this->dues = $dues;
}
You can iterate over objects through for in loop. like as below:
for(var prop in object){
console.log(object[prop]);
}
Hope this helps.
Try with json.
Use
json_encode()
in the php code and
dataType: "json"
in the ajax call
Related
Ajax:
<script type="text/javascript">
$(document).ready(function () {
$('#finalSubmit').click(function() {
var form1 = $('#priceform').serialize();
var form2 = $('#formdescription').serialize();
var form3 = $('#additionaldescription').serialize();
//var form4 = new FormData($("#imagesform").get(0));
//alert(form4);
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN':
$('meta[name="_token"]').attr('content') }
});
$.ajax({
url :"{{url('/dbvalue')}}",
type: 'POST',
data: {form1: form1, form2: form2,form3: form3},
dataType:'json',
success:function(data){
alert(data);
}
});
});
});
</script>
This is my ajax code.Here I'm passing the values of four forms
Controller:
public function finalSubmit(Request $request)
{
var_dump($_POST);
$var1 = $this->addPriceDetails1($request->form1);
$var2 = $this->addProductDetails1($request->form2);
$var3 = $this->addAdditionalInformation1($request->form3);
//$var4 = $this->addImages($imagesform);//you dont't have
$imagesform
return response()->json(["response"=>"success"]);
}
Eg. for function:
public function addPriceDetails1($request)
{
$priceInfo = new priceInfo ;
$priceInfo->id=$this->getpriceDetailsId();
$priceInfo->SKUID=$request->input('skuid');
echo($priceInfo->id);
//return $request->all();
}
Also here when I'm trying to echo the values of $priceInfo->Id it echoes '0'.I don't know why
With this I'm getting FatalErrorException..call to member function input() on string
var_dump($_POST) gives me an array of forms values.
UPdate:
public function getpriceDetailsId()
{
$id = mt_rand(1000000, 9999999);
$id="PD".$id;
$count=priceInfo::select('id')->where('id',$id)->count();
if($count==0)
{
return $id;
}
else
{
$this->getpriceDetailsId();
}
}
here is my function for getpriceDetailsId().
You get that error because your input query when you access as object when it is string, you can convert your query string to an array to access like so.
public function addPriceDetails1($request)
{
parse_str($request, $input);
$priceInfo = new priceInfo ;
$priceInfo->id = $this->getpriceDetailsId();
$priceInfo->SKUID = $input['skuid'];
echo($priceInfo->id);
}
Hope this help
I have tried different ways to make this work but it is still not working. data[0].urgency is undefined. I tried to stringify data but a bunch of \n in between the result (see below).
Thank you in advance.
My ajax code:
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
console.log(data.length);
console.log(data[0].urgency);
}
});
}
My PHP code:
<?php
session_start();
ob_start();
require_once('../../mysqlConnector/mysql_connect.php');
$results = array();
$query="SELECT COUNT(initID) AS count, urgency, crime, initID, TIMESTAMPDIFF( minute,dateanalyzed,NOW()) AS minuteDiff FROM initialanalysis WHERE commanderR='0' AND stationID='{$_SESSION['stationID']}';";
$result=mysqli_query($dbc,$query);
while ($row = $result->fetch_assoc()){
$count = $row['count'];
$urgency = $row['urgency'];
$crime = $row['crime'];
$initID = $row['initID'];
$minuteDiff = $row['minuteDiff'];
$results[] = array("count" => $count, "urgency" => $urgency, "crime" => $crime, "initID" => $initID, "minuteDiff" => $minuteDiff);
}
echo json_encode($results);
?>
Result of PHP:
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4743"}]
I think the result is in wrong format? I'm not sure.
This is the result of console.log(data), there is a comment tag of html and I don't know why:
<!-- -->
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4761"}]
Use a JSON parser for validate the json response like JSON.parse
function ValidateJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
Update your ajax call like this
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
data= jQuery.parseJSON(data);
console.log(data.length);
console.log(data[0].urgency);
}
});
}
So when i try to return an array of database object to my AJAX and parse it, it becomes in an array of chars. I mean my json_encode result is [{'id':38, 'first_name':jana}] and when try to parse it to array in the ajax what is happen is and array of chars - ['[', '{', '''] etc. This is my ajax:
function searchInput() {
var $content = $('.jobboard-quick-search-form').serialize();
$.ajax({
url : '/admin/site/search',
method : "GET",
data : $content,
success : function ( data ) {
var arr = JSON.parse(data);
console.log(arr);
}
});
}
and my action:
public function actionSearch()
{
$lang = \frontend\models\Lang::getCurrent();
$pageSize = 100;
if(\Yii::$app->request->isAjax)
{
$search = \Yii::$app->request->get('search-label');
$town = \Yii::$app->request->get('towns-list');
$startsWith = '%'.$search;
$between = '%'.$search.'%';
$endsWith = $search.'%';
$joinDoctors = "SELECT `doctor`.`id`, `doctorLang`.`first_name`, `doctorLang`.`second_name`, `doctorLang`.`city`, `doctorLang`.`hospital_name`
FROM `doctor` LEFT JOIN `doctorLang` ON `doctor`.`id`=`doctorLang`.`doc_id`
WHERE `doctorLang`.`city`='$town'
AND `doctorLang`.`language`='$lang->url'
AND `doctor`.`active`=1
AND (`doctorLang`.`first_name` LIKE '$startsWith'
OR `doctorLang`.`first_name` LIKE '$between'
OR `doctorLang`.`first_name` LIKE '$endsWith'
OR `doctorLang`.`second_name` LIKE '$startsWith'
OR `doctorLang`.`second_name` LIKE '$between'
OR `doctorLang`.`second_name` LIKE '$endsWith'
OR `doctorLang`.`third_name` LIKE '$startsWith'
OR `doctorLang`.`third_name` LIKE '$between'
OR `doctorLang`.`third_name` LIKE '$endsWith')";
$doctor = \Yii::$app->db->createCommand($joinDoctors)->queryAll();
$joinHospitals = "SELECT `hospital`.`id`, `hospitalLang`.`title`, `hospitalLang`.`address`, `hospitalLang`.`description`
FROM `hospital` LEFT JOIN `hospitalLang` ON `hospital`.`id`=`hospitalLang`.`hospital_id`
WHERE `hospitalLang`.`city`='$town'
AND `hospitalLang`.`language`='$lang->url'
AND `hospital`.`active`=1
AND (`hospitalLang`.`title` LIKE '$startsWith'
OR `hospitalLang`.`title` LIKE '$between'
OR `hospitalLang`.`title` LIKE '$endsWith')";
return json_encode($doctor);
}
}
Thank you in advance!
First of all add in ajax:
dataType: 'json'
$.ajax({
url:<code>,
type: <code>,
dataType: 'json',
data:<code>
})
Next try use restController
class DataController extends yii\rest\Controller
{
public function actionSearch()
{
[.....]
return \Yii::$app->db->createCommand($joinDoctors)->queryAll();
}
}
now guys i know this is a simple error but no matter what i try i cant access the json values whenever i use alert after parse json it shows me undefined
why is it caused ?
here is my code
script
function getfriend_requests()
{
var id=$('.id_data').attr('value');
jQuery.ajax({
type:'POST',
url:'<?php echo base_url("user/getallfriends"); ?>',
data:{id:id},
dataType:'json',
success:function(data)
{
var ParsedObject = JSON.stringify(data);
var json = $.parseJSON(ParsedObject);
alert(json);
$.each(json,function(key,data)
{
alert(data.object);
});
}
});
}
now the controller
public function getallfriends()
{
$id=$this->input->post('id');
$this->load->model('Pmodel');
$data['senders']=$this->Pmodel->get_all_user_friends_sender($id);
$data['recievers']=$this->Pmodel->get_all_user_friends_reciever($id);
echo json_encode($data);
}
now the model
public function get_all_user_friends_sender($id)
{
$this->db->select('*');
$this->db->from('user_friend');
$this->db->join('user_data', 'user_friend.senders_id = user_data.id');
$this->db->join('user', 'user_friend.senders_id = user.id');
$this->db->where('user_friend.senders_id',$id);
$query = $this->db->get();
$row = $query->result_array();
// print_r($row);
return($row);
}
public function get_all_user_friends_reciever($id)
{
$this->db->select('*');
$this->db->from('user_friend');
$this->db->join('user_data', 'user_friend.recievers_id = user_data.id');
$this->db->join('user', 'user_friend.recievers_id = user.id');
$this->db->where('user_friend.recievers_id',$id);
$query = $this->db->get();
$row = $query->result_array();
// print_r($row);
return($row);
}
now when i try to return the value with result_array iy shows me undefined value but if i use $row_array it return only single value from each model.
can you tell me where i am going wrong?
You have array of objects in json response so in success function try like this..
$.each(json,function(key,data)
{
alert(data.key);//where key is key of pointing object
});
In your controller try to change
echo json_encode($data);
to
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($data));
I'm facing a strange problem for the last 10 hours and its really very annoying. The problem is with jquery printing json data from php. The php script is running fine, but when the ajax call returns in complete: event i'm not getting any valid otput.
here is the jquery code::
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST',
dataType: 'json',
complete: function(data) {
console.log(data['message']['Album_Name']);
}
});
return false;
});
});
i had to use complete: event as success: didn't worked at all. Atleast i'm getting some sort of output from the complete: event, although its giving undefined or [object][Object] which is totally ridiculous.
here is the retrieveFileFront.php:
<?php
require './retrieveFiles.php';
$type = $_POST['type'];
$nav_text = $_POST['navtext'];
$ret_files = new retrieveFiles($type, $nav_text);
$data = $ret_files->retFiles();
if ($data['success'] == FALSE) {
$data = array('success' => FALSE, 'message' => 'Sorry an Error has occured');
echo json_encode($data);
} else {
echo json_encode($data);
}
?>
and here is the /retrieveFiles.php
<?php
class retrieveFiles {
public $content_type;
public $list_nav;
public $connection;
public $result;
public $result_obj;
public $tags_array;
public $query;
public $row;
public function __construct($type, $nav_text) {
$this->content_type = $type;
$this->list_nav = $nav_text;
}
public function retFiles() {
#$this->connection = new mysqli('localhost', 'usr', 'pass', 'data');
if(!$this->connection) {
die("Sorry Database connection could not be made please try again later. Sorry for the inconvenience..");
}
if ($this->content_type == "Artists") {
$this->query = "SELECT album_name, album_art FROM album_dummy NATURAL JOIN album_images_dummy WHERE artist_name LIKE '$this->list_nav%'";
try {
$this->result = $this->connection->query($this->query);
$this->row = $this->result->fetch_row();
if (isset($this->row[0]) && isset($this->row[1])) {
$this->tags_array = array("success" => true, "message" => array("Album_Name" => $this->row[0], "Album_Art" => $this->row[1]));
return $this->tags_array;
}
} catch (Exception $e) {
echo 'Sorry an Error has occurred'.$e;
return false;
}
}
}
}
?>
I'm getting a 200 response in console in firebug, which indicates that its running okay.
<!DOCTYPE HTML>
{"success":true,"message":{"Album_Name":"Streetcleaner","Album_Art":"\/var\/www\/html\/MusicLibrary\/Musics\/1989 - Streetcleaner\/folder.jpg"}}
Now this is making me even more confused as i can see that the json is formatted properly. Please provide any sort of suggestion on how to solve this problem.
Thanks in advance..
JSON encoded data is usually not sent like
data['message']['Album_Name']);
But rather like:
data.message.Album_Name;
You're calling your results the wrong way. These are not associative arrays anymore but are now objects, as the name JSON (JavaScript Object Notation) suggests.
You need to parse the json response using
data = $.parseJSON(data)
Use success event instead of complete in ajax and we can able to parse JSON encoded data in javascript/jQuery by using JSON.parse
well after a long period of trauma, i finally found a solution, turns out that i needed to parse the response text and then access the objects, individually.
Here is the working code
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$('#loading').css('visibility', 'visible');
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST'
dataType: 'json',
complete: function(data) {
var res = data.responseText;
res = res.replace(/<!DOCTYPE HTML>/g, "");
res = res.trim();
console.log(res);
var arr = JSON.parse("[" + res +"]"); //needed to parse JSON object into arrays
console.log(arr[0].message.Album_Name);
console.log(arr[0].message.Album_Art);
$('#loading').css('visibility','hidden');
}
});
return false;
});
This works fine and gives the desired response. Anyways thanks for the help, guys.