How to access array elements in ajax response received from PHP? - javascript

jQuery code of ajax function is as follows:
$(document).ready(function() {
$("#zip_code").keyup(function() {
var el = $(this);
var module_url = $('#module_url').val();
if (el.val().length === 5) {
$.ajax({
url : module_url,
cache: false,
dataType: "json",
type: "GET",
data: {
'request_type':'ajax',
'op':'get_city_state',
'zip_code' : el.val()
},
success: function(result, success) { alert(result.join('\n'));
$("#city").val(result.place_name);
$("#state_code").val(result.state_code);
}
});
}
});
});
PHP code snippet is as follows :
case "get_city_state":
// to get the city and state on zip code.
$ret = $objUserLogin->GetCityState($request);
if(!$ret) {
$error_msg = $objUserLogin->GetAllErrors();
list($data) = prepare_response($request);
$smarty->assign('data', $data);
} else {
$data = $objUserLogin->GetResponse();
echo $data;
}
die;
break;
In PHP code the $data contains data in following manner :
<pre>Array
(
[id] => 23212
[zip_code] => 28445
[place_name] => Holly Ridge
[state_code] => NC
[created_at] => 1410875971
[updated_at] => 1410875971
)
</pre>
From the above data(i.e. response which will be available in variable result in ajax response) I want to access only two fields place_name and state_code.
I tried printing the content of result variable using alert(result) in console but I get the word Array
How to achieve this is my doubt?
Thanks in advance.

You should encode your result to json. So instead of the statement echo $data
use
echo json_encode($data);
it will return your result in json format. like
{"id":23212,"place_name":"Holly Ridge"...}
and in your javascript your can access your data

Related

Ajax not getting only json output data (it print whole loaded view code.).? codeigntier

Here is my little script code I want to get data from codeingiter controller. I get json data from controller to view ajax, but It print with html page code.
any one can help me here, How can I solve this.
I only want to get json data ans a variable data to my page.
this is output that I am getting but this is comming with html code and I don't want html code.
[{"id":"1","p_name":"t_t11","p_type":"t_t1","paid_type":"0"},{"id":"2","p_name":"t_t12","p_type":"t_t1","paid_type":"1"},{"id":"3","p_name":"t_t1","p_type":"t_t1","paid_type":"0"}]
I have follow some question answers but can't et success, because that question's answers not related to me.
Link 1
Link 2 and many more...
<script>
$("a.tablinks").on('click',function(e){
e.preventDefault();
var p_name = $(this).attr('value');
alert(p_name);
$.ajax({
url:"<?php echo base_url(); ?>teq/gettabdata",
dataType:'text',
type: "POST",
data:{p_name : p_name},
success : function(data){
alert(data);
if(data !=""){
var obj = JSON.parse(data);
alert(obj.id);
/*$.each(obj, function(key,val){
console.log(key);
console.log(val); //depending on your data, you might call val.url or whatever you may have
});*/
}else{
alert(data+ '1');
}
},
error : function(data){
//var da = JSON.parse(data);
alert(data+ '2');
//alert(da+ '2 da ');
}
});
});
</script>
Here is controller code.
public function gettabdata(){
$p_name = $this->input->post('p_name');
//echo $p_name." this is paper name.!";
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
//$p_name = $data;
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
echo json_encode($query['res']);
$this->load->view('teq', $tabs_data);
}
You added view at the end of your function that return view's code.
Remove line:
$this->load->view('teq', $tabs_data);
You can either use
if ($this->input->is_ajax_request()) {
echo json_encode($data_set);
}else{
//Procced with your load view
}
Or if you're avoiding ajax request check then please pass any extra paramter from your ajax call then then check for its existence at your controller and on behalf of it proceed your conditional statement . it will solve your problem
Change your controller method like this:
public function gettabdata(){
$p_name = $this->input->post('p_name');
//echo $p_name." this is paper name.!";
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
//$p_name = $data;
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
// if ajax request
if ($this->input->is_ajax_request()) {
echo json_encode($query['res']);
return; // exit function
}
$this->load->view('teq', $tabs_data);
}
In your ajax code chage dataType: to json
$.ajax({
url:"<?php echo base_url(); ?>teq/gettabdata",
dataType:'json',
type: "POST",
data:{p_name : p_name},
success : function(res)
{
if(res !=""){
alert(res.id);
}else{
alert(res+ '1');
}
}
});
And in your controller
public function gettabdata()
{
if($this->input->post('p_name'))
{
$p_name = $this->input->post('p_name');
$query['res'] = $this->db->select('*')->from('t_name')->where('p_type',$p_name)->get()->result();
if($query['res'])
{
$resp = $query['res'];
}
else
{
$resp = array('status' => FALSE,'msg' => 'Failed');
}
echo json_encode($resp);
}
else
{
$tabs_data['res1'] = $this->db->distinct()->select('p_type')->from('t_name')->get()->result();
$this->load->view('teq', $tabs_data);
}
}
Hope this helps :)

