Jquery, tablednd and ajax post - php

So, im using $.tableDnD.serialize() function, to get the current order of the Table TR-s, and want to post to a php function alongside with another variable.
$("#articlestable").tableDnD({
onDragClass: "drag",
onDrop: function(table, row) {
$.post('<?php echo HTML_ROOT; ?>/admin/cikkek/updateOrder/', {
pagesid : "1",
arr : $.tableDnD.serialize()
});
}
});
If i am sending the serialized data only, there is no problem with the access.
According to firebug the sent data:
arr articlestable[]=1&articlestable[]=2&articlestable[]=4&articlestable[]=3
pagesid 1
The main question, how can i get the data in php?
I thought:
$pagesid = $_POST["pagesid"];
$orderarr = $_POST["arr"]["articlestable"];
Thanks for help, and sorry for my english.

I think what you want to do is parse string. I could be wrong.
<?php
$arr = array();
$str = $_POST['arr'];
parse_str($str, $arr);
?>
In doing this, you should be able to then access the array as ->
echo $arr[0]; // outputs 1
echo $arr[1]; //outputs 2
echo $arr[2]; //outputs 4
So on and so forth.
EDIT
I should also note that using this method, you can still access your pageid by using the following:
echo $arr['pagesid'];

Related

jquery ajax sortable pass data in object as key value after serialize

I am using jquery ui sortable to reorder a list via php, I get the ids like so:
var ids = $('#sort1').sortable('serialize');
It works fine when on update in the ajax call I pass the data in the ajax call like so:
data: ids
And then catch in inside my php script like so (notice singular id):
$getids = $_POST['id'];
All that works fine, however I want to pass the data inside an object because there are other things I want to pass along as well, but it does not seem to be working.
I tried:
data: {
id: ids
},
then I get this php error:
Warning: Invalid argument supplied for foreach() in C:\wamp\www\sortable\sort.php on line 8
And I also tried changing $getids = $_POST['id']; to $getids = $_POST['ids']; but then I get unidentifed index and also invalid argument error.
How can I pass the ids inside an object as key value pair?
EDIT:
the foreach code
$count = 1;
foreach ($getids as $key => $id) {
$q = "UPDATE titles SET sorting='$count', parent_id='1' WHERE id='$id'";
$r = mysqli_query($dbc, $q);
if ($r) {
echo 'done <br>';
} else {
echo 'problem <br>' . mysqli_error($dbc);
}
$count++;
}
I had this issue and came across this post, as it doesn't include any code to solve the issue. I finally found a solution that worked for me...
In my Ajax request I converted my sortable UI to an array using the following:
var data = $(this).sortable('toArray');
Then the Ajax request was sent the following way:
data: { sectiononelink: data, currentUserID: user_id },
Then because the sortable to array function gave me a string such as sectionone-asectionone-bsectionone-csectionone-d etc... I only wanted the letters after the "sectionone-" part of the string as I was looking to order a list in my html using the letters a - z.
In my PHP I used a foreach loop which contained:
$profileLinkOrder = "";
foreach($_POST['sectiononelink'] as $value)
{
$profileLinkOrder .= substr(strstr($value, "-"), 1);
}
Then the variable $profileLinkOrder would come out like abcdefg etc... Depending on how I had my sortable UI list on my HTML page.
This worked for me so I hope someone else can use this to solve this problem. I could not find any other solutions on the web. Let me know if this helps.

Echo/return an array in php

Im trying to query a database from a php file then return the results (userLOC of each row) to the calling Jquery function.
Calling Jquery:
$.post(url, data, function (data)
{
alert(data);
})
relavent PHP:
$sql = "Select * from location";
$result = mysql_query($sql);
$stack = array();
while($row = mysql_fetch_array($result))
{
array_push($stack, $row["userLOC"]);
}
return $stack;
The problem is that I cant return it correctly, if I "echo $stack" it does not work it says Im trying to convert the array to string. If I "echo $stack[0]" it will give me the first result in the array correctly so I know the values are being stored correctly (as are $stack[1], etc.) but this only sends the one value back. And if I "return $stack" as pictured nothing is alerted because nothing is echoed. How would I go about getting the whole array back so that I could iterate through and use them on the jquery side?
In PHP
$foo = array();
echo $foo;
will produce the literal string Array as output.
You need to convert your array into a string. Since you're dealing with a Javascript target, use JSON as the perfect means of doing so:
$foo = array('a', 'b', 'c', 'd', 'e');
echo json_encode($foo);
Then in your JS code:
$.get(...., function (data) {
alert(data[1]); // spits out 'b'
});
Just remember to tell jquery that you're expecting JSON output.
You need to wrap (serialize) the data in a way that can be transported to the client via HTTP and used to get the original data.
Usual container formats are XML and JSON. JSON is well suited for usage in JavaScript, so use the PHP function json_encode() and echo the result.
Youll want to use JSON!
Client-side:
jQuery.post(url, data, function( data ) {
//Data is already converted from JSON
}, "json");
Server-side:
return json_encode($stack);
Explanation
Hope this helps!
echo json_encode($stack); can help you
at jquery side use jQuery.parseJSON()
You need to convert the array to a JSON object like this : return json_encode($stack);
Just convert your array it to a JSON object and return it back to your JavaScript:
return json_encode($stack);
As others have said, you may wish to wrap the output using something like json:
echo json_encode($stack);
However, if you aren't looking for an output with the complexity of JSON formatting, you could just use implode() to output a comma separated list:
echo implode(',',$stack);

