Decoding javascript array in PHP - javascript

I've been trying to decode a Javascript array in PHP for several days now with no luck.
I basically have a PHP while loop that loops through all products in my SQL database and it spits out a checkbox on each row to allow users to select 1 or more product to action via a PHP script.
My HTML & form is:
<div class="error_box"><?php echo $_SESSION['newdata']; ?></div>
<div class="error_box"><?php echo $_SESSION['errordata']; ?></div>
<form>
<input type='submit' value='Bulk update products -->' id='bulk-change-products' onClick='updateProduct()'>
<input type='checkbox' name='products[]' id='serialized' value='$product_no' onclick='serialize()'>
</form>
My Javascript code:
window.serialize = function serialize() {
var values = [].filter.call(document.getElementsByName('products[]'), function(c) {
return c.checked;
}).map(function(c) {
return c.value;
});
console.log(values);
$('#result').html(values);
}
function updateProduct(values){
$.ajax({
url: "https://tech-seo.co.uk/ecommerce/products/bulk_process_products.php",
method: "POST",
data: {array:values},
success: function(res){
}
})
}
Console log shows the data correctly e.g.
(2) ["1", "2"]
0: "1"
1: "2"
length: 2
My php code after posting with AJAX:
session_start();
$getArray = json_decode($_POST['data']);
// checking if data exists
if ($getArray != null ){
$_SESSION['newdata'] = "Success!";
}else{
// either of the values doesn't exist
$_SESSION['errordata'] = ">>>>>> There was an error <<<<<<<";
}
I always get '>>>>>> There was an error <<<<<<<' when I select the products and click the submit button.
Any help is appreciated.
Thanks.
Stan.

You're not passing the values array when you call updateProduct() from the onclick attribute. It needs to get the values itself.
function updateProduct() {
var values = $("input[name='products[]']:checked").map((i, el) => el.value).get();
$.ajax({
url: "https://tech-seo.co.uk/ecommerce/products/bulk_process_products.php",
method: "POST",
data: {
products: values
},
success: function(res) {
}
})
}
If you pass the array in the data: option, you don't need to use json_decode() in PHP. jQuery will send the parameters using the URL-encoded format that PHP decodes into an array in the $_POST element.
$getArray = $_POST['products'];

Related

show values entered in form as a table before getting submitted