$.ajax missing some data on post to php

I have a problem where some of my data is not getting through to php. I think the problem lies in ajax sending it. I send about 10 attributes, from which some are strings and some are integers. This is just simplified example of what I did. Few of the values given that it misses are integers, I think. And some values are got from cordova.Localstorage with storage.getItem("itemkeyname"); There's no problem with connection, because I get at least error message back saying "missing data" etc, etc..
I've tried PHP's isset() instead of empty(), which didn't change anything.
var_dump() returns array of send attributes, but few last attributes are cut-off or missing.
//when submitbtn is pressed
$("#submitbtn").click(function () {
// First I get data from input elements from page
$name = $("#name").val();
$name2 = $("#name2").val();
//debug to see $name's value
alert("name: " + $name + ", name2: " + $name2);
// then I check it's not empty/null
if ($name && $name2) {
//then call ajax and send data to server
$.ajax({
url: "http://localhost:1234/phpfile.php",
type: "POST",
data: {
name: $name,
name2: $name2
},
dataType: "text",
success: function (response) {
alert(response);
},
error: function (err) {
$output = JSON.stringify(err);
alert($output);
}
});
}
});
On the server side phpfile.php
<?php header('Content-Type: text/html; charset=utf-8');
//store missing data on array
$data_missing = array();
if(empty($_POST['name'])) {
$data_missing[] = "name";
} else {
$name = trim($_POST['name']);
}
if(empty($_POST['name2'])) {
$data_missing[] = "name2";
} else {
$name2 = trim($_POST['name2']);
}
//check there's no data missing
if(empty($data_missing)) {
//do stuff
} else {
echo 'missing data: ';
foreach($data_missing as $missing) {
echo '$missing , ';
}
}
?>
echo '$missing , ' won't work should be echo "$missing , "
In your JS code the dataType is defined as "text" (plain), while PHP defines its response as text/html.
Try to check the input values as:
if( !isset($_POST["name"]) || strlen(trim($_POST["name"])) == 0 ) {
$data_missing[] = "name";
}

PHP/Ajax/jquery/JSON - Take a part from echo text back as a variable after Ajax Post

I'm working on a simple Ajax post method and here is my code:
<script type="text/javascript">
jQuery(document).ready(function($) {
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
var nextUrl = "<?PHP echo $nexturl;?>";
$('#Loading').show();
$.ajax({
url: 'ajax.php',
type: 'POST',
dataType: 'html',
data: {
next_url: nextUrl
},
}).done(function ( html ) {
$('#LoadedResults').html( html );
$('#Loading').hide();
});
}
});
});
</script>
This code is sending post data to ajax.php:
<?PHP
function callInstagram($url)
{
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 2
));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$client_id = "1e0f576fbdb44e299924a93cace24507";
$Next_URL = $_POST["next_url"];
$url = $Next_URL;
$inst_stream = callInstagram($url);
$results = json_decode($inst_stream, true);
$maxid = $results['pagination']['next_max_id'];
$nexturl = $results['pagination']['next_url'];
//Now parse through the $results array to display your results...
echo json_encode(array(
'next_url_link' => $nexturl
));
The ajax.php is echoing result as:
{"next_url_link":"https:\/\/api.instagram.com\/v1\/tags\/sweden\/media\/recent?count=24&client_id=1e0f576fbdb44e299924a93cace24507&max_tag_id=1427904820688670"}
I was looking here and there and i think there is some method with json with which i can get the result of next_url_link.
So guys, how can i get back the result printed for next_url_link and set is active jQuery/JavaScript variable ?
For example:
var NextUrlLink = data.next_url_link;
Is it possible somehome ?
Should i create two .ajax post methods or how, i have no idea ?
Thanks in advance!
Use the function JSON.parse() for it.
So here is how you will do it :
.done(function ( html ) {
var data = JSON.parse(html);
//now use data.next_url_link
$('#LoadedResults').html(data.next_url_link);
$('#Loading').hide();
});
Maybe you can use the success function to retrieve the data you encoded in your json
var NextUrlLink = []; //declare it as a global variable or somewhere within the same level or scope of where you want to use it so that you can use it
$.ajax({
url: 'ajax.php',
type: 'POST',
dataType: 'json',
data: {
next_url: nextUrl
},
success:function(data){
NextUrlLink = data.next_url_link;
}
})

How to show alert when error comes from the PHP as response to ajax request in following case?

