Jquery .post() return array - php

Sorry for the bad title, but I don't know how to name this. My problem is that whenever I pass a value from a select box I trigger this jquery event in order to check on the check boxes. Bassically I echo $res[]; at selecctedgr.php. Do I need to use json? and how can I do this?
Mainpage:
$("#group_name").change(function(){
var groupname = $("#group_name").val();
var selectedGroup = 'gr_name='+ groupname;
$.post("selectedgr.php", {data: selectedGroup}, function(data){
$.each(data, function(){
$("#" + this).attr("checked","checked");
});
},"json");
});
PHP (selectedgr.php):
<?php
include_once '../include/lib.php';
$gr_name=mysql_real_escape_string($_POST['gr_name']);
$sqlgr = "SELECT * FROM PRIVILLAGE WHERE MAINGR_ID=".$gr_name;
$resultgr = sql($sqlgr);
while($rowgr = mysql_fetch_array($resultgr)){
$res[] = $rowgr['ACT_ID'];
}
echo $res[];
?>

Change the last line in your PHP sample (echo $res[];) to:
echo json_encode($res);
json_encode() manual page will tell you more.
Also as #Unicron says you need to validate the $gr_name variable before passing it to your SQL statement.
You could use:
if(isset($_POST['gr_name'])) {
$gr_name = mysql_real_escape_string($_POST['gr_name']);
}
See: http://php.net/manual/en/function.mysql-real-escape-string.php for more information in the PHP manual.

You can use json_encode function to convert arbitrary data into JSON. Assuming that you want to return an array of strings, here is how you will use json_encode:
<?php
include_once '../include/lib.php';
$res = array(); // initialize variables
$sqlgr = sprintf("
SELECT ACT_ID
FROM PRIVILLAGE
WHERE MAINGR_ID=%d
",
$_POST['gr_name']
); // only select those columns that you need
// and do not trust user input
$resultgr = sql($sqlgr);
while($rowgr = mysql_fetch_array($resultgr)){
$res[] = $rowgr['ACT_ID'];
}
echo json_encode($res); // use json_encode to convert the PHP array into a JSON object
// this will output something like ['foo', 'bar', 'blah', 'baz'] as a string
?>
On the client side you can use jQuery.post method, like this:
<script type="text/javascript">
$("#group_name").change(function () {
$.post("selectedgr.php", {
gr_name: $(this).val()
}, function (data) {
// console.log(data);
// jQuery will convert the string "['foo', 'bar', 'blah', 'baz']" into a JavaScript object
// (an array in this case) and pass as the first parameter
for(var i = 0; i < data.length; i++) {
$("#" + data[i]).attr("checked", "checked");
}
}, "json");
});
</script>

If you want to use JSON then just use echo json_encode($res);
But I don't really understand what you'll gain if your code is working now, since you'll still have to do some processing in the Javascript to handle the result.

