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');
Related
I have a simple code but is not working. I want to create a more complex function but I just need the basic structure.
HTML
<span class="cleanreport">Delete Record</span>
Javascript:
$( ".cleanreport" ).click(function() {
var token = "test";
$.ajax({
data: {"data": token},
type: "post",
url: "clean.php",
success: function (data) {
console.log(data);
$('.test').html(data);
}
});
});
PHP clean.php
$data = $_POST['data'];
echo $data;
What I am doing wrong?
This should work for you:
var token = "test";
$.ajax({
type: 'POST',
url: "clean.php",
data: {id: token},
dataType: "json",
success: function(response) {
// some debug could be here
},
error: function(a,b,c) {
// some debug could be here
}
});
If not, please debug success and error parameters using console.log().
Based on jquery documentation setting type is an alias for method so this could not be a problem in you case for sure.
$( ".cleanreport" ).click(function() {
var token = "test";
$.post('clean.php",
{
data: token
},
function (data,status) {
//console.log(data);
$('.test').html(data);
});
});
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");
}
});
I'm having trouble getting JSON data sent from JavaScript to PHP. Here is my Javascript:
var noteData = {
nData: {
"postID": $postID,
"commentPar": $commentPar,
"commentValue": $commentValue
}
}
var sendData = JSON.stringify(noteData);
$.ajax({
type: "POST",
url: templateUrl+"/addnote.php",
data: sendData,
dataType : 'json',
success: function(data) {
alert(data);
console.log(sendData);
},
error: function(e) {
console.log(e.message);
console.log(noteData);
console.log(sendData);
alert("error");
}
});
Here is how I just test if the data is even being passed to PHP, it always returns back null.
<?php
$nData = json_decode($_POST['nData']);
echo json_encode($nData);
?>
What am I doing wrong?
You are sending the data as raw JSON to PHP, not as POST parameter.
There are two alternatives. The first one leaves your PHP intact:
var noteData = {
nData: {
"postID": $postID,
"commentPar": $commentPar,
"commentValue": $commentValue
}
}
var sendData = JSON.stringify(noteData);
$.ajax({
type: "POST",
url: templateUrl+"/addnote.php",
data: {
nData: sendData
},
dataType : 'json',
success: function(data) {
alert(data);
console.log(sendData);
},
error: function(e) {
console.log(e.message);
console.log(noteData);
console.log(sendData);
alert("error");
}
});
The second one modifies the PHP side alone. You need to read the input stream directly to obtain the raw data.
<?php
$nData = json_decode(file_get_contents('php://input'));
echo json_encode($nData);
This one might be slightly different depending on the server configuration. See the documentation on the input stream wrappers.
Tell your post request that you are sending json object
contentType: "application/json"
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 have a php program where I just test some sample data. I am getting error as missing ] after element list. How can I read this?
$dataDetailsList = array();
array_push($dataDetailsList, array('a' =>'1','b' =>'2','c' =>'3','d' =>'4','e' =>'5'));
echo json_encode(array("DataDetailsList"=>$dataDetailsList));
Then in my jQuery processor I am doing like this.
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(data) {
//alert(json);
var jsonData = eval(" (" + data + ") ");
},
cache: false
});
function requestData() {
$.ajax({
url: 'live-server-data.php',
success: function(data) {
//alert(json);
var jsonData = data;
},
cache: false,
dataType: 'json' //data type that it will return
});
}
Don't use eval is evil.
Instead of this use:
JSON.parse(data); // not supported in IE7 and below
I think you need to try
dataType: 'json'
That is,
$.ajax({
url: 'live-server-data.php',
dataType: 'json',
success: function(data) {
var jsonData = data;
console.log(jsonData);
$.each(jsonData.DataDetailsList, function(key, val) {
var key = Object.keys(val)[0],
value = val[key];
console.log(key); // output: a, b, c ...
console.log(value); // output: 1, 2, 3,...
// alternative
for(var key in val) {
console.log(key);
console.log(val[key]);
}
});
},
cache: false
})
You should just set the dataType to json and jQuery will do the trick for you..
$.ajax({
url: 'live-server-data.php',
dataType: 'json', //Added dataType json
success: function(data) {
//Now data is a javascript object (JSON)
},
cache: false
});