The jQuery AJAX function is as follows :
$(document).ready(function() {
$("#zip_code").keyup(function() {
var el = $(this);
var module_url = $('#module_url').val();
if (el.val().length === 5) {
$.ajax({
url : module_url,
cache: false,
dataType: "json",
type: "GET",
async: false,
data: {
'request_type':'ajax',
'op':'get_city_state',
'zip_code' : el.val()
},
success: function(result, success) {
$("#city").val(result.place_name);
$("#state_code").val(result.state_code);
}
});
}
});
});
The PHP code is as follows :
case "get_city_state":
// to get the city and state on zip code.
$ret = $objUserLogin->GetCityState($request);
if(!$ret) {
$error_msg = $objUserLogin->GetAllErrors();
$data = array();
$data['error_message'] = $error_msg;
$data = json_encode($data);
echo $data;
die;
} else {
$data = array();
$data = $objUserLogin->GetResponse();
echo json_encode($data);
die;
}
break;
Now I'm able to print the success when the response comes without any error but what about showing the alert message when some error happens. How to achieve it? What change needs to make to the above code? Please help me.
Use below condition in success:
success: function(result, success) {
if($.inArray( "error_message", result)) {
alert("Error message");
} else {
$("#city").val(result.place_name);
$("#state_code").val(result.state_code);
}
}
on php file if u found data acc to ur parameter
than it ok if there is no data acc to ur parameter than this time u can call its an error so in thsi case echo "error";
and on ajax page check for result if its value is error then do what else u want
success: function(result, success) {
$("#city").val(result.place_name);
$("#state_code").val(result.state_code);
}

How to do the ajax + json using zf2?

i am using zf2. i want to load my second drop down by using the ajax call. i have tried with following code. i can get hard coded values. but i dont know how to add database values to a array and load that values to the drop down using ajax.
Ajax in phtml :
<script type="text/javascript">
$(document).ready(function () {
$("#projectname").change(function (event) {
var projectname = $(this).val();
var projectkey = projectname.split(" - ");
var projectname = {textData:projectkey[1]};
//The post using ajax
$.ajax({
type:"POST",
// URL : / name of the controller for the site / name of the action to be
// executed
url:'<?php echo $this->url('userstory', array('action'=>'answer')); ?>',
data:projectname,
success: function(data){
//code to load data to the dropdown
},
error:function(){alert("Failure!!");}
});
});
});
</script>
Controller Action:
public function answerAction() {
// ead the data sent from the site
$key = $_POST ['textData'];
// o something with the data
$data= $this->getProjectTable ()->getkeyproject( $key );
$projectid = $data->id;
$projectusers[] = $this->getRoleTable()->fetchRoles($projectid);
// eturn a Json object containing the data
$result = new JsonModel ( array (
'projectusers' => $projectusers
) );
return $result;
}
DB query :
public function fetchRoles($id) {
$resultSet = $this->tableGateway->select ( array (
'projectid' => $id
) );
return $resultSet;
}
your json object new JsonModel ( array (
'projectusers' => $projectusers
) json object become like this format Click here for Demo
var projectkey = [];
projectkey = projectname.split(" - ");
var projectname = { "textData" : "+projectkey[1]+" };
$.ajax({
type:"POST",
url : "url.action",
data : projectname,
success : function(data){
$.each(data.projectusers,function(key,value){
$('#divid').append("<option value="+key+">"+value+"</option>");
});
});
});
<select id="divid"></select>
This is what i did in my controller. finaly done with the coding.
public function answerAction() {
// ead the data sent from the site
$key = $_POST ['textData'];
// o something with the data
$data= $this->getProjectTable ()->getkeyproject( $key );
$projectid = $data->id;
$i=0;
$text[0] = $data->id. "successfully processed";
$projectusers = $this->getRoleTable()->fetchRoles($projectid);
foreach ($projectusers as $projectusers) :
$users[$i][0] = $projectusers->username;
$users[$i][1] = $projectusers->id;
$i++;
// eturn a Json object containing the data
endforeach;
$result = new JsonModel ( array (
'users' => $users,'count'=>$i
) );
return $result;
}
and the ajax is like this
<script type="text/javascript">
$(document).ready(function () {
$("#projectname").change(function (event) {
var projectname = $(this).val();
var projectkey = projectname.split(" - ");
var projectname = {textData:projectkey[1]};
//The post using ajax
$.ajax({
type:"POST",
// URL : / name of the controller for the site / name of the action to be
// executed
url:'<?php echo $this->url('userstory', array('action'=>'answer')); ?>',
data:projectname,
success: function(data){
// alert(data.users[0][0]+" - " + data.users[0][1] );
var count= data.count;
alert(count);
$('#myDropDown').empty();
for(var i=0;i<count;i++){
$('#myDropDown').append($('<option></option>').attr('value', data.users[i][1]).text(data.users[i][0]));
}
},
error:function(){alert("Failure!!");}
});
});
});
</script>
used the same zf2 query to access the database. thanks for the help everyone :)

Categories

Resources