How to pass Array from Javascript to PHP - php

I have a function which saves an array each time the button is clicked to localStorage.The button will be clicked multiple times and I need to put this Array list into PHP somehow which is on another page from this file.
Thanks
a.js
(this function listens onLoad of the page)
function doFirst(){
var button = document.getElementById("button");
button.addEventListener("click", save, false);
var buttons = document.getElementById("clear");
buttons.addEventListener("click", clear, false);
var buttonss = document.getElementById("submittodb");
buttonss.addEventListener("click", toPHP, false);
$.ajax({
method: 'post',
dataType: 'json',
url: 'edit.php',
data: { items: oldItems }, //NOTE THIS LINE, it's QUITE important
success: function() {//some code to handle successful upload, if needed
}
});
}
function save(){
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];
var newItem = {
'num': document.getElementById("num").value,
'methv': document.getElementById("methv").value,
'q1': document.getElementById("q1").value,
'q2':document.getElementById("q2").value,
'q3':document.getElementById("q3").value,
'q4':document.getElementById("q4").value,
'comm':document.getElementById("comm").value,
};
oldItems.push(newItem);
localStorage.setItem('itemsArray', JSON.stringify(oldItems));}
edit.php
$parsed_array = json_decode($_POST['items']);
and i get the error: Notice: Undefined index: items in /home/project/edit.php on line 9

In order to pass this array to PHP you need to:
JSon-encode it
Make an AJAX or POST request to PHP
Parse the passed array into PHP array
If you're using jQuery (if you're not you should start - it is really handy tool) steps (1) and (2) is as simple as
$.ajax({
method: 'post',
dataType: 'json',
url: 'the URL of PHP page that will handle the request',
data: { items: oldItems }, //NOTE THIS LINE, it's QUITE important
success: function() {//some code to handle successful upload, if needed
}
});
In PHP you can parse the passed array with just
$parsed_array = json_decode($_POST['items']);
There is a direct connection between { items: oldItems } and $_POST['items']. The name of variable you give to the parameter in javascript call will be the name of key in $_POST array where it ends up. So if you just use data: oldItems in javascript you'll have all your entities scattered around the $_POST array.
More on $.ajax, and json_decode for reference.

You can create an AJAX function (use jQuery) and send the JSON data to the server and then manage it using a PHP function/method.
Basically, you need to send the data from the client (browser) back to the server where the database hosted.

Call JSON.stringify(oldItems); to create the json string
Do a Do a POST request using AJAX.
Probably the simplest way is using jQuery:
$.post('http://server.com/url.php', { items: JSON.stringify(oldItems) }, function(response) {
// it worked.
});

Related

Ajax call to PHP action/function with array as data (in wordpress)

