I have a page with 3 forms on it.
To create a valid get(or post) data str with each form as a nested array nested arrays.
psuedo-code for what i want (just don't know how to wrap them in nested arrays..):
var data_str = $('#form1').serialize() + $('#form2').serialize() + $('#form3').serialize();
$.ajax(.....
desired output on processing file:
print_r($_GET);
/*
{
['form1'] => .....nested array here..
['form2'] => .....nested array here..
['form3'] => .....nested array here..
}
*/
$.get({
data:{
form1:$('#form1').serialize(),
form2:$('#form2').serialize(),
form3:$('#form3').serialize()
},
//other options
I'm not a javascript pro but I've built a solution and it works, enjoy:
function mutliple_forms_to_data_str(array_of_form_ids){
var multidim_data = {};
$.each(array_of_form_ids, function(index,id) {
var forms_data = $('#'+id).serializeArray();
var htemp = {};
$.each(forms_data, function(index,val) {
htemp[val.name] = val.value;
});
multidim_data[id] = htemp;
});
return multidim_data;
}
Use array push, to do that
but honestly you best use one form no need for all three of them unless is last resource.
or simply.
var data_str = {
'form1': $('#form1').serialize(),
'form2': $('#form2').serialize(),
'form3': $('#form3').serialize(),
}
PHP would read them fine as a tree like array,
You might have to use serializeArray(); instead
Related
I have a jquery function that calls a controller which in turn calls a function that I extracted the data from the users table. I return an array cin all the data in the table. ID, username etc etc.. So mold date in jQuery and indeed the array is full. Ex. [{"Id_user": "21", "username": "cassy1994"}].
From this array I have to extract only the username. How can I do?
This is the Ajax function:
$(".apprezzamenti").click(function()
{
var id = $(this).attr('id');
var txt = "";
$.get("http://localhost/laravel/public/index.php/apprezzamenti/"+id,
function(data)
{
$(".modal-body-apprezzamenti>p").html(data);
});
});
If the json is parsed, your object is stored in an array, so:
data[0].username
If not (if it is a string), you need to parse it first:
data_parsed = JSON.parse(data);
// data_parsed[0].username
assuming data is where your response is stored, data[0].username should work. Example:
$(".modal-body-apprezzamenti>p").html(data[0].username);
To print all usernames:
var count = 0;
$.each($(".modal-body-apprezzamenti>p"), function() {
this.html(data[count].username);
count++;
]);
Hope this helps!
So, this is the problem. It's okay though, I realized that with this code I'm using can not seem to generate as many sections as there are users want to print and it shows me only the last username because it can generate only a paragraph in html. A possible solution which would it be?
This is the code:
$(".apprezzamenti").click(function()
{
var id = $(this).attr('id');
var txt = "";
$.get("http://localhost/laravel/public/index.php/apprezzamenti/"+id,
function(data)
{
data_parsed = JSON.parse(data);
for(var i=0; i<data_parsed.length; i++)
{
$(".modal-body-apprezzamenti>p").html((data_parsed[i].username));
}
});
});
So I have got to a stage in my website where I need to pack a lot of information into a single json array like object, so in order to do this I need to pack a list of array information under a certain key name, then another set of data under another key name.
So for example:
$array = array();
foreach(action goes here)
{
$array['data1'] = array('information' => data, 'more_information' => more_data)
}
$array['data2'] = array("more data");
This basically illustrates what I am trying to do, I am able to partially do this, however naming the key for the new data set only replaces each data, instead of adding into it in the foreach loops.
Now if this part isn't too confusing, I need some help with this. Then in addition to this, once this is sorted out, I need to be able to use the data in my jQuery response, so I need to be able to access each set of data something like: json.data1[i++].data, which would ideally return "more_information".
You need an incremental number in that loop and make the results available as a json object...
$array = array();
$i = 0;
foreach(action goes here)
{
$array['data'.$i] = array('information' => data, 'more_information' => more_data)
$i++;
}
$array['data2'] = array("more data");
$data = json_encode($array);
Then in php you might set a js var like so:
<script type="text/javascript">
var data = <?php echo $data; ?>;
</script>
which could then be accessed in js easily:
alert(data.data1.information);
If I understand your question correctly you expect to get this object as a response to something? Like a jQuery .ajax call?
http://api.jquery.com/jQuery.ajax/
This link illustrates how to use it pretty clearly. You would want to make sure to specify dataType = "json" and then place your data handling in the success call:
$.ajax({
url: 'some url string',
type: "GET",
dataType: "json",
success: function(data)
{
$.each(data, function(i, v){
console.log(data[i]);
});
},
error: function()
{
//error handling
}
});
This is relatively untested, but the concept is what I am trying to convey. You basically make your multi-dimensional array in php and json_encode it. Either of these methods will allow you to parse the json.
I am trying to split the values of an array i'm generating through an autosuggest.
The output of the values are as such:
[
{"value":"12","name":"Solid Fuel Fire Installers"},
{"value":"11","name":"Oil Engineers & Boiler Fitters"}
]
I want to extract the values 12 & 11 and store as a variable so I can save these to a database through php. This is what I have tried so far and to no success:
<script type="text/javascript">
var arr = $(".as-values").val().split(",");
var category_1=arr[0];
var category_2=arr[1];
var category_3=arr[2];
</script>
I only have 3 categories as I have set a limit on the amount they can add (3).
Many thanks in advance.
That looks like json. Why not just access it as a native JS structure?
var json = $(".as-values").val();
data = jquery.parseJSON(json)
alert(data[0].name); // solid fuel fire installers
The array is an array of objects, not strings, so why not treat them as such?
<script type="text/javascript">
var arr = $(".as-values").val();
var category_1=arr[0].value;
var category_2=arr[1].value;
var category_3=arr[2].value;
</script>
Not sure what you're trying to do. Does this sound like it?
var values = '[{"value":"12","name":"Solid Fuel Fire Installers"},{"value":"11","name":"Oil Engineers & Boiler Fitters"}]';
values = $.parseJSON(values);
var submitValues = {};
$.each( values, callback(i, element){
submitValues[element.value] = element.name;
});
The string you're trying to use is valid json so you should be able to just decode the string with native functions in js that would be JSON.parse(json_string, reviver) in php you would use json_decode($json).
Decoding the string will give you an object/array you should be able to work with easily.
(This is what you want right?)
Is your question how to access an element by value of its property? You could do this:
var elements = [
{"value":"12","name":"Solid Fuel Fire Installers"},
{"value":"11","name":"Oil Engineers & Boiler Fitters"}
]; // Retrieve however you want
var element;
for(var i = 0; element = elements[i]; i++) {
if(element.value == 11) {
// It's number 11, for example
}
}
Of course you should probably put that in a function:
function findByProperty(elements, property, value) {
var i, element;
for(i = 0; element = elements[i]; i++) {
if(element[property] === value) return element;
}
return null;
}
// ... define 'elements' as before
var numberEleven = findByProperty(elements, 'value', "11");
Since you already have an array of a valid json you dont need to parse it. Just try this.
var arr = [
{"value":"12","name":"Solid Fuel Fire Installers"},
{"value":"11","name":"Oil Engineers & Boiler Fitters"}
]
var category_1=arr[0].name;
var category_2=arr[1].name;
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.
I have gathered data with jQuery, putten it into a multidimensional array, used JSON.stringify on it and passed it to PHP by use of AJAX, for some reason json_decode keeps on giving me a Syntax error, malformed JSON error.
Heres the JSON that gets passed on to the PHP
[\"foo\",\"foobar did the baz\",[[\"bar\",\"kg\",\"200\"],[\"baz\",\"l\",\"1337\"]]]
The weird thing is that i use JSON.stringify on the multidimensional array in JS. Heres how i put it together
var dataz = [];
var arrayContainingAll = [];
$("li", "#ingredientlist").each(function() {
var tempArray = [];
tempArray.push($(".ingredientname", this).text());
tempArray.push($(".unittext", this).text());
tempArray.push($(".amounttext", this).text());
arrayContainingAll.push(tempArray);
});
dataz.push($("h1").text());
dataz.push($("#method").val());
dataz.push(arrayContainingAll);
var json = JSON.stringify(dataz);
How can i make PHP parse the multidimensional array correctly?
I have fixed it by passing on 3 different stringified arrays, but its more the curiosity of why a multidimensional array fails
The PHP to show what happens is: var_dump(json_decode($_POST['ingredients']));
because it appearantly is important to show how i post the data, heres the JS to do the ajax request
$.ajax({
url: '/api/savenewrecipe.php',
type: 'POST',
data: 'ingredients=' + json + "&name=" + $("h1").text() + "&method=" + $("#method").val(),
success: function(result) {
if (result.ok == true) {
// #todo remove this for debugging purposes
//document.location.href = '/recipe/' + result.id;
}
else {
showError("Noget gik galt!", 2000);
}
}
});
If your server uses magic quotes, you'll need to remove them:
if (get_magic_quotes_gpc()) {
$_POST['ingredients'] = stripslashes($_POST['ingredients']);
}