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
}
});
Related
I am having problem sending/reading ajax variable.
Ajax code is as below:
$.ajax({
url: "/wp-content/themes/canvas-child/get-clients-dropdown.php?it=1",
success: function(data) {
$("#ClientID").html(data);
}
});
I have tried to read it in another php file like this:
$InvoiceType = $_REQUEST['it'];
//$InvoiceType = $_POST['it'];
//$InvoiceType = $_GET['it'];
But none of above works. The variable $InvoiceType always stays empty.
What is the problem?
The best way is to use POST method like this :
$.ajax({
method: "POST",
url: ""/wp-content/themes/canvas-child/get-clients-dropdown.php",
data: { it: 1, param2: "value2" }
})
You can get your value in $_POST['it']
Please try it with full url of file with get_template_directory_uri().
$.ajax({
type: 'GET',
url: '<?php echo get_template_directory_uri(); ?>/get-clients-dropdown.php',
data: {it: 1},
success: function(data) {
$("#ClientID").html(data);
}
});
$.ajax({
type: "GET",
data: {it: "1"},
url: "/wp-content/themes/canvas-child/get-clients-dropdown.php?it=1",
success: function(data) {
$("#ClientID").html(data);
}
});
try this
You have to use it like this:
$.ajax({
type: "POST",
url: "/wp-content/themes/canvas-child/get-clients-dropdown.php?it=1",
success: function(data) {
$("#ClientID").html(data);
}
});
Then in PHP File use this:
$InvoiceType = $_POST['it'];
How can i send data like this to php using ajax
["{"title":"mr","fname":"john","lname":"Annah","oname":"Clement","staffid":"123"}"]
try json_encode
for more refer -
http://php.net/manual/en/function.json-encode.php
Do it like so, using jQuery(which you need to include in your script):
<script>
var data={};
data= {
"title":"mr",
"fname":"john",
"lname":"Annah",
"oname":"Clement",
"staffid":"123"};
$.ajax({
url:"somwhere.php",
type:"POST",
dataType:"JSON",
data:data,
async: true});
</script>
And on the page where you want to catch this data, do it like this:
<?php
$title=$_POST['title'];
$fname=$_POST['fname'];
?>
And so on.
stringify before sending
Eg :
var postData = [
{ "id":"1", "name":"bob"},
{ "id":"2", "name":"jonas"}]
this works,
$.ajax({
url: Url,
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(postData) //stringify is important,
});
Try this
$(document).on("click", "#your element", function () {
$.ajax({
type: 'POST',
url: "your_url",
data : {"title":"mr","fname":"john","lname":"Annah","oname":"Clement","staffid":"123"},,
success: function (result) {
### your action after ajax
},
})
})
you can pass it in data like this,
$.ajax({
url: 'url',
type: 'GET',
data: { title:"mr",fname:"john",lname:"Annah",oname:"Clement",staffid:"123" } ,
contentType: 'application/json; charset=utf-8',
success: function (response) {
//your success code
}
});
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 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 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()