UPDATE!! My code is actually valid to run. The original question is below. If you are still curious please read the question and then back to read my update.
My bad, the db actually can get updated successfully after the code runs. I accidentally set the datatype in the table as INT but my initial intention, varchar.
But from HenryDev's answer I managed to find the acquired array by post method in php becomes STRING type but array type. I used
$cameArray = $_POST['cameArray'];
echo gettype($cameArray);
to output "string" on my screen, so implode would not work oh that(see the discussions on HenryDev's answer).
However his answer will work as a charm if you set up an array in PHP and implode it, it will give you back a "string type" of your array!
UPDATE!! My code is actually valid to run. The original question is below. If you are still curious please read the question and then back to read my update.
Here is my original question
So I have a very basic question but the tutorials and answers I found online are kinda complicated for my situation.
I have a JS array like
var sentArray = ['1','2','3'];
I want to insert this array into the database as one field of a table. I use ajax to send this array to PHP and then execute the query in PHP. For instance,
$cameArray = $_POST['cameArray']; //then $cameArray is sentArray
mysqli_query($con, "INSERT INTO thisTable (arrayField) VALUES ($cameArray)");
And then I want the value in the database shown as "1, 2, 3", but the problem is the value in the database is simply shown as a single "2". The type in table is varchar.
No any JSON object involved just pure text. How could I do that? Thanks!
Here's a quick solution. If you want to store the array as an string simply do this in your PHP code.
$array = array('1', '2', '3'); // Your array
$cameArray = implode(",", $array);
echo $cameArray; // "1,2,3"
Now you can store the variable $cameArray in your Data Base. Hope it helps!
My bad, the db actually can get updated successfully after the code runs. I accidentally set the datatype in the table as INT but my initial intention, varchar.
But from HenryDev's answer I managed to find the acquired array by post method in php becomes STRING type but array type. I used
$cameArray = $_POST['cameArray'];
echo gettype($cameArray);
to output "string" on my screen, so implode would not work oh that(see the discussions on HenryDev's answer).
However his answer will work as a charm if you set up an array in PHP and implode it, it will give you back a "string type" of your array!
Related
I want extract text values from every sub objects the given JSON structure . For do that I have used following JMSEPath query translations.en.*[0].[*].children.text but I was not unable to extract the value . Can someone suggest me a correct query or other approches
It may be better if you add to the question the expected output as well.
Making a big assumption that you want all text values "flatten up" into a single array you can try this: translation.en.*[].children[].text
Ref https://jmespath.org/tutorial.html#flatten-projections
After hours of searching and testing I finally have decided to post a question.
I need to be able to make something like this to work with a function.
var myCSV = [1,3,5,6];
Currently, I can grab the CSV from the database as that is how it is stored, myColumn = 1,3,5,6. I can get it to pass as an AJAX success response but it seems to want to add quotes. I then tried to add JSON encode to my PHP side of things and JSON Parse to the success call but still cannot get the function to work. The end goal is to select checkboxes based off the csv value.
This works
var FilterArray = [1,3,5,6]; // Manually added these numbers as is for testing
$('#myForm').find('.checks').each(function () {
$(this).prop("checked", ($.inArray(parseInt($(this).val()), FilterArray ) != -1));
});
After trying to much to get my AJAX success response to work in the FilterArray, I decided to just pass it to an input value and work with it. However, cannot figure out how to not treat it as a string when I pass it to the function. Here is what I have tried.
In my getCSV.php I have at the end this
json_encode($foundCSV);
In my AJAX Success
var FilterArray = JSON.parse(response);
I have also tried it without the json_encode and just sending it to an input value which does not add quotes.
So in summary, how can I take a csv e.g. 1,3,5,6 stored value and pass it to a function that works as shown above?
Assuming you have your string in a variable, called response, and its value is "1,3,5,6", you can translate it into an array of integers with this:
response.split(',').map(e => parseInt(e))
and you can then pass the result of this to your function.
Sticking to your naming, the code should look like this:
var FilterArray = response.split(',').map(e => parseInt(e));
What the code does:
takes the response and split it by using the comma character as a delimiter
this will create an array of strings
for each string in that array, tries to parse it as an integer (an ID, i guess?)
Clarifying question: What does your $foundCSV look like on the PHP side, before you json-encode it? Is it an array or a string with comma-separated numbers? You might want to check with your developer tools/debugger what the Ajax response contains. It sounds like you have a string but expect an array.
If that's the case, you can create an array on the JS- or PHP-side. For the JS-side, consult #GregorioPalama's answer.
Alternatively, you could do this on the PHP-side, which might be shorter:
$response = explode(',', $foundCSV);
and then work with json_encode($response).
Before I describe the issue, please forgive any incorrect terms and accidental references to objects instead of arrays and vice-versa, I'm not completely up to speed on this but working my way through it.
I have the following array in PHP saved as a session variable:
{"CategoryF":[],"CategoryA":["Life","There","People","Land","Family"],"CategoryC":["Various"]}
After a thumbnail in a grid of images is dragged into a new order, it execute a function in javascript and makes a call to a PHP script using ajax. It currently only retrieves the most up to date version of a session array. It will later progress to make the necessary steps to save the updated array back to session variable and database:
var sorty = Sortable.create(thumbcontainer, {
animation: 250,
draggable: "img",
dataIdAttr: 'id',
onUpdate: function (/**Event*/evt) {
var orderList = sorty.toArray();
var catsArray =
$.ajax({
type: 'POST',
url: 'includes/proc_cats.php',
dataType: 'json'
}).done(function(returnedCatsArray) {
console.log(returnedCatsArray);
});
console.log('Dragged. Order is: ' + orderList);
}
});
proc_cats.php
<?php
// Access the existing session
session_start();
// $catsArray is a session variable, in the format as above.
$catsArray = json_encode($_SESSION['categoriesPics']);
echo $catsArray;
?>
The var orderList will produce a string with the order of each thumbnail by id, separated by comma: '42,35,95,12,57'.
The console shows the PHP array as a javascript array fine but in a different order. I want to be able to insert the string containing the orders into the array and save it back into the database. It will associate with its relevant category, similar to:
{"CategoryF":[],"CategoryA":["Life":["23,74,47,12,86,83,12"],"There","People","Land","Family"],"CategoryC":["Various"]}
But can't lose the order as other parts of the site reference the array by indices using array_keys. The console produces:
Object:
CategoryA:Array[0]
CategoryC:Array[0]
CategoryF:Array[5]
Have I missed something? I believe that the overall array is an object rather than an array because it didn't have any index whereas the subcategories did and they get presented as an array. array_keys in PHP have made it straightforward enough to work around any indexing problems up until now on the PHP side in other areas of the site but I'm wondering if the solution for the javascript side is something as straightforward? The subcategories currently have indices only because I've yet to associate and orderList with them so I'm not trying not to backtrack and build an index for the array as it's going to get difficult (unless there's a simple way to do this that I've overlooked).
(This is a more specific version of a question I asked an hour ago that I've now deleted for being too broad).
I believe you have a slight confusion based on the terms 'associative array' and 'array'. A php associative array corresponds to a javascript object. returnedCatsArray should be accessed similar to $catsArray. ie. with keys. If one of those keys returns an an actual array, you can then index into it.
php array_keys would be Object.keys(returnedCatsArray) in javascript.
From further research it appears this is just not doable. So the best way to do this may be to provide an order array alongside my category array.
If I add the additional code of:
$parentCatOrder = array_keys($catsArray);
in my proc_cats.php script I have a concise way of generating an index reference for my original array on the fly each time. This produces an array similar to:
$parentCatOrder = {'categoryF', 'categoryA', 'categoryC'};
which has an index that I can refer to that keeps its order. So $parentCatOrder[2] will always produce 'categoryC' unless I've changed the array myself.
I then return both arrays to javascript using the following:
$return_data['catsarray'] = $catsArray;
$return_data['parentcatsorder'] = $parentCatOrder;
// Encode it back into a JSON object before sending
echo json_encode($return_data);
In javascript I can reference returnedCatsArray.catsarray[returnedCatsArray.parentcatsorder[1]][3] if I'm working with an index of 1-3 and guarantee this will produce the same result for every user unless the array has been changed by the user.
I have a database with strings and which language this string belongs. A string has a unique name, which I use to identify it, and then a translation for each language.
With PHP, I get this information from the database and store it in an associative array like:
$languages['strings']['lang']['unique_string_name'] = $translation;
Now, as I want my Javascript code to be translated too, I need to pass it to. I've tried doing it in JSON, but some $translation have quotes and double quotes, and it's a hell to escape and get it all correct - because escaping just escapes the whole JSON string, not only translation.
So, what I've done is loop the whole array and echoing the $translation in a Javascript associative array again, but this time with addslashes - only the translation.
However, if I look to the Source Code, I see 600 lines of Javascripts entries, one for each translation (of course, this has nothing strange, just simply UGLY).
I was wondering if there's a much cleaner way of passing this translation array to my Javascript code without having to loop the PHP array and echo it to a JS variable.
Thanks for your time and answers!
All you really need is:
<script type="text/javascript">
var languages = <?php echo json_encode($languages); ?>;
</script>
You'll end up with an exact duplicate of your PHP array in JS, so
echo $languages['strings']['lang']['unique_string_name']; // PHP
alert(languages.strings.lang.unique_string_name); // JS
will both bring up the same translation.
When i add new category, i am storing child category in serialize format, Which works just perfect. Like :-
a:1:{i:0;s:2:"41";} But when i edit it back and try to change it to other category, which are loaded via Ajax-Json Javascript. But value is still 41 as above. It stores value in below format :-
s:2:"41";, Which is wrong and i get error while going back and editing it again.
Does any one know how this serialize failed to store in proper format ?,
Thanka
I got it Working, Oh, I had to dig and Understand what is serialize first and how php understands and converts it in serialize format.
Here you go from php.net
String s:size:value;
Integer i:value;
Boolean b:value; (does not store "true" or "false", does store '1'
or '0')
Null N;
Array a:size:{key definition;value definition;(repeated per
element)}
Object O:strlen(object name):object name:object
size:{s:strlen(property name):property name:property
definition;(repeated per property)}
That means, I was not sending value as array, and since value was not getting sent in array via HTML form, it didn't appended a for array tag. :)
And when i made my HTML``input field name as category[] from category, Everything worked as expected :)
Thanks
How are you editing it (code sample)?
You should unserialize it first, then modify, and serialize again.