Why Javascript array doesn't implode in php? - javascript

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()+",";
});

Related

Passing Array to PHP from Javascript

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.';
}

how to seperate each variable in JSON

so, I have an ajax call that displays my JSON like this:
{"main_object":{"id":"new","formData":"language=nl_NL&getExerciseTitle=test&question_takeAudio_exerciseWord%5B0%5D=test&Syllablescounter%5B0%5D=test&Syllablescounter%5B1%5D=test"}}
but I would like to have it like this:
{"main_object":{"language":"nl_NL","getExerciseTitle":"asd","question_takeAudio_exerciseWord":["asd"],"Syllablescounter":["ASDasd",""]}}
The only thing I want to add is the "id":"new".
This is my ajax call (my JSON starts looking like the first one with my ajax call)
function saveExerciseAjaxCall() {
$("#my_form").on("submit", function (event) {
event.preventDefault();
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: {id: getUrlParameter('id'), formData: $('#my_form').serialize()},
dataType: 'json',
}).done(function (response) {
window.location = 'index.php';
});
});
}
edit: Ouni wanted me to show what is going on in the php script so here it is:
<?php
include_once('database_json.php');
$data = $_POST;
//Setup an empty array.
$errors = array();
if (isset($data)) {
$newExerciseData['main_object'] = $data;
$exerciseArray = $data['main_object'];
$databaseFile = 'json_files/database.json';
$textContent = file_get_contents($databaseFile);
$database = json_decode($textContent, true);
if ($data['id'] === 'new') {
if (count($database['data']) == 0) {
$ID = 0;
} // ending database['data'] count 0.
else {
$maxID = max($database['data']);
$ID = ++$maxID["id"];
} // ending the max ID else statement.
$newJsonFile = 'jsonData_' . $ID . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData = array(
'id' => $ID,
'exercisetitle' => $data['formData']['getExerciseTitle'],
'language' => $data['formData']['language'],
'file' => $newJsonFile
);
$database['data'][] = $newArrayData;
} // } op regel 34 lijkt verdwaald...?
else {
$index = array_search((int) $_POST['id'], array_column($database['data'], 'id'));
$correctJsonFile = 'json_files/jsonData_' . $_POST['id'] . '.json';
$newJsonFile = 'jsonData_' . $_POST['id'] . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData2 = array(
'id' => (int) $data['id'],
'exercisetitle' => $data['formData']['getExerciseTitle'],
'language' => $data['formData']['language'],
'file' => $newJsonFile
);
$database['data'][$index] = $newArrayData2;
} // closing off the else statement
$newExerciseData['main_object'] = $database['data'];
header('Content-Type: application/json');
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
echo json_encode($newExerciseData, JSON_UNESCAPED_UNICODE);
} //closing off the if isset.
how could this be achieved? I know it isn't my saveJson.php that's the problem. I know it's my ajax call since it starts showing like the first JSON piece of code when I add the id: getUrlParameter('id')
Just to focus on your question itself without regard for the perfectly valid comments made about your overall approach, it looks like you have data in a querystring format and you want to parse it into a JSON format. The quesrystring format is the data that looks like this:
language=nl_NL&getExerciseTitle=test
And you ultimately wants this:
{
language: "nl_NL",
getExerciseTitle: "test"
}
and so on.
One way to accomplish this is to use an existing library that does precisely that for you. For example, the query-string package.
For example, given a string:
const result = "language=nl_NL&getExerciseTitle=test";
const parsed = queryString.parse(result);
will produce the result you expect.
Here's how to parse your query string in vanilla JavaScript, without installing a third-party package:
const start = {"main_object":{"id":"new","formData":"language=nl_NL&getExerciseTitle=test&question_takeAudio_exerciseWord%5B0%5D=test&Syllablescounter%5B0%5D=test&Syllablescounter%5B1%5D=test"}}
const temp = Object.assign({}, start);
temp.formData = decodeURIComponent(start.main_object.formData)
.split("&")
.reduce((result, data) => {
const components = data.split("=");
let prop_name = components[0];
const prop_value = components[1];
const array_char_index = prop_name.indexOf('[');
if (array_char_index > 0) {
prop_name = prop_name.substring(0, array_char_index);
if (result[prop_name] === undefined) { result[prop_name] = []; }
result[prop_name].push(prop_value);
}
else {
result[prop_name] = prop_value;
}
return result;
}, {})
;
console.log(temp.formData);
I recommend using vanilla JS whenever possible, so that you learn the concepts, and so you can adapt it to your own needs, when you find yourself wanting more.

JSON invalid syntax between js and php

I have this code:
var temp = 'tag1,tag2'.split(','),
tags = [];
if (temp.length > 0) {
for (i = 0; i < temp.length; ++i) {
tags.push(temp[i]);
}
}
Now I want to send this array as an Ajax request:
var data = {
action: 'my_wp_ajax',
ajax_req: JSON.stringify(tags)
};
$.post(
ajaxurl,
data,
function (data) {
console.log('this is data: '+data);
}
);
On the other side I have these codes:
echo $_POST['ajax_req'];
$temp = json_decode($_POST['ajax_req']);
$error = json_last_error();
echo $error;
The result I see in browser console is:
this is data: "[\\\"tag1\\\",\\\"tag2\\\"]4"
As you can see in above result, last json error is 4 which means invalid json syntax. I don't know what is wrong in above codes. If I try
foreach (json_decode($_POST['ajax_req']) as $hi)
echo $hi;
In console it only shows me
this is data: ""
What am I doing wrong?
Edit:
I tried var_dump(get_magic_quotes_gpc(), $_POST); and the result in console:
"bool(false)\narray(2) {\n [\"action\"]=>\n string(8) \"my_wp_ajax\"\n [\"ajax_req\"]=>\n string(19) \"[\\\"tag1\\\",\\\"tag2\\\"]\"\n}\n0"
No need to double stringify array, data passed to array is going to be properly handled by jQuery:
var tags = 'tag1,tag2'.split(',');
var data = {
action: 'my_wp_ajax',
ajax_req: tags
};

