I am passing a json in my ajax request but it is just returning 10 every time, why??
whay my array in not getting passed??
Here is my code:
jQuery(document).ready(function($){
$('#list-3 .ajaxcall').click(function(){
$.ajax({
type : "GET",
url : ajaxurl,
dataType: 'json',
contentType: "application/json; charset=utf-8",
data : {
gpl_args : JSON.stringify({"cat":"26","posts_per_page":"4","paged":1}),
gpl_layout : {"show_thumb":"1","columns":"4","thumb_height":"85","thumb_width":"85","title_link":"1","content_excerpt":"50","posts_per_page":"4"}
},
success : function(response) {
// The server has finished executing PHP and has returned something,
// so display it!
$("#list-3").append(response);
}
});
});
});
and:
$args = isset($_REQUEST['gpl_args']);
//$args = json_encode(isset($_REQUEST['gpl_args']));
print_r($args)
Update:
my data inside ajax:
data : { gpl_args : JSON.stringify(<?php echo json_encode($args); ?>),
JSON.stringify(gpl_layout : <?php echo json_encode($layout); ?>)},
Simple fix. You have to DE-code the json, not EN-code it.
$args = isset($_REQUEST['gpl_args']) ? $_REQUEST['gpl_args'] : null;
$args = json_decode(stripslashes($args));
print_r($args)
See your php script:
$args = isset($_REQUEST['gpl_args']);
//$args = json_encode(isset($_REQUEST['gpl_args']));
// $args is false(Boolean type), But not json
print_r($args); // print_r(false); is show nothing!!
right way:
$json_array[] = isset($_REQUEST['gpl_args']) ? $_REQUEST['gpl_args'] : false;
echo json_encode($json_array); // will show json string
Aren't you printing the boolean result of isset() instead of the actual args?
Related
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' );
I want to send an array to PHP (POST method) using jQuery.
This is my code to send a POST request:
$.post("insert.php", {
// Arrays
customerID: customer,
actionID: action
})
This is my PHP code to read the POST data:
$variable = $_POST['customerID']; // I know this is vulnerable to SQLi
If I try to read the array passed with $.post, I only get the first element.
If I inspect the POST data with Fiddler, I see that the web server answers with "500 status code".
How can I get the complete array in PHP?
Thanks for your help.
To send data from JS to PHP you can use $.ajax :
1/ Use "POST" as type, dataType is what kind of data you want to receive as php response, the url is your php file and in data just send what you want.
JS:
var array = {
'customerID': customer,
'actionID' : action
};
$.ajax({
type: "POST",
dataType: "json",
url: "insert.php",
data:
{
"data" : array
},
success: function (response) {
// Do something if it works
},
error: function(x,e,t){
// Do something if it doesn't works
}
});
PHP:
<?php
$result['message'] = "";
$result['type'] = "";
$array = $_POST['data']; // your array
// Now you can use your array in php, for example : $array['customerID'] is equal to 'customer';
// now do what you want with your array and send back some JSON data in your JS if all is ok, for example :
$result['message'] = "All is ok !";
$result['type'] = "success";
echo json_encode($result);
Is it what you are looking for?
I have this jQuery code that adds to an array inside an $each loop:
new_edit = {};
new_edit['file_id'] = $file_id;
new_edit['file_realname'] = $new_file_realname;
new_edit['file_folder'] = $new_file_folder;
new_file_edits.push(JSON.stringify(new_edit));
jQuery new_file_edits array output
{"file_id":"1857","file_realname":"dddd[1].mp4","file_folder":"/"},
{"file_id":"1856","file_realname":"aaaa[1].jpg","file_folder":"/"},
{"file_id":"1855","file_realname":"ssss[1].jpg","file_folder":"/"}
and im trying to post it to call.php like this:
$.ajax({
type: "POST",
url: "/call.php",
data: "edit_files="+ arrayVarHere,
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(msg){
alert(+msg);
}
});
In the PHP file call.php i have this code:
if(isset($_POST['edit_files'])){
$edit_array = $_POST['edit_files'];
$file_array = array();
foreach($edit_array as $key => $value){
$file_array[$key] = $value;
}
print_r($file_array);
die();
}
but i get this error and i cant figure out how to fix it, been googling it for a while now...
error:
Warning: Invalid argument supplied for foreach() in /home2/dddd/public_html/call.php on line 237
Line 237: foreach($edit_array as $key => $value){
Any help is much appreciated!
-Morten
EDIT 1:
I changed $edit_array = $_POST['edit_files']; to $edit_array = array($_POST['edit_files']);
And now it outputs:
{"file_id":"1857","file_realname":"dddd[1].mp4","file_folder":"/"},
{"file_id":"1856","file_realname":"aaaa[1].jpg","file_folder":"/"},
{"file_id":"1855","file_realname":"ssss[1].jpg","file_folder":"/"}
How do i go from here with the foreach($edit_array as $key => $value){ part?
Edit 2:
i build my arrayVarHere like this:
$.each( $selected_files_array, function( index, value ){
//i get $file_id, $new_file_realname and $new_file_folder with some code here
new_edit = {};
new_edit['file_id'] = $file_id;
new_edit['file_realname'] = $new_file_realname;
new_edit['file_folder'] = $new_file_folder;
arrayVarHere.push(JSON.stringify(new_edit));
});
change your code like this:
data: "edit_files="+ arrayVarHere,
call json data by json_decode in call.php
if(isset($_POST['edit_files'])){
$edit_array = json_decode($_POST['edit_files'],true); //return array
$file_array = array();
foreach($edit_array as $key => $value){
$file_array[$key] = $value;
}
print_r($file_array);
die();
}
in your ajax alert should be
success: function(msg){
alert(msg); //remove plus sign ,this can output `NaN`
}
check edit_array is array print_r($edit_array);
check contentType is used form data then correct otherwise used json type
if form data then check data: edit_files[]: arrayVarHere,
It returns this array
Array ( [0] => [{"file_id":"1857","file_realname":"aq53pop_460sv[1].mp4","file_folder":"/"},{"file_id":"1859","file_realname":"aKqbD8Q_460sv[1].mp4","file_folder":"/"},{"file_id":"1856","file_realname":"aDopymK_700b[1].jpg","file_folder":"/"}] )
how can i loop the array and access file_id value etc?
The way you are passing Data to PHP may not be that ideal. Here is what might get you started:
PHP: call.php
<?php
$data0 = isset($_POST['data_0']) ? json_decode($_POST['data_0'], true) : null;
$data1 = isset($_POST['data_1']) ? json_decode($_POST['data_1'], true) : null;
$data2 = isset($_POST['data_2']) ? json_decode($_POST['data_2'], true) : null;
$arrData = array(
'data0' => $data0,
'data1' => $data1,
'data2' => $data2,
);
foreach($arrData as $dataKey=>$dataObject){
$tempFileID = $dataObject->file_id;
$tempFileName = $dataObject->file_realname;
$tempFileFolder = $dataObject->file_folder;
// DO SOMETHING WITH THESE DATA AND THEN BUILD UP A RESPONSE FOR AJAX + SEND IT...
// UNCOMMENT TO SEE THE DATA IN YOUR NETWORKS CONSOLE BUT
// IF YOU DO THIS (SINCE YOU EXPECT JSON RESPONSE) YOUR AJAX WILL RESPOND WITH AN ERROR...
// var_dump($dataObject);
}
// RESPOND WITH THE SAME DATA YOU RECEIVED FROM AJAX: JUST FOR TESTING PURPOSES...
die( json_encode($arrData));
?>
JAVASCRIPT: BUILDING THE DATA FOR PHP
<script type="text/javascript">
var dataForPHP = {};
var iCount = 0;
$.each( $selected_files_array, function( index, value ){
var keyName = "data_" + iCount;
new_edit = {};
new_edit['file_id'] = $file_id;
new_edit['file_realname'] = $new_file_realname;
new_edit['file_folder'] = $new_file_folder;
dataForPHP[keyName] = new_edit;
iCount++;
});
</script>
JAVASCRIPT: AJAX REQUEST
<script type="text/javascript">
$.ajax({
type : "POST",
url : "/call.php",
datatype : "JSON",
data : dataForPHP,
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(msg){
if(msg){
alert("Ajax Succeeded");
console.log(msg);
}
}
});
</script>
I use jquery to call two url in file indexFunctions.php but the response of server is empty i dont know why please help there is my code
$("#start_peering").submit(function(event){
$("#wait").html('<img src="ajax-loader.gif">');
event.preventDefault();
$.ajax({
url : 'indexFunctions.php',
type : 'POST',
data : {peering:true},
success : function(data){
$("#StbStatus").html(data);
$.ajax({
url : 'indexFunctions.php',
type : 'POST',
data : {test_params:true},
success : function(data){
$("#results").html(data);
$("#wait").html('');
}
});
}
});
});
File indexFunctions.php
$rpi="http://192.168.1.15";
if (isset($_POST['peering']) && isset($_POST['test_params']))
{
$url = $rpi."/peering.php?askSTB=true";
$response = proxy::get($url);
echo $response;
$url = $rpi."/installUSBKeyOnStb.php";
$response = proxy::get($url);
echo $response;
}
?>
Thank you in advance.
You seem to be sending two request but checking if both are set at the same time.
if (isset($_POST['peering']) && isset($_POST['test_params']))
You should check for either or not both.
Try changing it to:
if (isset($_POST['peering']) || isset($_POST['test_params']))
You used AND && instead of OR ||
I have an ajax code which passes data to php and then retrieves data from php...
function updateDatabase(syncData){
$.ajax({
type : 'POST',
async: false,
url : 'php/syncData.php',
dataType : 'json',
data: {myData : syncData}, //i even used this "mydata"+syncData
success : function(result){
res = result;
},
error : function() {
res = false;
}
});
return res;
}
And here's my php code...
<?php
include("database.php");
if(isset($_GET['myData'])){
$data = $_GET['myData'];
$insert = "INSERT INTO `mydata` VALUES (NULL,'$data')";
mysql_query($insert);
$data = mysql_insert_id();
echo json_encode($data);
}
?>
Here's javascript function that pass/calls ajax...
<script>
var theData = "blahblah";
var alertData = updateDatabase(theData);
alert(alertData);
</script>
the problem is that when i use htmt/text as data type it alerts empty/blank output, but when i used json as data type it alerts false where i conclude it went to error function not to success... anyone knows what's the proper way to do this? or maybe i'm just missing something? Thanks!
Well, you're posting the data using jQuery, but you're looking for a $_GET value in the PHP. Fix that and see if it changes anything.
Edit: It should look like this:
...
if(isset($_POST['myData'])){
$data = $_POST['myData'];
...
Try to set content type in your PHP file:
header( 'Content-Type: application/json' );
Then echo your data:
echo json_encode( $data );
Then exit script:
exit;
Hope it helps!