I have the followin PHP file (a function of it):
public function get_hotels(){
$hoteles = new HotelModel();
$query = "SELECT * FROM hotel";
$hoteles = $hoteles->execute_query($query);
echo json_encode($hoteles);
}
And this is my jQuery script:
$.ajax({
type: "POST",
url: "index.php?controller=ExcursionTypes&action=get_hotels",
dataType:"json",
success: function(response){
alert(typeof (response[0].hotel_name));
//$("#pickups_fields").html(response[0].hotel_name);
},
error:function(response){
alert("ERROR");
}
});
Firebug throws me this JSON:
[{"id_hotel":"1","hotel_name":"Apt.Playa del Ingles", "hotel_phone":"928762629",
"hotel_corporation_id":"1","hotel_state_id":"1"},
{"id_hotel":"2","hotel_name":"LZ",
"hotel_phone":"928762629","hotel_corporation_id":"1",
"hotel_state_id":"2"}]
I want to read both hotel_name fields and I can't.
I'm sure you're giving me the solution or a link to solve it.
Although I'm looking for it too.
Javascript is case sensitive, so you should write dataType, not datatype.
JSON that you get as a response is correct and response[0].hotel_name would work, but because you mistyped dataType, the response is not parsed as a JSON and therefore you can't access it the way you did.
Try iterating over the objects in response, like this:
$.ajax({
type: "POST",
url: "index.php?controller=ExcursionTypes&action=get_hotels",
dataType:"json",
success: function(response){
$.each(response, function(i, hotel) {
alert(typeof (hotel.hotel_name));
//$("#pickups_fields").html(hotel.hotel_name);
});
},
error:function(response){
alert("ERROR");
}
});
$.ajax({
type: "POST",
url: "index.php?controller=ExcursionTypes&action=get_hotels",
dataType:"json",
success: function(response){
for(key in response) {
alert(typeof (response.hotel_name[key]));
});
},
error:function(response){
alert("ERROR");
}
});
Related
As the title says, I failed to pass the data array via json ajax to php. I am using codeigniter, what did I do wrong? here is the jQuery code:
function load_page_data1(){
var data = [];
data['val'] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
Here is the php code:
function getdata(){
$parameter = '';
if(isset($_POST))
{
if(isset($_POST['val']))
{
$parameter = $_POST['val'];
} else
{
echo "failed!";
}
}
$this->load->model('Chart');
$this->load->helper('url');
$data1 = $this->Chart->getdata_solid($parameter);
echo json_encode($data1);
}
Final:
Guys, it turn out that the values did passed from jQuery to php, the problem is that I stupidly call the same php function twice within the javascript function, then the second time calling without posting the 'val', so that the php function error and stop.
Thank you all for your answers, at least I learn the different ways to passing data by using jQuery.
Don't make a array if it's not a array just make a object
var data = {};
data.val = "solid_t1";
// equivalent to
data ={val:"solid_t1"};
// equivalent to
data['val'] ="solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
Update 1: if you need to send array you need to make a proper array object like below
Example :
var data=[];
item ={val:'value'};
data.push(item);
var new_data = JSON.stringify(data);
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: new_data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
For Debugging :
May be problem with your server side code .so for the testing purpose comment all the line in function just do this echo json_encode($_POST); and in your ajax success function just add console.log(output); and let me know the result.
create one json object
jsonObj = [];
create array list as per your need
item = {}
item ["val"] = "solid_t1";
push the array list in to the json.
jsonObj.push(item);
Please have a try like this. It is working in my case.
Your full code will be like
function load_page_data1(){
jsonObj = [];
item = {}
item ["val"] = "solid_t1";
jsonObj.push(item);
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: jsonObj,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
The another way to use this is given below.
function load_page_data1(){
var jsonObj = {};
jsonObj["val"] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/Chart_varnish/getdata',
data: jsonObj,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
Instead of var data = []; use var data = {}; to initialize your data. It should solve your problem.
Your data wasn't being passed as json, now it will.
Code will be:
function load_page_data1(){
var data = {};
data['val'] = "solid_t1";
$.ajax({
type: 'POST',
url: BASE_URL+'index.php/welcome/getdata',
data: data,
dataType: 'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: not working");
}
});
}
One more suggestion please use CI input library for post request in controller.
e.g.
$parameter = $this->input->post('val');
This is my imple code on submit of form. Where I want to insert table data values in database through ajax. But it's not going to controller.
$('#submit').click(function(){
var TableData = new Array();
$('#cart_details tr').each(function(row, tr){
TableData[row]={
"productname" : $(tr).find('td:eq(0)').text()
, "quantity" :$(tr).find('td:eq(1)').text()
, "unit" : $(tr).find('td:eq(2)').text()
, "unit_rate" : $(tr).find('td:eq(3)').text()
}
});
TableData.shift();
//TableData = $.toJSON(TableData);
var TableData = JSON.stringify(TableData);
alert(TableData);
var followurl='<?php echo base_url()."index.php/purchase/save_product";?>';
$.ajax({
type: "POST",
url:followurl,
data: TableData,
datatype : "json",
cache: false,
success: function (data) {
alert("dsad"+data);
}
});
});
When I stringify tabledata array output is like this..
[{"productname":"Copper Sulphate","quantity":"1","unit":"1","unit_rate":"100"},
{"productname":"Hypta Hydrate","quantity":"1","unit":"1","unit_rate":"100"}]
My question is why it's not going to controller? it's because of array object or something else??
Tabledata is javascript object array . Am I right??
Use
$.ajax({
instead of
$.post({
use this code
$.ajax({
type: "POST",
url:followurl,
data: {TableData : TableData},
cache: false,
success: function (data) {
alert("dsad"+data);
}
});
check the Documentation jquery.post
The syntax for $.post is
$(selector).post(URL,data,function(data,status,xhr),dataType)
You don't have to define the type ,
but here you are using the $.ajax mixing with $.post
this is the $.ajax function syntax
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
SO change the $.post to $.ajax and try
As you can read in the documentation, you can pass an object to data. I think you'd make things easier and simpler for you if you followed that approach.
...
//TableData = $.toJSON(TableData); NO!!!
//var TableData = JSON.stringify(TableData); NO!!!
//alert(TableData);
var followurl='<?php echo base_url()."index.php/purchase/save_product";?>';
$.ajax({
type: "POST",
url:followurl,
data: {
dataTable: TableData
},
datatype : "json",
cache: false,
success: function (data) {
alert(data);
}
});
});
Very simple example (without validation or anything of the kind) of index.php/purchase/save_product
$data = $_POST["dataTable"];
echo $data[0]["productname"];// Sending back the productName of the first element received.
die();
As you can see, you could access data in your index.php/purchase/save_product file very easily if you followed this approach.
Hope it helps.
Hi It look like you are using some CMS or Framework. Can you please let us know which framework or CMS you are using. I would then be able to sort out this issue. It looks like you are using Code Ignitor. If its so then i hope this would help you
$.post( "<?php echo base_url();?>index.php/purchase/save_product", function(data) {
alert( "success" );
}, 'html') // here specify the datatype
.fail(function() {
alert( "error" );
})
in Your case your ajax call must look like
var followurl="<?php echo base_url();?>index.php/purchase/save_product";
$.ajax({
type: "POST",
url:followurl,
data: TableData,
datatype : "json",
cache: false,
success: function (data) {
alert("dsad"+data);
}
});
});
Error Seems to be in your followUrl please try using as its in mine code
I want to send the data via ajax to other page. I have isolated the problem. This is the code.
Thank you all for your help..But no effect..
updated code
It worked...
<script>
$(document).ready(function(){
$(".edit").click(function(event) {
event.preventDefault(); //<--- to prevent the default behaviour
var box = 1233;
var size=123;
var itemname=123;
var potency=123;
var quantity=12333;
var dataString ={
'box' :box,
'size':size ,
'itemname':itemname,
'potency':potency,
'quantity':quantity
};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
success: function(data) {
alert(data);
},
error: function(data) {
alert(data);
}
});
});
});
</script>
So I click the link,it navigates, to dd.php which has
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']));
echo $_POST['itemname'];
?>
I get Object Object as alert. What am doing wrong? Pls throw some light here..thanks you..
$(document).ready(function(){
$(".edit").click(function(event) {
event.preventDefault();
var data = {"box":1233,
"size":565,
"itemname":565,
"potency":876,
"quantity":234};
$.ajax({
url: "dd.php",
type: "post",
data: data,
dataType: "json",
success: function(data) {
if(console){
console.log(data);
}
},
error: function(data) {
if(console){
console.log(data);
}
}
});
});
});
few things to consider... you can post data as object..which is clean and easier to use
$(".edit").click(function(event) {
event.preventDefault(); //<--- to prevent the default behaviour
var box = 1233;
....
var dataString ={'box':box,'size':size,'itemname':itemname,'potency':potency,'quantity':quantity};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
dataType: "json", //<--- here this means the response is expected as JSON from the server
success: function(data) {
alert(data.itemcode); //<--here alert itemcode
},
error: function(data) {
alert(data);
}
});
so you need to send the response as json in PHP
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']))
?>
Here you are using querystring as sent in GET request.
If you want to send the data in same form, you can use this with GET request type:
$.ajax({
url: "dd.php"+dataString,
type: "get",
dataType: "json",
success: function(data) {
console.log(data);
alert(data.itemcode);
},
error: function(data) {
alert(data);
}
});
Or for POST request,you will have to put data in json object form, So you can use :
var dataString ={
'box' :box,
'size':size ,
'itemname':itemname,
'potency':potency,
'quantity':quantity
};
$.ajax({
url: "dd.php",
type: "post",
data: dataString,
dataType: "json",
success: function(data) {
console.log(data);
alert(data.itemcode);
},
error: function(data) {
alert(data);
}
});
});
And put echo in your php code :
<?php
echo json_encode(array('itemcode'=>$_POST['itemname']))
?>
Javascript alert shows [Object object] for object. You can see response using console.log or can use that key with alert.
For more information, refer jQuery.ajax()
I send an array from PHP with json_encode, and I trying to get with AJAX and jQuery.
Every thing is ok.
JSON structure is :
names{"p1":"John","p5":"Smith"}
jQuery code is :
$.ajax({
type: "POST",
url: "return.php",
dataType: "json",
data: "id=56",
success: function(data) {
$(data.names).each(function(key, txt) {
alert(txt);
});
}
}
this code don't return any thing! I think browser don't enter in each
what should I do ?
instead this:
$(data.names).each(function(key, txt) {
alert(txt);
});
use this:
$.each(data.names, function(key, txt) {
alert(txt);
});
and your json seems to be incorrect as you mentioned: names{"p1":"John","p5":"Smith"}
this should be like this:
{
"names": {
"p1": "John",
"p5": "Smith"
}
}
you can check your json here: http://jsonlint.com/
I'd suggest you use jQuery's $.getJSON(); http://api.jquery.com/jQuery.getJSON/
But to answer your question directly; you didn't close your ajax() function.
$.ajax({
type: "POST",
url: "return.php",
dataType: "json",
data: "id=56",
success: function(data) {
$(data.names).each(function(key, txt) {
alert(txt);
});
}
});
In your code you could just use parseJSON().
$.ajax({
type: "POST",
url: "return.php",
dataType: "json",
data: "id=56",
success: function(data) {
var d = jQuery.parseJSON(data);
// ... do stuff
}
});
I am trying to send data to my PHP script to handle some stuff and generate some items.
$.ajax({
type: "POST",
url: "test.php",
data: "album="+ this.title,
success: function(response) {
content.html(response);
}
});
In my PHP file I try to retrieve the album name. Though when I validate it, I created an alert to show what the albumname is I get nothing, I try to get the album name by $albumname = $_GET['album'];
Though it will say undefined :/
You are sending a POST AJAX request so use $albumname = $_POST['album']; on your server to fetch the value. Also I would recommend you writing the request like this in order to ensure proper encoding:
$.ajax({
type: 'POST',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});
or in its shorter form:
$.post('test.php', { album: this.title }, function() {
content.html(response);
});
and if you wanted to use a GET request:
$.ajax({
type: 'GET',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});
or in its shorter form:
$.get('test.php', { album: this.title }, function() {
content.html(response);
});
and now on your server you wil be able to use $albumname = $_GET['album'];. Be careful though with AJAX GET requests as they might be cached by some browsers. To avoid caching them you could set the cache: false setting.
Try sending the data like this:
var data = {};
data.album = this.title;
Then you can access it like
$_POST['album']
Notice not a 'GET'
You can also use bellow code for pass data using ajax.
var dataString = "album" + title;
$.ajax({
type: 'POST',
url: 'test.php',
data: dataString,
success: function(response) {
content.html(response);
}
});
$.ajax({
type: 'POST',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});