I found my major problem as below
instead of (before):
$.post("selectedgr.php", {data: selectedGroup}, function(data){
do this (after):
$.post("selectedgr.php", selectedGroup, function(data){
Forgive my bad. Ahh ya guys, regarding the escaping on mysql actually #group_name is not any input field but a select box. Appreciate for every comment, suggestion and guide.
Eric.

Related

How to access entry in the javascript object array

I assigned a JSON result from php to a javascript variable.
The result returned looks like below but it gives me undefined undefined
[{"a":"2","u":"jamesoduro","l":"Oduro","f":"James"},{"a":"5","u":"deary.grace","l":"Grace","f":"Dear"}]
I simple know this look like a javascript array with two objects.
I am trying to access the data inside the objects but to no avail.
Below is script:
PHP
<?php
//fetch online users
$array = array();
$sql = "SELECT id as a,username as u, lastname as l,firstname as f FROM users WHERE active =1 limit 2";
$q = mysqli_query($dbc_conn,$sql);
while($row = mysqli_fetch_assoc($q)){
$array[] = $row;
}
$json = json_encode($array);
echo $json;
?>
JQUERY
$(document).ready(function(){
//checking online users
setTimeout(function(){
$.ajax({
url:"testing.php",
type:"post",
success:function(response){
var array = response;
console.log(array[0].f +" "+ array[0].l);
}
});
},200);
});
Please what could be the problem?? Thank you
$.ajax({
url:"testing.php",
type:"post",
success:function(response){
var array = JSON.parse(response);
console.log(array[0].f +" "+ array[0].l);
}
});
You get a string from php , need turn the string into a json object .
You have to learn to debug your code to find what is going wrong I guess .
Try deserializing the response:
var array = JSON.parse(response);
EXPLANATION
The response you get from the ajax call is of type string, so you have to convert it to an object. That's what JSON.parse() method do: it parses the JSON string and creates the object that this string represent, following specific rules (The parsed string must be in a valid JSON format).
Keep your server side PHP script code neat and clean
Start PHP block from first character of first line.
Do not close php block if there is no output in HTML format.
Use ob_clean() function before echo output in is your are in developer mode and display error is enabled.
for example
ob_clean();
echo json_encode($array);
In client side, if you are getting JSON response in ajax, pass dataType:'json' in ajax option
$.ajax({
url:"testing.php",
type:"post",
dataType:"json",
success:function(response){
console.log(response[0].f +" "+ response[0].l);
}
});

Passing array through AJAX from php to javascript

I need to get an array generated from a script php. I have Latitude and Longitude for each user in a database.
I take the values from the db with this code (file.php):
$query = "SELECT Latitude, Longitude FROM USERS";
$result=mysql_query($query);
$array=array();
while ($data = mysql_fetch_array($result)) {
$array[]=$data['Latitude'];
$array[]=$data['Longitude'];
}
echo $array;
and I call with ajax with this code:
$.post('./file.php',
function( result ){
alert(result);
});
but even if in the script php the array is correct (if I echo array[25] I obtain the right value) in Javascript I obtain "Undefined".
How can I get the array in correct way??
thanks!
edit: after encoded with json_encode($array); in php and JSON.parse(result) in javascript seems not working.
In the console I have the array, but I can't access to its values. (Array[0] gave me "undefined").
use this
echo json_encode($array);
on server side
and
var arr=JSON.parse(result);
on client side
As Ruslan Polutsygan mentioned, you cen use
echo json_encode($array);
on the PHP Side.
On the Javascript-Side you can simply add the DataType to the $.post()-Function:
$.post(
'./file.php',
function( result ){
console.log(result);
},
'json'
);
and the result-Parameter is the parsed JSON-Data.
You can also set the correct Content-Type in your PHP Script. Then jQuery should automaticly parse the JSON Data returned from your PHP Script:
header('Content-type: application/json');
See
http://api.jquery.com/jQuery.post/
http://de3.php.net/json_encode
You need to convert the php array to json, try:
echo json_encode($array);
jQuery should be able to see it's json being returned and create a javascript object out of it automatically.
$.post('./file.php', function(result)
{
$.each(result, function()
{
console.log(this.Latitude + ":" + this.Longitude);
});
});

Jquery set PHP $_GET array

Greetings Stackoverflow
How do I set the php $_GET[] array from Jquery? I have a string looking simmilar to this: $sample_string = "Hi there, this text contains space and the character: &";. I also have a variable containing the name of the destination: $saveAs = "SomeVariable";. In PHP it would look following: $_GET["$SomeVariable"] = $sample_string;.
How do I do this in Jquery?
Thanks in advance, Rasmus
If you're using jQuery, you'll have to set up an AJAX request on the client side that sends a GET request to the server. You can then pull the data you supplied in the request from the $_GET[] array on the server side.
$(function() {
var data = {
sample_string: "hi",
saveAs: "something"
};
$.get('/path/to/script.php', data, function(response) {
alert(response); // should alert "some response"
});
});
And in script.php:
<?php
$sample = $_GET['sample_string']; // == "hi"
$saveAs = $_GET['saveAs']; // == "something"
// do work
echo "some response";
?>
Can't tell if you're looking to grab a GET param from javascript or set a GET param from jQuery. If it's the former, I like to use this code (stolen a while back from I can't remember where):
var urlParams = {};
(function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
Then you can call
var cake = urlParams['cake'];
To get the $_GET param specified by http://someurl.com?cake=delicious
If you want to send a $_GET parameter, you can use either jQuery's $.get() or $.ajax() functions. The $.get function is more straightforward and there's documentation on it here http://api.jquery.com/jQuery.get/
For $.ajax you would do something like this:
var trickystring = "Hi there, this text contains space and the character: &";
$.ajax({
url:'path/to/your/php/script.php',
data: {
'getParam1':trickystring,
'getParam2':'pie!'
},
type:'GET'
});
Now in PHP you should be able to get these by:
$trickystring = $_GET['getParam1'];
$pie = $_GET['getParam2'];
Hope these examples GET what you're looking for. (Get it?)
if $sample_string is what you want in jquery, you can do
var sample_str = '<?php echo $sample_string; ?>'; and then use the js variable sample_str wherever you want.
Now, if you want to do set $_GET in jquery, an ajax function would be way to go.
$.ajax({
url:'path/to/your/php_script.php',
data: {
'param1': 'pqr',
'param2': 'abc'
},
type:'GET'
});
Do you mean that would look like $_GET[$saveAs] = $sample_string y think.
$_GET is a variable for sending information from a page to another by URL. Its nosense to do it in jQuery that is not server side. If you want to dynamically set the $_GET variable to send it to another page you must include it in the URL like:
/index.php?'+javascriptVariable_name+'='+javascriptVariable_value+';
$_GET is just a URL parameter. So you can access get like /index.php?id=1:
echo $_GET['id'];
Look at this article, it shows all the ways to load stuff with ajax:
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/

json object usage with ajax returned array

I have a problem with the returned array from ajax call.
the array is encrypted using json. it is as below
while ($found_course = mysql_fetch_assoc($sql)) {
$info[] = array(
'code' => $found_course['course_code'],
'name' => $found_course['course_name'] );
}
echo json_encode($info); //this is returned to javascript
then the problem is that I am unable to use the above array returned in javascript. I tried using the $.each method but to no avail. the eval() also do not work as it give output as [object object]. Can someone please help me with this.
All I want is to be able to acces the code and the name of the course saperately
Thanks.
Just loop through it with for()
for (var c in myAjaxArray){
myAjaxArray[c].code; // contains the code
myAjaxArray[c].name // contains the name
}
Make sure you set the dataType in the jQuery ajax call to "JSON" to make sure you have a json Object. Or use the $.getJSON() function.
<script>
var data = <?= json_encode($info); ?>;
for (var i = 0; i < data.length; i++) {
var item = data[i];
alert(item["code"] + " / " + item["name"]);
}
<script>
This should get you the data you need. Not sure how you tried using $.each but it should be in your success function on your ajax call. Also make sure the datatype is set to json.
success: function(data){
$(data).each(function(idx,val){
alert(val.code + " " + val.name);
})
}

$.post() jQuery and PHP

Here is a piece of code :
$username="anant";
$name="ana";
echo $username;
echo $name;
Now if using jquery $.post() i want to retrieve $username and $name ,how would I do it ?
Thanks!
I assume the code is your php based response to the $.post call. If all you are returning are values then the easiest thing to do is to return a json response. For example...
PHP Script:
$values = array(
'username' => 'anant'
'name' => 'ana'
);
header('Content-type: application/json');
echo json_encode($values);
JS $.ajax call:
$.ajax(
url: '/path/to/script.php',
type: 'post',
dataType: 'json',
success: function(data){
alert('Username: '+data.username);
alert('name: '+data.name);
}
);
Or if you wanna stick with $.post then follow kovshenin's answer for the syntax using $.post. But be sure you use my php code witht he header() call to properly set the content type of the http response. I just prefer to use the long hand.
I'm not a php expert but try something like:
php
$username="anant";
$name="ana";
echo json_encode(array("username"=>$username,"name"=>$name));
js
$(function() {
$.get('test.php', function(data) {
alert(data.username + ':' + data.name);
});
});
I hope this helps!
You will be better off with json_encode which javascript will understand just fine:
$res = array('username' => 'anant', 'name' => 'something');
echo json_encode($res);
Then use the following code in jQuery to retrieve the values:
$.post('/something', function(response) {
alert("Username is: " + response.username + " and name is: " + response.name);
}, "json");
Cheers.
Now that I know what you are trying to do post expects a fourth parameter the encoding type. If you set it to JSON you would encode your data like so
echo '{"username": ".'$username.'", name":"'.$name.'"}'; //Json may not be perfect
you can access it in jQuery using
data.username
First thing is you have to do a GET not a POST. You may need to change your server side code a little bit so that front end had a clue of how to identify different values (JSON will be better) but a simple , should work fine.
$username="anant";
$name="ana";
echo "$username,"
echo "$name";
your output will be then something like Anant001,Anant your username, name.
Then use a simple jQuery call to get it and split it by , and here is an example..
$.get('/getnames', function(data){
var tokens = data.split(",");
var username = tokens[0];
var name = tokens[1];
});

Categories