Loop through this json object (jquery) with Codeigniter - php

I've created a controller & view as follows - I am trying to loop through the jSON object - can anyone assist?
Can anyone demonstrate how to loop through the json object in the view?
//Controller PHP function:
public function ajax_get_all()
{
$stockists = $this->stockists_model->get_all();
header('Content-type: application/json');
echo json_encode($stockists);
}
//HTML View
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
// Stuff to do as soon as the DOM is ready;
$.getJSON("/stockists/ajax_get_all", function(data) {
var obj = jQuery.parseJSON(data);
//console.log(obj);
});
});

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
// Stuff to do as soon as the DOM is ready;
$.getJSON("/stockists/ajax_get_all", function(data) {
$.each(data, function(key,value){
console.log(key);
console.log(value);
});
//var obj = jQuery.parseJSON(data);
//console.log(obj);
});
});

Related

not returning anything in ajax

this is simple test for ajax and i want to send variable t in my index.php and get data(t) in my process.php and alert digit 15 when i click on button but my problem is not alerting anything
this is my index.php
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
var t = 10;
$("#btn").click(function () {
$.ajax({
type:'post',
url:'process.php',
data:{
't':t
},
success:(function (response) {
alert(response);
}
})
})
})
</script>
<button id="btn">Click!</button>
this is my process.php
<?php
$res = $_POST['t'] + 5;
return $res
?>
Change codes like below:-
1.jQuery:-
$(document).ready(function () {
var t = 10;
$("#btn").click(function () {
$.ajax({
type:'post',
url:'process.php',
data:{'t':t},
success:function (response) { //remove (
alert(response);
}
});
});
});
2.Php:-
<?php
$res = $_POST['t'] + 5;
echo $res; //use echo rather than return
?>
Reason:-
return is used for returning a value from a function to another piece of PHP code.jQuery is not part of the execution of the PHP code on the server, so it has no idea what is really going on server side. jQuery is waiting for the rendered server response, which is what echo provides.
Note:- After doing These changes, Please check the browser console while running the ajax and see any error happen there? If yes share with us
i) Change your code with following code
$(document).ready(function () {
var t = 10;
$("#btn").click(function () {
$.ajax({
type:'post',
url:'process.php',
data:{
't':t
},
success:(function (response) {
alert(response);
}) //Close brace missing
})
})
});
2) Change return to echo
$(document).ready(function(){
$("#btn").click(function (){
var t = 10;
$.ajax({
type:'post',
url:'process.php',
data:{
t:t
},
success:(function (response) {
alert(response);
// you didnt close )
}) // close of success
})// close of ajax
})// close of click
}); // close of document
Process.php
<?php
$res = $_POST['t'] + 5;
echo $res;
?>
You should add jQuery like this
<script src="jquery-3.2.1.min.js"></script>
If you actually have downloaded and placed the file in the same directory.
You can include in from a CDN if you don't want to download it.
use this instead:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
And fix your JS code: (remove the extra '}' ...)
$(document).ready(function () {
var t = 10;
$("#btn").click(function () {
$.ajax({
type:'post',
url:'test.php',
data:{
't':t
},
success:(function (response) {
alert(response);
})
})
});
});

Dynamically autocomplete based on category