json encoding 2 dimension array

I have the following in php:
$query = mysql_query($sql);
$rows = mysql_num_rows($query);
$data['course_num']=$rows;
$data['course_data'] = array();
while ($fetch = mysql_fetch_assoc($query) )
{
$courseData = array(
'course_name'=>$fetch['course_name'],
'training_field'=>$fetch['training_field'],
'speciality_field'=>$fetch['speciality_field'],
'language'=>$fetch['language'],
'description'=>$fetch['description'],
'type'=>$fetch['type'],
);
array_push($data['course_data'],$courseData);
}
echo json_encode($data);
when I receive the result of this script in jquery (using post)
I log it using :
console.log(data['course_data']);
and the output is :
[Object { course_name="Introduction to C++", training_field="Engineering" , speciality_field="Software", more...}]
But I can't seem to figure out how to access the elements.
I tried
data['course_data'].course_name
data['course_data']['course_name']
Nothing worked. Any ideas
When you array_push($data['course_data'],$courseData); you are actually putting $courseData at $data['course_data'][0] and therefore you would access it in JavaScript as data['course_data'][0]['course_name'].
If you only intend to have one result, instead of array_push($data['course_data'],$courseData); you should just specify $data['course_data'] = $courseData. Otherwise, you should iterate over data['course_data'] like so:
for (i in data['course_data']) {
console.log(data['course_data'][i]['course_name']);
}
You should specify the index in the first array for instance
data['course_data'][0]['course_name'];
you could make it better if you had defined the first array just as variable not a variable within an array
$data['course_data'][0]['course_name']
should do the trick. If not please send the output of var_dump($data)
Assuming the PHP code is correct, you will receive a JSON data like:
{
"course_num":34,
"course_data":[
{
"course_name":"name_value",
....
},
....etc (other object based on SQL result)
]
}
So, if you want to access to the total number of result:
data.course_num
If you want to access to the first element of the list of result:
data.course_data[0]
If you want to access to the name of the first element of the list of result:
data.course_data[0].course_name
or
data.course_data[0]['course_name']
use jquery's parseJSON method to get all the goodies out of the json object...
http://api.jquery.com/jQuery.parseJSON/

json returning string instead of object

i have
$age = implode(',', $wage); // which is object return: [1,4],[7,11],[15,11]
$ww = json_encode($age);
and then i retrieve it here
var age = JSON.parse(<?php echo json_encode($ww); ?>);
so if i make
alert(typeof(<?php echo $age; ?>)) // object
alert(typeof(age)) //string
in my case JSON.parse retuned as string.
how can i let json return as object?
EDIT:
var age = JSON.parse(<?php echo $ww; ?>); // didnt work , its something syntax error
implode returns a string, so it is only natural that json_encode encodes it as such. It does not recognize already JSON-like data passed as a string.
If you want to get an object, you have to pass an associative array to json_encode:
$foo = array(
1 => 4,
7 => 11,
15 => 11
);
echo json_encode($foo); // {1:4,7:11,15:11}
With so little info about what $wage looks like before it's imploded, it's hard to tell exactly what you want to get. How is that structure ([1,4],[7,11],[15,11]) an object? Is the first element of each tuple a key? That's what I assumed with my example, but it might be off.
var age = [<?php echo $age; ?>];
a. You get a syntax error because you need to enclose the string within quotes, like so:
var age = JSON.parse("<?php echo $ww; ?>");
b. Moreover, you don't need JSON.parse. You can simply echo the php var after it was already json_encoded in the server side:
var age = <?php echo $ww; ?>;
JSON.parse is there to convert a JavaScript string to an object. In the case of PHP string, once it is built as JSON, echoing it in the right place is equivalent to coding it yourself.

JSON_encode adding too much stuff! How do I filter it all out?

I'm calling in values using PHP to cURL a site's API. I'm able to pull the data in and put into an array just fine, but when using JSON, one of the attributes ($title) comes back with too much data.
For example, if I just do
echo $new_array[27]['title'];
-> I get "Event Name" but if I do
echo json_encode($new_array[27]['title']);
-> I get {"#attributes":{"abc_id":"8"},"0":"Event Name"}
I want to use JSON as this works with something else I'm doing, but is there a way I can strip out the {"#attributes":{"abc_id":"8"},"0": part leaving just the "Event Name" as a string by itself?
Try:
$json = $new_array[27]['title'];
echo json_encode($json);
I'm not sure what you have in your array there, so these are a guess!
You could try:
unset($new_array[27]['title']['#attributes']);
Or:
$a = array();
foreach($new_array[27]['title'] as $arr) {
$a[] = $arr->__toString();
}
echo json_encode($a);

Categories