Load data from table using PHP & AJAX

I'm trying to retrieve data from table using PHP and AJAX, at the moment I'm able to display the result of my query in json format, what I want to do is select an specific data from that array, for example I get this array:
{data: [{IdProduct: "1", Name: "Name here..........",…}]}
For example I want to select only Name, I tried doing this:
function LoadProductos() {
$.ajax({
url: '../../class/loadProd.php',
method: 'POST',
success: function (data) {
var aRC = JSON.parse(data);
for (var i = 0; i < aRC.length; i++) {
console.log(aRC[i].Name);
}
}
});
}
But this doesn't shows anything, how can I do this? This is my PHP code:
while($row = mysqli_fetch_array($registros)) {
$table.='{
"IdProduct":"'.$row['IdProduct'].'",
"Name":"'.$row['Name'].'",
"Description":"'.$row['Description'].'",
"ImagePath":"'.$row['ImagePath'].'"
},';
$table = substr($table, 0, strlen($table) -1);
echo '{"data":['.$table.']}';
}
There are couple of things you need to change in your code, such as:
That's not how you should create a json string. Create an empty array before the while() loop and append the row details to this array in each iteration of the loop. And after coming out of the loop, simply apply json_encode() function to the resultant array to get the final json string.
$table = array();
while($row = mysqli_fetch_array($registros)) {
$table[]= array(
'IdProduct' => $row['IdProduct'],
'Name' => $row['Name'],
'Description' => $row['Description'],
'ImagePath' => $row['ImagePath']
);
}
echo json_encode($table);
Since you're expecting a json string from server, add this setting dataType:'json' to your AJAX request. dataType is the type of data you're expecting back from the server. And in the success() callback function, simply loop through the json result to get the relevant data.
function LoadProductos() {
$.ajax({
url: '../../class/loadProd.php',
method: 'POST',
dataType: 'json',
success: function (data) {
for (var i = 0; i < data.length; i++) {
alert(data[i].Name);
}
}
});
}
First off, your shouldn't echo the json data in the loop. It should be outside the loop.
You shouldn't build your own json data either.
Let's build an array that looks like the json response you want. Then we'll use the function json_encode() to encode it as a proper json-string:
// Define the response array
$response = [
'data' => []
];
while($row = mysqli_fetch_array($registros)) {
// Push a new array to 'data' array
$response['data'][] = [
'IdProduct' => $row['IdProduct'],
'Name' =>.$row['Name'],
'Description' => $row['Description'],
'ImagePath' => $row['ImagePath']
];
}
// Now, let's encode the data:
echo json_encode($response);
In you PHP file make changes according to this:-
$outp = array();
$outp = $res->fetch_all(MYSQLI_ASSOC);
For make sure that json_encode don't return null
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}
echo json_encode(utf8ize($outp));
You JavaScript is okay You just need to change code in PHP.

jquery post form and variables together

I used this Code to send a form + a variable to a php-script.
function upload() {
var test = "test";
var infos = $('form').serialize() + '&' + test;
$.post("ajax.php", { infos: infos }).done(function (data) {
alert(data);
});
}
now the PHP-Code:
$data = $_POST['infos'];
echo $data;
returns: formfield1=value1&formfield2=value2&formfield3=value3&test
All values are in this variable...
But how i can use them seperatly with PHP?
For example:
$data = $_POST['formfield1'];
didn't worked :(
Use jQuery's serializeArray(). It will return you with array of objects that contain 2 properties: name and value. You can then parse it and pass it as data.
It could look like this
var formdata = = $('form').serializeArray();
var infos = { };
for (var i = 0; i < formdata.length; i++) {
infos[formdata[i].name] = formdata[i].value;
}
// To add separate values, simply add them to the `infos`
infos.newItem = "new value";
$.post("ajax.php", infos).done(function (data) {
alert(data);
});
Then in PHP, you'll retrieve values using $_POST["formfield1"].
Try to explode them with -
$data = $_POST['infos'];
$form_data = explode('&', $data);
$posted_data = array();
foreach ($form_data as $value) {
list($key, $val) = explode('=', $value);
$posted_data[$key] = $val;
}
var_dump($posted_data);
You can use the parse_str method to convert the query string into an array.
In your case, you can do something like this:
parse_str($_POST['infos'], $data); // $data['formfield1'], $data['formfield2'], $data['formfield3'] have the values you need
More details here: http://php.net/manual/en/function.parse-str.php
// here is the jquery part
function upload() {
var test = "test";
var infos = $('form').serialize() + '&' + test;
$.post("ajax.php", { infos: infos },function (data) {
alert(data); // the fetched values are alerted here.
});
}
//the php part is here
$data = $_POST['infos'];
$field_seperator='&';
$val_seperator='=';
$form_data_val=explode($field_seperator,$data);
foreach($form_data_val AS $form_vals){
$vals=explode($val_seperator,$form_vals);
echo $vals[1];// here the value fields of every form field and the test is fetched.
}
try this .

Categories