i have a problem when i am trying to create a autocomplete with dynamic value that based on combobox using codeigniter,
i have tried using ajax and no success.
here is my ajax code for calling item in category
<script type="text/javascript">
$(document).ready(function() {
$("#jenis").change(function(){
$.ajax({
type : "POST",
url: "<?php echo base_url(); ?>whz/admin/get_item",
dataType: "html",
data : "item=" + $("#jenis").val(),
success: function(data)
{
$("#showitem").text(data);
}
});
});
});
</script>
this is my autocomplete jquery code
<div id="showitem">
<script>
$(function() {
var availableTags = [
<?php foreach ($item as $row){
echo '"'.$row->item_name.'",';}?>
];
$( "#autotags" ).autocomplete({
source: availableTags
});
});
</script>
</div>
and here is my controller
public function get_item()
{
$this->load->model('whz_model');
$category = $this->input->post('item');
$item=$this->whz_model->get_item_by_cat($category);
$script = '
$(function() {
var availableTags = [';
foreach ($item as $row)
{
$script .= '"'.$row->item_name.'",';
}
$script .= '];
$( "#autotags" ).autocomplete({
source: availableTags
});
});';
echo $script;
}
i am considering using json as another option, but i still don't have enough experience using it.
sorry for bad english,
thanks for your help
This is only based on documentation because I don't have any system handy where I could try.
You are telling jQuery that your AJAX response is "html" which means the JavaScript you load will never be executed, I believe. Possibly, it would work if you loaded the data as "script" but the better way would indeed be to use JSON.
Your AJAX call would then look like this:
<script type="text/javascript">
$(document).ready(function() {
$("#jenis").change(function(){
$.ajax({
type : "POST",
url: "<?php echo base_url(); ?>whz/admin/get_item",
dataType: "json",
data : "item=" + $("#jenis").val(),
success: function(data)
{
availableTags = data;
}
});
});
});
</script>
with a controller like that:
public function get_item()
{
$this->load->model('whz_model');
$category = $this->input->post('item');
$item=$this->whz_model->get_item_by_cat($category);
$this->output
->set_content_type('application/json')
->set_output(json_encode($item)));
}
You will have to expose the variable availableTags globally for this to work which you can achieve by changing your DOM to
<div id="showitem">
<script>
$(function() {
availableTags = [
<?php foreach ($item as $row){
echo '"'.$row->item_name.'",';}?>
];
$( "#autotags" ).autocomplete({
source: availableTags
});
});
</script>
</div>
You might also want to expose it as window.availableTags, so you can check it's value in your browser's console.
As mentioned at the start, I did not test this but I believe it should work.
i already fix it with another method i found in the internet, it might be not the best but it works with me,
here is the link
http://www.danielrosca.ro/blog/en/codeigniter-autocomplete/
thank you for all of your answer

Sending map boundary via Jquery to google maps ui

I use this script to get the markers for Google Maps with JSON.
It is not working because I need to receive the boundary in the Json script like this:
$swLat=$_GET["swLat"];
$swLon=$_GET["swLon"];
$neLat=$_GET["neLat"];
$neLon=$_GET["neLon"];
That is where I need your help.
Google maps script
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript" src="http://skiweather.eu/gmap3/js/jquery.ui.map.js"></script>
<script language="javascript" type="text/javascript">
var map = null;
map = new google.maps.Map(document.getElementById("map"));
var markers = new Array();
var bounds = map.getBounds();
var zoomLevel = map.getZoom();
$(function() {
demo.add(function() {
$('#map').gmap().bind('init', function() {
$.getJSON( 'http://skiweather.eu/gmap3/markers/index.php', {zoom: zoomLevel,
swLat: bounds.getSouthWest().lat(), swLon: bounds.getSouthWest().lng(),
neLat: bounds.getNorthEast().lat(), neLon: bounds.getNorthEast().lng()}, function(data) {
$.each( data.markers, function(i, marker) {
$('#map').gmap('addMarker', {
'position': new google.maps.LatLng(marker.latitude, marker.longitude),
'bounds': true
}).click(function() {
$('#map').gmap('openInfoWindow', { 'content': marker.content }, this);
});
});
});
});
}).load();
});
</script>
</head>
<body>
<div id="map"></div>
The jQuery/gmap-part of your code will not be executed at all.
Fixed code:
<script type="text/javascript">
$(function() {
$('#map').gmap().bind('init', function() {
var markers = new Array();
var bounds = $(this).gmap('get','map').getBounds();
var zoomLevel = $(this).gmap('get','map').getZoom();
$.getJSON( 'http://skiweather.eu/gmap3/markers/index.php', {zoom: zoomLevel,
swLat: bounds.getSouthWest().lat(), swLon: bounds.getSouthWest().lng(),
neLat: bounds.getNorthEast().lat(), neLon: bounds.getNorthEast().lng()}, function(data) {
$.each( data.markers, function(i, marker) {
$('#map').gmap('addMarker', {
'position': new google.maps.LatLng(marker.latitude, marker.longitude),
'bounds': true
}).click(function() {
$('#map').gmap('openInfoWindow', { 'content': marker.content }, this);
});
});
});
});
});
</script>
However, it's sending the data now, but it's still not working, because the server will not give any response(are you sure that there is a webservice that returns JSON-data?)