I'm trying to push an array from jquery to a php function and I'm out of options to make it work. I've tried multiple options; $_request, $_post, with JSON.stringify, without JSON.stringify, ...
But I keep getting 'null'; can't figure out the right combination. Someone who's willing to explain me why it's not working and how to fix?
JQuery code:
var userIDs = [];
$( "tr.user-row" ).each(function() {
var userID = $(this).attr("data-userid");
userIDs.push(userID);
});
var jsonIDs = JSON.stringify(userIDs);
$.ajax({
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'built_ranking', // This is our PHP function below
'data' : {data:jsonIDs},
},
dataType:"json",
success:function(data){
// This outputs the result of the ajax request (The Callback)
//$("tr[data-userid='"+userID+"'] td.punten").html(data.punten);
//$("tr[data-userid='"+userID+"'] td.afstand").html(data.afstand);
console.log(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
PHP code:
function built_ranking(){
if ( isset($_REQUEST) ) {
$data = json_decode(stripslashes($_REQUEST['data']));
foreach($data as $d){
echo $d;
}
print json_encode($data);
//$testResult = array("points"=>"test", "afstand"=>"test");
//print json_encode($testResult);
}
// Always die in functions echoing AJAX content
die();
}
add_action( 'wp_ajax_built_ranking', 'built_ranking' );
If I print the $testResult it returns the array and I can use the data back in jquery, so the function is called.
I've based the code on Send array with Ajax to PHP script
I've multiple ajax calls with $_request instead of $_post and they are working fine. But maybe they can't handle arrays? I've no idea... ^^
What I learned from this question and the help I got: don't guess, debug. try to find ways to see what is posted, what is received, ...
You can read how to 'debug' in the comments of the original question. Useful for starters as me ;)
Working code:
JQuery
var jsonIDs = JSON.stringify(userIDs);
$.ajax({
type: 'POST',
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'built_ranking', // This is our PHP function below
'data' : jsonIDs,
},
dataType:"json",
success:function(data){
// This outputs the result of the ajax request (The Callback)
//$("tr[data-userid='"+userID+"'] td.punten").html(data.punten);
//$("tr[data-userid='"+userID+"'] td.afstand").html(data.afstand);
console.log(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
PHP
function built_ranking(){
if ( isset($_POST) ) {
$data = json_decode(stripslashes($_POST['data']));
print json_encode($data);
//$testResult = array("points"=>"test", "afstand"=>"test");
//print json_encode($testResult);
}
// Always die in functions echoing AJAX content
die();
}
add_action( 'wp_ajax_built_ranking', 'built_ranking' );

Use the autocomplete event in the succes of my ajax

I would like to use an autocompletion in my application. I'm trying to use the jquery UI completion but nothing happens. I made an ajax to get all columns with a specific variable written by the user. The query is working, I have my array with all my columns back from the server. With this query reponse, I tried to do the jquery autocompletion in the success ajax but as I said nothing is happening.
Do you have an idea?
function autoCompleteRegate(){
$("#code_regate").keyup(function() {
// AJAX de l'auto-complete
var source = '/gestion/gestDepot/ajaxautocompleteregate';
var codeRegate = $("#code_regate").val();
$.ajax({
type : "POST",
url : source,
async : false,
dataType : 'json',
data : {
'codeRegate' : codeRegate
},
success : function(response) {
var availableTags = response;
$("#code_regate").autocomplete({
source: availableTags
});
}
});
});
public function ajaxautocompleteregateAction()
{
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$params = $this->_getAllParams();
$codeRegate = $params['codeRegate'];
$oDepotService = new Services_Depot();
$response = $oDepotService->searchCodeRegate($codeRegate);
echo json_encode($response);
}
Network query - form
Exemple of nothing happening
The answer from the server
You have to directly pass the cd_regate array instead of a multidimensional array. One workaround is you could process the json output on the backend side :
public function ajaxautocompleteregateAction()
{
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$params = $this->_getAllParams();
$codeRegate = $params['codeRegate'];
$oDepotService = new Services_Depot();
$response = $oDepotService->searchCodeRegate($codeRegate);
$json = [];
foreach ($response as $key => $value) {
array_push($json, $value->cd_regate); // the output will be "[774970, 774690, 774700,... ]"
}
echo json_encode($json);
}
I would suggest the following for your JavaScript:
$("#code_regate").autocomplete({
source: function(request, response){
$.ajax({
type : "POST",
url : '/gestion/gestDepot/ajaxautocompleteregate',
async : false,
dataType : 'json',
data : {
'codeRegate' : request.term
},
success : function(data) {
response(data);
}
});
}
});
This uses a function as a Source. From the API:
Function: The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete, including JSONP. The callback gets two arguments:
A request object, with a single term property, which refers to the value currently in the text input. For example, if the user enters "new yo" in a city field, the Autocomplete term will equal "new yo".
A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.
When filtering data locally, you can make use of the built-in $.ui.autocomplete.escapeRegex function. It'll take a single string argument and escape all regex characters, making the result safe to pass to new RegExp().
When 1 or more letters are entered into the text field, this will be passed to the function under request.term and you can POST that to your script via AJAX. When you get the result data, it must be in an Array or an Object with the right format.

Multiple Ajax call with same JSON data key calling one php file

I am trying to validate list of dynamic text fields.
Validation needs an AJAX call to interact with server.
At the backend I have written just one php file that reads the input request data and performs operation. Below is the example.
abc.js
row_count = 6
for (i = 1; i <=row_count; i++) {
id = "#val"+i.toString() ;
$(id).change(function(){
input_val="random";
$.ajax({
url:"url.php",
type:post,
async:true,
dataType: 'json',
data : {temp:input_val},
success:function(result){},
error: function (request, status, error) {}
});
});
}
url.php
<?php
$random_val = $_POST['temp'];
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
if ($flag == 0){
echo json_encode(array("status"=>'Fail'));
}
else{
echo json_encode(array("status"=>'Success'));
}
?>
It works fine when the row_count = 1 (Just one text field) but fails when the input is more than 1.
When the count is more than 1, the php script is not able to read the request data(The key in JSON data "temp"). it is blank in that case.
Any lead or help should be appreciated.
Thanks
Your javascript bit needs some adjusting, because you do not need to define an ajax for every single element. Use events based on a class. Also, since input behave differently than select, you should setup two different event class handlers.
function validateAjax ( element ) {
var input_val = element.val();// get the value of the element firing this off
$.ajax({
url: "url.php",
type: 'post',
async: true,
dataType: 'json',
data : { temp: input_val },
success: function(result) {
// check your result.status here
},
error: function (request, status, error) { }
});
}
$(".validate_change").on("change",function() { // for selects
validateAjax( $(this) );
});
$(".validate_input").on("input",function() { // for text inputs
validateAjax( $(this) );
});
And for your select or input you add that appropriate class.
<select class="validate_change" name="whatever"><options/></select>
<input class="validate_input" name="blah">
PS
I really worry about this code you have:
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
So, you are just executing anything that is coming in from a webpage POST var??? Please say this website will be under trusted high security access, and only people using it are trusted authenticated users :-)

Get JQUERY function return in PHP

I want to know if I can get the return of a JQUERY function, in PHP ?
I have this following jquery function, returning an array and I want to get this array in my PHP, in order to send it to process the data
function getItemMetaList() {
var itemMetaArray = [];
$('.frm_pro_form input, .frm_pro_form select, .frm_pro_form textarea').each(function(cpt){
if($(this).attr('type') != 'hidden' && ($(this).attr("type") != "submit")) {
console.log(cpt);
console.log($(this).attr("name"));
itemMetaArray.push($(this).attr("name"));
}
});
return itemMetaArray;
}
Thanks in advance
function getItemMetaList() {
var itemMetaArray = [];
$('.frm_pro_form input, .frm_pro_form select, .frm_pro_form textarea').each(function(cpt){
if($(this).attr('type') != 'hidden' && ($(this).attr("type") != "submit")) {
itemMetaArray.push($(this).attr("name"));
}
});
$.ajax({
method: "POST",
url: "some.php",
//data: { array: itemMetaArray}
data: JSON.stringify({ array: itemMetaArray})
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
you can send data by this way in a php file like documented here: ajax jquery
The Ajax request returns data for JavaScript in the page loaded in your browser. The browser does not display the data automatically. The answer is captured by .done() in MacBook's example. You can put JavaScript in the done () method to display the data returned. If you wish the page to reload in your browser, Ajax is not the good way. In JavaScript, use form.submit instead. Then you can have your PHP code read the submitted data and generate a new html page and have this displayed by the browser.

arrays in $.ajax jquery and then sends it to a php page

jQuery(document).ready(function(){
// Set the data text
var dataText = "
{
name: 'John',
time: '2pm'
}";
alert(dataText);
// Create the AJAX request
$.ajax({
type: "POST", // Using the POST method
url: "/ajax/analytics/push", // The file to call
data: dataText, // Our data to pass
success: function() { // What to do on success
alert("Data Loaded: " + dataText);
}
});
});
</script>
hello im still learning ajax. how can we push a array of $_POST?
1.im trying to do something like
var dataText['name'] = 'Jhon';
var dataText['time] = '2pm';
then somehow turns it into
$_POST['name'] = 'Jhon';
$_POST['time'] = '2pm';
then send it to the url..
2.is there a way to debug this ? what im doing now is im writing
# somehow doesnt work becouse its not auto refresh when the ajax sends a post
var_dump($_POST);
# ok heres how i debug it right now.
ob_start();
// write content
$content = $_POST;
ob_end_clean();
file_put_contents('CACHE',$content);
in to a file, i hope there is a better solution for this..
Thankyou for looking in.
Adam Ramadhan
I'm not entirely sure what you're doing. You seem to be building JSON manually (and not doing it correctly) and then passing that (in the JSON-serialised string form) to your file. You then seem to expect it to be parsed by PHP automatically.
It would be better to send it as key-value pairs. You can let jQuery do this for you if you pass in an object. This won't look much different to your existing code:
var dataText =
{
name: 'John',
time: '2pm'
};
Note that I have removed the double quotes. This is primarily because it is illegal to have a JS string covering more than one line without escaping the line breaks. It is also because you want the object to pass into your $.ajax call.
These should be available as $_POST['name'] and $_POST['time'] now.
file_put_contents('CACHE',serialize($content));
or
foreach($_POST as $k => $v) $content .= $k .'='.$v;
jQuery(document).ready(function(){
// Set the data text
var dataText =
{
name: 'John',
time: '2pm'
};
alert(dataText);
// Create the AJAX request
$.ajax({
type: "POST", // Using the POST method
url: "/ajax/analytics/push", // The file to call
data: dataText, // Our data to pass
success: function() { // What to do on success
alert("Data Loaded: " + dataText);
}
});
});
# ok heres how i debug it right now.
ob_start();
# somehow doesnt work becouse its not auto refresh when the ajax sends a post
var_dump($_POST);
$content = ob_get_contents();
ob_end_clean();
file_put_contents('CACHE',$content);

Categories