I'm trying to pass my JS array to PHP array and all of the solutions that I have found here is useless or I can integrate these solutions to my problem.
Javascript
$('#siparisButon').click(function(){
var splitListe = $('#siparis-block span').text();
splitListe = splitListe.split("- ");
splitListe = JSON.stringify(splitListe);
$.post("menu.php",{'siparisListe[]': splitListe});
// I have a div that shows the result of PHP function and it says undefined index.
$('#fonksiyon').show();
})
PHP
function ekleme(){
if($_POST['siparisListe']){
$liste = $_POST['siparisListe'];
echo $liste;
}
}
instead of this
$('#siparisButon').click(function(){
var splitListe = $('#siparis-block span').text();
splitListe = splitListe.split("- ");
splitListe = JSON.stringify(splitListe);
$.post("menu.php",{'siparisListe[]': splitListe});
// I have a div that shows the result of PHP function and it says undefined index.
$('#fonksiyon').show();
})
modify you code in to this
$('#siparisButon').click(function(){
var splitListe = $('#siparis-block span').text();
splitListe = splitListe.split("- ");
var input_data = new FormData();
$.each(splitListe,function(index,value){
input_data.append("siparisListe["+index+"]",value)
});
$.ajax({
url: "menu.php",
data: input_data,
type: "POST",
success: function(data) {
$("#passwordMatch").html(data);
},
error: function(data) {}
})
// I have a div that shows the result of PHP function and it says undefined index.
$('#fonksiyon').show();
})
Remove the [] from the POST field name and pass it an array (jQuery will JSON encode it for you).
$('#siparisButon').click(function() {
let splitListe = ($('#siparis-block span').text() || '').split('- ');
if (splitListe) {
$.post("menu.php", { siparisListe: splitListe });
$('#fonksiyon').show();
}
});
Then in your PHP to verify:
function ekleme() {
if ($liste = $_POST['siparisListe']) {
var_dump($liste);
}
echo 'No $liste array in POST.';
}
Related
I try to take object from my controller, when I console.log(response) it show the value correctly which is in
[
{
"itemValue":100,
"itemUnit":"2"
}
]
unfortunately I try to use the object like response.itemValue when I console it show undefined. I try var object = response. during the console it show the same value. Please I want to use the response data.
if(itemID){
$.ajax({
type:'POST',
url:'?syspath=ajax&controller=ajax&action=getActItemDose',
data: { 'itemId': itemID, 'itemType': itemType },
success:function(response){
// var obj = jQuery.parseJSON(data);
console.log(response);
var object = response;
var value = object.itemValue;
var unit = object.itemUnit;
console.log(object);
console.log(value);
}
});
}
This is controller where I encode the object into Json
$row = $getProcess->fetch();
$object[] = array(
'itemValue' => $row['each_dose'],
'itemUnit' => $row['unit_dose']
);
echo json_encode($object);
I recommend using the jQuery library. For parsing JSON, simply do
var obj = JSON.parse(data);
// Accessing individual value from JS object
alert(obj.itemValue);
alert(obj.itemUnit);
It worked, by changing this few item
$object[] = array();
into
$object = array();
and JSON.parse(data)
var object = JSON.parse(data);
value = object.itemValue;
unit = object.itemUnit;
Your response is an array. So you need to access it like
response[0].itemValue
or you can loop through the array
response.forEach(element => {
console.log(element.itemValue);
});
Below is the example
const response = JSON.parse(`[
{
"itemValue":100,
"itemUnit":"2"
}
]
`);
response.forEach(element => {
console.log(element.itemValue);
});
i have file.txt
apple <--line 1
banana <--line 2
and this is my script
url = 'file.txt';
homelists = [];
$.get(url, function(data) {
var lines = data.split("\n"); <--i want to split it by line
$.each(lines, function(n ,urlRecord) {
homelists.push(urlRecord); <--add it to my homelists array
});
});
console.log(homelists); <-- returns array
console.log(homelists[0]); <--undefined
my problem is i cant get the inside value of homelists
how can i get homelists[0] or homelists[1]..(javascript or jquery(preferrable))
Javascript/Jquery ajax is an Async call meaning the code $.get and console.log on your example will be executed parallelly (immediate or the same times), so to parse the result of your file.txt, you need to do it inside the function (which will be executed after ajax called is done).
url = 'file.txt';
homelists = [];
$.get(url, function(data) {
var lines = data.split("\n");
$.each(lines, function(n ,urlRecord) {
homelists.push(urlRecord);
});
console.log(homelists);
console.log(homelists[0]);
});
I know this is too simple answer and may sound stupid to others but i have an idea!
why not store in the session the $.get data
url = 'file.txt';
$.get(url, function(data) {
localStorage['homelists'] = data;
});
then assign a variable to that session
homelists = localStorage['homelists'];
then make the session = null
localStorage['homelists'] = null
when you do console.log outside
console.log(homelists); <-returns string which you can manipulate to turn it into array
console.log(localStorage['homelists']); <-returns null
I dont know yet what could be the bad side/effect of this with my project.. any idea?
Since you are using jQuery, It would be better if you use AJAX. !
const ImportData = function(file){
let arrayData = undefined;
$.ajax({
url: file,
type: 'GET',
error: (err) => { throw new Error(err) },
success: ( data ) => {
arrayData = MakeArray( data );
//Do whatever you want here
console.log( arrayData );
}
});
}
const MakeArray = function(plaintext){
const array = [];
plaintext.split('\n').forEach( (line) => {
line = line.trim();
array.push( line );
} );
return array;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
const file = "https://www.w3.org/TR/PNG/iso_8859-1.txt";
document.addEventListener('DOMContentLoaded', function(){
ImportData( file );
});
</script>
In the following code i am not able to filter entry.AllLinks.
The code is as follows:
$.ajax({
url: url,
type: "get",
headers: {"Accept": "application/json;odata=verbose"},
success: function (data) {
var c = [];
var stringData = JSON.stringify(data.d.results[0].AllLinks);
//alert(stringData);
c.push(JSON.parse(stringData));
alert(c);
var xonly = c.filter(function (entry){
return entry.AllLinks != x;
});
alert(xonly);
},
error: function() {
alert('fail');
}
});
}
It does not filter and when i hover cursor over AllLinks in entry.AllLinks it is undefined.
Value of entry is coming as:
[{"AllLinks":"Link9","LinkURL":"http://www.Link9.com"},{"AllLinks":"Link6","LinkURL":"http://www.Link6.com"}]
You can use Array.filter to filter the array as per the values you require.
let arr = [{"AllLinks":"Link9","LinkURL":"http://www.Link9.com"},{"AllLinks":"Link6","LinkURL":"http://www.Link6.com"}] ;
arr = arr.filter(function(elem) {
return elem.AllLinks !== 'Link9';
});
console.log(arr);
I'm trying to send an array from Javascript to PHP.
function wishlist_save(arr){
$.ajax({
type: "POST",
url: "from.php?type=customers",
data: {info: JSON.stringify(arr) },
success: function(){
}
});
}
The array is set this way:
function getAll(){
var info = [];
var i = 0;
$(".desc").each(function(){
var value = $(this).text();
var qtt = $(this).attr('alt');
info[i] = [];
info[i]['desc'] = value;
info[i]['qtt'] = qtt;
i++;
});
return info;
}
If I output (with console.log(getAll())) the array in javascript I get the right values in Chrome Console:
[Array[0], Array[0], Array[0]]
->0: Array[0]
desc: 'John'
alt: 'Good'
->1: Array[0]
desc: 'Obama'
alt: 'Great'
But in PHP (from.php?type=customers) I can't figure out how to get those values..
$arr = json_decode($_POST['info']);
ChromePhp::log($arr[0]['desc']); // returns null
What am I doing wrong?
Solved.
The problem was on JSON.stringify(arr), which in some way didn't send properly the array to PHP.
So, all I needed was to adapt the function that retrieves the array:
var info = [];
info.push({desc: value, qtt: qtt });
Besides that, the AJAX only now need:
data: {info: arr },
And PHP:
I actually have this array var checked_rls= ['24','56'];
var checked_rls = []
$("input[name='chk_cont[]']:checked").each(function ()
{
checked_rls.push($(this).val());
});
and then I tried to pass it using AJAX
$.ajax(
{
type :"POST",
url : "sale_ajax.php",
data:
{
rls : checked_rls,
rls_date : $("#rls_date").val()
},
success: function(msg)
{
alert('saved successfully');
},
error: function()
{
alert("Failure");
}
});
and then i received the array in sale_ajax.php file like this $cont = $_POST['rls'];
Now the problem is that I can run this array in a forEach function, but when I tried to implode this array into a string it only returns one value.
For e.g. in this scenario I passed 24,56 and when I tried to implode(",",$cont); it only returns the very first value, 24:
var_dump($cont) output is
array(2){[0]=>string(2) "24" [1]=>string(2) "56"}
and the php code is:
if(isset($_POST['rls']))
{
$rls_date = $_POST['rls_date'];
$cont = $_POST['rls'];
$rls_cont_sold = implode(",",$cont);
$rls_insert = mysql_query("INSERT INTO release_details (release_date, cont_sold_id) VALUES (STR_TO_DATE('$rls_date', '%d-%m-%Y'), '$rls_cont_sold')")or die(mysql_error());
$id = mysql_insert_id();
foreach($cont as $val)
{
$cont_sold_update = "UPDATE cont_sold SET release_details_id = '$id' WHERE cont_sold_id = '$val'";
$insert = mysql_query($cont_sold_update)or die(mysql_error());
}
}
and the var_dump($_POST) is
array(2){
["rls"]=>(array(2){[0]=>string(2) "24" [1]=>string(2) "56"})
["rls_date"]=>string(10) "10-04-2015"
}
What is actually happening in this condition?
Thank you
Put below code in click event of chk_count element:-
$("input[name='chk_cont[]']").click(function(){
var checked_rls = [];
$("input[name='chk_cont[]']:checked").each(function ()
{
checked_rls.push($(this).val());
});
});
Rather than passing passing an array why don't you pass a string itself, it will reduce your number of steps.
var checked_rls = "";
$("input[name='chk_cont[]']:checked").each(function ()
{
checked_rls += $(this).val()+",";
});