Submit a form and reload data on same page

I got a left_column with a #form, when I sumbmit it should load the results on #content_div without refreshing the page.
Im using this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">
$(function() {
$('#dateform').submit(function(evt) {
evt.preventDefault();
$.ajax({
url: "charts/client.php",
type: 'POST',
data: $(this).serialize(),
success: function(result) {
$('#content_div').html(result);
}
});
});
});
</script>
<div id="content_div">
Nothing seems to appear.
And firebug reports this:
ReferenceError: google is not defined
This charts/client.php is using google api, and yes i've declared it like this:
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
What am I doing wrong?
Thanks
use ajax form
<script>
// wait for the DOM to be loaded
$(document).ready(function()
{
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'../calling action or servlet',
type:'post',
beforeSend:function()
{
alert("perform action before making the ajax call like showing soinner image");
},
success:function(e){
alert("data is"+e);
alert("now do whatever you want with the data");
}
});
});
</script>
you can find the plugin here
It seems that the error you get is from the client.php, not from the actual jquery ajax script.
Probably you tried to call a google method before creating a new instance of the google object you used. I could help you out more if you post the client.php's code here.
For example, when i have worked with gmaps api:
trying to do:
geocoder.geocode( { 'address': target}, function(results, status) {...
before setting :
var geocoder = new google.maps.Geocoder();
will return "google is not defined";

jQuery array() with select on change

I am trying to minimize my code by putting it into an array but nothing happens. I can't figure out what I am doing wrong. Here's the code
<html>
<head>
<title>test</title>
<!-- JavaScript -->
<script src="js/jquery-1.5.2.js" type="text/javascript"></script>
<script type="text/javascript">
var phpfile = new Object();
phpfile["testselect"] = "zoomchange.php";
var elementID = new Object();
elementID["testselect"] = "#testdiv";
$(document).ready(function(){
$("select").change(function() {
$.post(
phpfile[$(this).id()],
$(this).serialize(),
function(data) {
$(elementID[$(this).id()]).html(data)
}
);
});
});
</script>
</head>
<body>
<select id="testselect">
<option value="1">1</option>
<option value="2">2</option>
</select>
<div id="testdiv"></div>
</body>
</html>
here is the zoomchange.php:
<?PHP echo $_REQUEST['testselect'] ; ?>
Your initializers shouldn't look like this:
var phpfile = new Array();
phpfile["testselect"] = "zoomchange.php";
var elementID = new Array();
elementID["testselect"] = "#testdiv";
A JavaScript Array is indexed by numbers, not strings. You want simple object literals:
var phpfile = { testselect: 'zoomchange.php' };
var elementED = { testselect: '#testdiv' };
Then, your POST callback is confused:
function(data) {
$(elementID[$(this).id()]).html(data)
}
this isn't what you think it is when that function is called. You want something more like this:
$("select").change(function() {
var that = this;
$.post(
phpfile[that.id],
$(this).serialize(),
function(data) {
$(elementID[that.id]).html(data);
}
);
});
This
function(data)
{
$(elementID[$(this).id()]).html(data);
}
instead of this
function(data)
{
$(elementID[$(this).id()]).html(data)
}
Is this the error ?
You should do new Object() instead of new Array().
Edit: There are other mistakes, your js code should be this:
<script type="text/javascript">
var phpfile = {};
phpfile["testselect"] = "zoomchange.php";
var elementID = {};
elementID["testselect"] = "#testdiv";
$(document).ready(function(){
$("select").change(function() {
var $select = $(this);
$.post(
phpfile[$select.attr("id")],
$select.serialize(),
function(data) {
$(elementID[$select.attr("id")]).html(data)
}
);
});
});
</script>

Categories