First, I do not have much talent in ajax so please consider that while answering. Here I want to get all the values which I inserted into the form in a table before getting submitted but unfortunately am not getting the results I want. So far I have done this. Please have a look.
<script>
var form_data={ agent_name: $('#agent_name').val(),
type: $('input[name="type"]').val(),
number: $('#number').val(),
quantity: $('#quantity').val()
}
$.ajax({
type: 'POST',
url: '<?php echo base_url();?>admin_control/ajax_data',
data: form_data,
dataType:"json", //to parse string into JSON object,
success: function(data){
if(data){
var len = data.length;
alert(len);
var txt = "";
if(len > 0){
for(var i=0;i<len;i++){
if(data[i].agent_name && data[i].type){
txt += $('#table').append('<tr class="item-row"><td><input type="hidden" id="add_type" name="add_type[]" value="super">Super</td><td><input type="hidden" id="add_amount" name="add_amount[]" value="10">745</td><td><input type="hidden" class="add_quantity" id="add_quantity" name="add_quantity[]" value="10">10</td><td name="add_amount" id="add_amount">100</td><td><input type="checkbox" class="add_checkbox" name="layout" id="add_checkbox" value="1" checked></td></tr>');
}
}
if(txt != ""){
$("#table").append(txt).removeClass("hidden");
}
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('error: ' + textStatus + ': ' + errorThrown);
}
});
return false;
</script>
Here I want to pass the values of form_data in to the table I had written and how can we pass that and did it compulsory to use the url in ajax while using this am getting an error like error: parsererror: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data.
Here is my controller
public function ajax_data()
{
$array = array("agent_name" => "admin","number"=>"785","type"=>"super","quantity"=>"10");
$data['json'] = $array;
echo json_encode($data);
}
The Ajax post will call the controller method for post values. The ajax code usually correct but you have not defined url.
url: '',
Firstly define a method (ex: HomeController) then set ajax url parameter like
url: '#Url.Action("Save","Home")' or url: 'Save/Home'
[HttpPost]
public JsonResult Save(string agent_name, string type , int number,int quantity)
{
// return json
}
Note :
The data types you send from the form with the method types must be
the same.
Well, just to give you some hints to work on: The Ajax call could look like this:
$.ajax({
type: 'POST',
url: 'echodata.php',
data: form_data,
dataType:"json",
success: function(data){
$('#table').append('<tr><td>'+data.agent_name+'</td>' // + more columns ...
+'</tr>');}
);
The php script should really be something that processes the incoming information (passed as the $_POST array) into some other data that will ultimately be echoed as JSON string.
This is just a trivial version of echodata.php for testing:
<?php
echo json_encode($_POST);
?>
EDIT:
While you have fixed your URL attribute and have added a "controller" on the server your Ajax success function still expects something it will not get. Your PHP script delivers a JSON string that will be parsed into as a JavaScript object and not an array. The object will not have the length property your success function tries to use. Instead you should be looking for the json property.
So, there is no point for the for loop, instead you can use data.json.agent_name, data.json.number and data.json.type (etc.) properties directly. Your current .append() also only adds a static string to your table. This should of course be changed to use the freshly received values.

Calling value in PHP from a jQuery serialized array doesn't work

I have an ajax call that sends data from serialized checkboxes (among other) to a php file:
$("#button1").click(function(e) {
var category_id = {};
category_id['datumanf'] = $("#datumanf").datepicker().val();
category_id['checkboxvalue'] = $('.checkboxes').serialize();
console.log($('.checkboxes').serialize());
$.ajax({
type: "POST",
url: "allgemein.php
dataType: "html",
data: category_id,
success: function(response) {
$("#resulttable").show().html(response);
}
});
});
The html checkboxes look like this (they contain bits of SQL):
<input type="checkbox" class="checkboxes" name="checkb[]" value="SYSTEM LIKE '%system%'">
When I try to call their name via POST in php like
echo $_POST['checkb'];
it's always empty. I tried variations like $_POST['checkb[1]']; or $_POST['checkb[]']; it's always empty.
However when i call the whole array echo $_POST['checkboxvalues']; I get the same as console.log.
I need the values singularily however. How can I do that?

Return multiple values from jquery ajax call to php

I am trying to return multiple values from a php process.
Here is the jQuery function
$.ajax({
url: 'shopping_cart_add.php',
data: 'item_id='+subscription_id+'&item_name='+subscription_name+'&item_price='+subscription_price,
type: 'POST',
dataType: 'json',
success: function(response, statusText) {
var qty = response.item_quantity;
$("#shopping-cart-quantity").html(qty);
}
});
The above seems to work except I can't retrieve the specific field values from the returned JSON.
When I try this...
var qty = response.item_quantity;
$("#shopping-cart-quantity").html(qty);
Nothing happens.
If I change...
$("#shopping-cart-quantity").html(qty);
to
$("#shopping-cart-quantity").html(response);
I get the following...
{ 'account_id': '1', 'item_id' : 'cce3d2a017f6f1870ce8480a32506bed', 'item_name' : 'CE', 'item_quantity' : '1', 'item_price' : '1' }
Please make sure that you are using json_encode() for returning result array
/*** PHP ***/
echo json_encode($resultArr); exit ;
And in AJAX try with eval() to access response text value .
/*** AJAX ***/
var qty = eval(response.item_quantity);

Update mysql data on textarea click off

I have this code below:
<?php
$stmt = $pdo_conn->prepare("SELECT * from controldata where field = :field ");
$stmt->execute(array(':field' => 'notice_board'));
$result = $stmt->fetch();
?>
<textarea id="notice_board_textarea" data-id="notice_board" rows="8"><?php echo stripslashes(strip_tags($result["value"])); ?></textarea>
<script type="text/javascript">
$('#notice_board_textarea').on('blur', function () { // don't forget # to select by id
var id = $(this).data('id'); // Get the id-data-attribute
var val = $(this).val();
$.ajax({
type: "POST",
url: "dashboard.php?update_notice_board=yes",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id // Id of the item stored on the data-id
},
});
});
</script>
which selects data from a MySQL database and shows it in a textarea
then then JS code updates it by POSTing the data to another page but without refreshing the page or clicking a save/submit button
on dashboard.php i have this code:
if($_GET["update_notice_board"] == 'yes')
{
$stmt = $pdo_conn->prepare("UPDATE controldata SET value = :value WHERE field = :field ");
$stmt->execute(array(':value' => $_POST["notes"], ':field' => 'notice_board'));
}
but its not updating the data
am i doing anything wrong?
Wrong:
if ($_POST["update_notice_board"] == 'yes') {
Right:
if ($_GET['update_notice_board'] == 'yes') {
When you append something straight to the URL, it is ALWAYS GET:
url: "dashboard.php?update_notice_board=yes",
Updated answer:
Based on what's written in the comments below, my guess is, it is a server side issue, beyond what is shared here. Perhaps dashboard.php is part of a framework that empty the super globals or perhaps the request is not going directly to dashboard.php
Old suggestions:
When you use type: "POST" you wont find the parameters in the $_GET variable. (U: Actually you probably would find it in $_GET, but in my opinion it's cleaner to put all vars in either $_GET or $_POST, although there may be semantic arguments to prefer the splitting).
Add your parameter to the data object of your ajax call and read it from the $_POST variable instead:
$.ajax({
type: "POST",
url: "dashboard.php",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id, // Id of the item stored on the data-id
update_notice_board:"yes"
},
success: function(reply) {
alert(reply);
},
error:function(jqXHR, textStatus, errorThrown ) {
alert(textStatus);
}
});
and
if($_POST["update_notice_board"] == 'yes')
(You may also look in $_REQUEST if you don't care whether the request is get or post.)
Compare the documentation entries:
http://www.php.net/manual/en/reserved.variables.get.php
http://www.php.net/manual/en/reserved.variables.post.php
http://www.php.net/manual/en/reserved.variables.request.php
Working client-side example:
http://jsfiddle.net/kLUyx/

How to access Javascript array in PHP file and printing array values in Javascript

I have first PHP file where I have form and it's action is directing me to next php file. The code snippet is as below:
<form name="drugForm" action="drug_form2.php" onsubmit="return validateForm()" method="post">
In function validateForm (javascript) I am checking whether text area is filled and at least a checkbox is checked. And I am creating array, here in javascript, to get checkbox values. The js code is below:
function validateForm()
{
var x=document.forms["drugForm"]["dname"].value;
var y=document.drugForm.drug;
var y_array = [];
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
else if (Boolean(x))
{
for(k=0;k<y.length;k++)
{
if(y[k].checked)
{
var arr_val = y[k].value;
y_array.push(arr_val);
//alert(arr_val);
}
}
for(m=0;m<y.length;m++)
{
if(y[m].checked)
{
for(l=0;l<y_array.length;l++)
{
alert("This is array " + y_array[l]);
}
dataString = y_array ; // array?
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "drug_form2.php",
data: {data : jsonString},
cache: false,
success: function(){
alert("OK");
}
});
//alert("The array length is " + y_array.length);
//return true;
}
}
alert("Check one checkbox at least");
return false;
}
}
Here, from this function I want send array to php, for this reason I referred following link but it didn't work:
Send array with Ajax to PHP script
Now, my queries are as following:
Why am I not able to print array value inside second for loop? and
How can I access javascript array in PHP file?
I have PHP file too to check whether array values are printing properly, but it is not giving those values. Below is second PHP file to get javascript array in PHP file:
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
$data = json_decode(stripslashes($_POST['data']));
// here i would like use foreach:
foreach($data as $d){
echo $d;
}
echo "Its in form2 and working fine";
?>
</body>
</html>
Am I including ajax function at right place?
You can just append each item in your javascript array into a string seperated by a unique character/s. As for my experience, it's easier than passing it as an array. Then pass the string to PHP.
In your PHP code, use the string method explode to create an array out of the string. Then go with the rest of your code logic.
if javascript array is simple array,than change it to csv and passed it has string.
In php serverside just explode that string you will again get array in php.
javscript
$.ajax({
type: "POST",
url: "drug_form2.php",
data: {data : y_array.join(',')},
cache: false,
success: function(){
alert("OK");
}
});
php
$array= explode(",", $_POST['data']);

Categories

Resources