I have this AJAX:
$.ajax({
url : get_base_url() + 'update',
type : 'POST',
async : false,
data : json_positions,
dataType : 'html',
success : function(data) {
console.log(data);
},
error : function(jqXHR, textStatus, errorThrown) {
console.log('error:');
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown)
}
});
data sent is:
json_positions
which is a string like this:
{"new_positions" : [{ "id": "2", "position": "0"},{ "id": "5", "position": "1"},{ "id": "4", "position": "2"}]}
I want to decode json_positions using json_decode() in a PHP page but it seem that tdata is not sent to the php page because when i try to:
print_r($_POST);
it returns an empty array using console.log(data).
Well your code is okay, no need to change anything. But it's how you pass your data.
data sent is: json_positions which is a string like this: ...
You should not pass it like string. It should be an object like you defimed it:
{"new_positions" : [{ "id": "2", "position": "0"},{ "id": "5", "position": "1"},{ "id": "4", "position": "2"}]}
Make you sure you pass an object, not string, e.g. don't add any quotes around it etc. Then it's going to work fine.
EDIT
As per jQuery documentation for $.ajax data parameter:
dataObject, String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
So your data should be a query string or an object.
In your case I recommend to use object. Like with this code:
var json_positions = {
new_positions: []
};
$.each(result, function(key, value) {
var value_splitted = value.split('-');
json_positions.new_positions.push({
id: value_splitted[1],
position: key
});
});
Since you are sending json data, you need to define the appropriate content type:
contentType: 'application/json'
Also, change the dataType to json if you are expecting json data back:
dataType : 'json'
$_POST only contains key value pair stuff. Your POSTed JSON is in $_HTTP_RAW_POST_DATA.
Related
I know this is basic but i don't know what else i can do. So i need your help. Ill tell you what happened.
The story is that i have a database request and I want to json encode the data from that request and use it through a javascript file ($.ajax or $.json).
the data i need from that request are two values. Latitude and longitude. but when i receive the json_encode from php and put it in the console log or an alert it displays undefined instead of the "double precision"(because the json string).
Ill show you the code.
the php
<?php
$dbconn3 = pg_connect
("host= localhost port=5432 dbname=EmergenciesResponse user=postgres password=asdf");
$query1=pg_query
("select latitude, longitude from emergency where id_emergency=5");
$arreglo=array();
while($reg=pg_fetch_assoc($query1)){
$arreglo[]=$reg;
}
echo json_encode($arreglo);
pg_close($dbconn3);
?>
Then the .js code
$.ajax({
url: 'consulta2.php',
data:{
},
method: 'POST',
dataType:'json',
success: function(data)
{
alert("latitude:"+data.latitude+"longitude:"+data.longitude);
}
});
As I said when I do an alert instruction the output prints undefined but the string of the php is correct. Sorry if its very easy but I don't know what to do about the undefined value
thx for your time.
Your PHP returns an array of objects. The response will look like this (without pretty print):
[
{
"latitude": 0.000,
"longitude": 0.000
},
{
"latitude": 1.000,
"longitude": 2.000
},
{
"latitude": 3.000,
"longitude": 4.000
}
]
However, in JS you are treating is as an object.
You would understand what the problem is if you simply opened your consulta2.php file and looked at the response.
There can be two causes:
id_emergency is not unique. Then, your PHP is good, but in JS you need to iterate through the array:
$.ajax({
url: 'consulta2.php',
data:{
},
method: 'POST',
dataType:'json',
success: function(data)
{
$.each(data, function() { // <-------
alert("latitude:"+this.latitude+"longitude:"+this.longitude);
});
}
});
You will get from 0 to many alerts, one for every pair of coordinates.
id_emergency is unique. Then, your JS is good, but in PHP you do not need to form an array. It should be as simple as:
$query1=pg_query("select latitude, longitude from emergency where id_emergency=5");
//$arreglo=array(); // don't need an array
$reg = pg_fetch_assoc($query1); // only 1 object
echo json_encode($reg); // encode the object, but not an array
pg_close($dbconn3);
As this is the single object, you will get only one alert.
I think there is a problem in your while loop, I think you are overwriting the same index in the loop, you should be increment the index at each iteration.
var counter = 0;
while($reg=pg_fetch_assoc($query1)){
$arreglo[counter]=$reg;
counter++;
}
I've been working on this for quite a while, and I've read TONS of posts on SO trying to figure out how I need to do this, and I can't seem to get it to work. I'm thinking it must be some aspect of the way I've coded things. So downvote away, but hopefully some kind soul will help me out.
I've tested using jsonlint, which comes back valid. I'm getting a response from the server with the values, I just can't seem to get anything in the browser other than when I just alert(response);. I need to be able to access the value of "cat_id_PK" and the other elements separately to loop through and display them in html table cells.
JSON:
{
"income": [
{
"cat_id_PK": 14,
"cat_name": "test1",
"cat_amount": "100.00"
},
{
"cat_id_PK": 15,
"cat_name": "test2",
"cat_amount": "200.00"
},
{
"cat_id_PK": 34,
"cat_name": "test3",
"cat_amount": "300.00"
},
"expense": [
{
"cat_id_PK": 14,
"cat_name": "tes41",
"cat_amount": "400.00"
},
{
"cat_id_PK": 15,
"cat_name": "test5",
"cat_amount": "500.00"
},
{
"cat_id_PK": 34,
"cat_name": "test6",
"cat_amount": "600.00"
}
]
}
PHP
$array = array(
'income' => $income,
'expense' => $expense,
'recurring' => $recurring
);
echo json_encode($array);
JQUERY
var request = $.ajax({
type: "POST",
url: 'inc/functions.php',
dataType: "JSON",
data: {action: "display_categories", cur_month:cur_month}
});
request.done(function(response){
//for each element put values in <td></td> tags.
});
"I've tested using jsonlint, which comes back valid."
No it doesn't, not for the JSON you've shown which has an error: it is missing a closing ] after the } and before the comma on the line before "expense" : .... But perhaps that's just a typo in your question given that you're generating the JSON with json_encode() (which wouldn't produce an error like that).
" I just can't seem to get anything in the browser other than when I just alert(response);"
So you are getting a value of some sort back then.
" but if I just alert response[0], it will return just the first character of the JSON array."
Yes, that's because response is a string - the raw string containing JSON, where what you want is to parse that string to get an object. Except that you don't have to do this manually because jQuery will do it automatically once you add dataType:"json" to your $.ajax() options.
"I actually was missing the datatype on this one, but even after adding it in, no matter what I try, I'm getting [Object:Object] or undefined. I'm literally doing nothing more than alert(response);"
Once you add the dataType:"json" the response parameter will be an object, which when you try to alert will correctly display as [object Object]. If you use console.log(response) then in your browser's console you'd see the actual object. You'd get undefined if you try to access a property that doesn't exist.
"I need to be able to access the value of cat_id_PK and the other elements separately to loop through and display them in html table cells."
Your response object has two properties, income and expenses, both of which are arrays of object. So use response.income to access the first array of objects, and response.expenses to access the second array of objects. The first income item is response.income[0] and the property you asked about is response.income[0].cat_id_PK. So you can use a for loop, or use $.each() to iterate over the array and do something with each .cat_id_PK property:
var request = $.ajax({
type: "POST",
url: 'inc/functions.php',
dataType: "json",
data: {action: "display_categories", cur_month:cur_month}
});
request.done(function(response){
//for each element put values in <td></td> tags.
var tr = $("<tr></tr>");
// using traditional for loop for income items
for(var i = 0; i < response.income.length; i++) {
$("<td></td>").text(response.income[i].cat_id_PK).appendTo(tr);
}
tr.appendTo("#idOfTableHere");
var tr = $("<tr></tr>");
// use equivalent jQuery $.each for expense items
$.each(response.expenses, function(i, v) {
$("<td></td>").text(v.cat_id_PK).appendTo(tr);
});
tr.appendTo("#idOfTableHere");
});
The code I've shown creates new td elements in each loop, appending them to new table rows, and then after each loop the new row is appended to a table that I've assumed already exists on your page with id="idOfTableHere".
try this you miss dataType:
var request = $.ajax({
type: "POST",
url: 'inc/functions.php',
data: {action: "display_categories", cur_month:cur_month},
dataType:"json",
});
request.done(function(response){
//for each element put values in <td></td> tags.
});
Hello I have a problem with my ajax request in jquery.
When I use my get request without sending any data the response is as expected, I receive my array and can access the values:
$.get(
loadUrl,
function(data) {
useReturnData(data);
},
"json"
);
function useReturnData(data){
leftPlayer = data;
alert(leftPlayer[4]);
};
This works as expected and I recieve my value of "528" being my leftPlayer[4] value.
But when I change my request to send a piece of data to php in the request like so:
$.get(
loadUrl,
{ type: "left" })
.done(function(data) {
useReturnData(data);
},
"json"
);
function useReturnData(data){
leftPlayer = data;
alert(leftPlayer[4]);
};
My data received seems to be in string format to javascript.
My alert prints "5" (the 4th character if the array was a string)
When alerting leftPlayer. I find that in the first request in which I send no data the variable is printed as: 355,355,355,355,528,etc...
Whereas in the second request in which I DO send data it prints as:
[355,355,355,355,528,etc...]
Notice the []. It isn't recognised as an array.
The php file it accesses has absolutely no changes in each request, as I am testing at the moment. The data sent isn't even used in the php file at the moment.
Any ideas where I'm going wrong?
I've fixed my problem.
Like what "nnnnnn" said in his comment I'm passing my "json" parameter to the .done() function instead of the $.get() function.
I couldn't seem to get it to correctly view it as JSON though so I used the easiest method:
$.getJSON(
loadUrl,
{ type: "left" },
function(data) {
useReturnData(data);
}
);
function useReturnData(data){
leftPlayer = data;
alert(leftPlayer[4]);
};
Using $.getJSON instead does like what it says and expects JSON to be returned as default.
I'm tring to send a JSON to a PHP page via jQuery, but it doesn't work properly:
json_data = {};
json_data.my_list = new Array ();
$('#table_selected tr').each (function (i) {
json_data.my_list.push ({id:$(this).attr("id")});
});
$.post ("my_page.php", json_data, function (response) {
if (response) alert("success");
else alert("error");
});
<?php
// this is my_page.php
$json = json_decode (stripslashes ($_REQUEST['my_list']), true);
echo var_dump($json);
?>
This returns NULL to my callback, where I'm wrong?
JSON is a string representation of JavaScript objects. You're sending something that looks like this:
{my_list: [{id: 'foo'}, {id: 'bar'}, {id: 'baz'}]}
Which is not JSON. This is JSON:
'{"my_list": [{"id": "foo"}, {"id": "bar"}, {"id": "baz"}]}'
I would recommend using json2.js (more info). This can be facilitated using .serializeArray().
you don't need the echo before var_dump
json_data is a literal with an array inside that you put as parameter to the post, and will be sent as encoded array in the post request to the server.
In my_page.php you may want to look at $_POST array.
UPDATE: Ehm, I re-read your question and I'm not completely sure of what I wrote. What I said applies to GET request, and I believe also to post requests.
As it stands, I have some JQuery along these lines -
ph=function(i){
$.each(i,function(po){
id=po.id;url="/"+id;t=$('<div id='+ id +' class=entry></div>');
t.html('<div class=hx>'+ po.author +'</div><div class=b>'+ po.body +'</div>');
t.prependTo($("#modpskx"));
t.hide();
t.slideDown("slow");});};
function mtoxps(){
mid=$("#xsodl").val();
id=$("#modpskx > div:first")[0].id;
if(id==""){id=0}
$.ajax({
url:'/widgets/live.php',
data:{'id':id,'mid':mid},
type:'post',
dataType:'json',
cache:false,
success:function(b){ph(b);}});}
setInterval("mtoxps()", 10000);
The JSON data sent back to the browser by the server is as follows:
[{
"author": "NiX",
"timestamp": "2009-12-20 21:35:32",
"id": "194",
"mig_id": "3",
"body": "Cows.",
"ip": ""
}]
This - every 10 seconds - successfully requests any new results. Unfortunately, the "ph" variable (what is used to return and display the result(s)) isn't properly parsing the returned output. Instead, it displays all the variables as undefined, resulting in the next request to send the server an "undefined" variable, as well.
Are there any suggestions as to why this isn't functioning?
Try:
$.each(i, function(index, po){
instead of
$.each(i, function(po){
The callback for the each function is at the bottom of this page.