Passing array from JavaScript to PHP without losing code functionality - javascript

Using this piece of code I can list all the file URLs inside the Folder_A and Folder_B and Folder_C :
<?php
function getDirContents($directories, &$results = array()){
$length = count($directories);
for ($i = 0; $i < $length; $i++) {
$files = array_diff(scandir($directories[$i]), array('..', '.'));;
foreach($files as $key => $value){
$path = $directories[$i].DIRECTORY_SEPARATOR.$value;
if(is_dir($path)) {
getDirContents($path, $results);
} else {
$directory_path = basename($_SERVER['REQUEST_URI']);
$results[] = 'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
}
}
}
return $results;
}
$directories = array("Folder_A", "Folder_B","Folder_C");
echo json_encode(getDirContents($directories));
And using the JavaScript code below we can log them in the console (And have access to them via javascript):
$(document).ready( function() {
$.ajax({
type: 'POST',
url: '../test.php',
data: 'id=testdata',
dataType: 'json',
cache: false,
success: function(result) {
console.log(result);
},
});
});
I just want one simple thing that I can't find a solution by myself:
How can I define the Folders inside javascript instead of having them in PHP?
I mean instead of having this inside PHP code:
$directories = array("Folder_A", "Folder_B","Folder_C");
I want to have this in Javascript:
let directories = [ "Folder_A", "Folder_B","Folder_C"];
And return the same functionality.

Pass the directories as part of the data: parameter.
$(document).ready( function() {
let directories = [ "Folder_A", "Folder_B","Folder_C"];
$.ajax({
type: 'POST',
url: '../test.php',
data: {id: "testdata", directories: directories},
dataType: 'json',
success: function(result) {
console.log(result);
},
});
});
Then in PHP you can use $_POST['directories'] to get the array:
echo json_encode(getDirContents($_POST['directories']));

Related

How to use jQuery to get variable from PHP

I am trying to get data from MySQL using ajax and jQuery. Right now, the only thing being returned is "0". Here is my PHP function:
function dallas_db_facebook_make_post () {
global $wpdb;
$query = "SELECT * FROM wp_dallas_facebook WHERE time > NOW() ORDER BY time LIMIT 1";
$results = $wpdb->get_results($query, ARRAY_A);
foreach($results as $result) {
$fbpost = $result['text'];
}
}
Here is my jQuery function:
function send_fb_post() {
jQuery.ajax({
type: "GET",
url: my_ajax.ajaxurl,
data: {
'action': 'dallas_db_facebook_make_post'
},
beforeSend: function() {
},
success: function(data){
console.log(data);
},
error: function(){
},
});
};
You are not getting anything, because you are not printing/echoing anything.
What happens if you try
foreach($results as $result) {
echo $fbpost = $result['text'];
}
You code is not working because you are not print anything on server side. so you can small change in your code like below.
jsonencode is use to return an array of data.
function dallas_db_facebook_make_post () {
global $wpdb;
$query = "SELECT * FROM wp_dallas_facebook WHERE time > NOW() ORDER BY time LIMIT 1";
$results = $wpdb->get_results($query, ARRAY_A);
$fbpost = array();
foreach($results as $result) {
$fbpost = $result['text'];
}
echo json_encode($fbpost);
exit;
}
in response you json_encodeed data. You can decode and use this data using below function in response callback.
function send_fb_post() {
jQuery.ajax({
type: "GET",
url: my_ajax.ajaxurl,
data: {
'action': 'dallas_db_facebook_make_post'
},
beforeSend: function() {
},
success: function(data){
console.log(jQuery.parseJSON( data ));
},
error: function(){
},
});
};

cannot receive json from server through php

i cannot get the json from php on sever
the javascript code is:
$.ajax({
type: "POST",
url: "doingSQL.php",
data: label,
success: function(result) {
$("#p").html("All my book: <br>"+ result);
console.log(result);
},
dataType: "json",
error: function(xhr){
console.log("error");
}
});
the job of doingSQL.php is selecting bookName from SQL database and convert the data to json. it look like this:
/* the server connecting code is omitted */
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$label = $_POST["label"];
}
$sql = "SELECT * FROM book WHERE ower = '". $label."'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$Arr = array("id" => $row["book_id"],
"bookName" => $row["bookName"]);
$bookDetail[] = array( "book".$i => $Arr);
}}
}
mysqli_close($conn);
$json = array("mybook" => $bookDetail);
echo json_encode($json);// return json
but the result i got in the html console is "[ ]" or array[0].
the json is valid json format, it is look like:
{
"mybook":[
{
"book0":{
"id":"0",
"bookName":"bookA"
}
},
{
"book1":{
"id":"1",
"bookName":"bookB"
}
}
]
}
however, if the code is outside the SQL connection in php. the json returning will success.
it is look like:
/* the server connecting code is omitted */
mysqli_close($conn);
// if outside the SQL connection
$ArrA = array("id" => "0", "bookName" => "bookA");
$ArrB = array("id" => "1", "bookName" => "bookB");
$bookDetail[] = array( "book0" => $ArrA);
$bookDetail[] = array( "book0" => $ArrB);
$json = array("mybook" => $bookDetail);
echo json_encode($json);// return json success
any idea?
Just pass your ajax data as :
data: {label:label}
The data property of the ajax settings can be type of PlainObject or String or Array. For more reference see this http://api.jquery.com/jquery.ajax.
So your javascript code would be like this :
$.ajax({
type: "POST",
url: "doingSQL.php",
data: {label: label},
success: function(result) {
$("#p").html("All my book: <br>"+ result);
console.log(result);
},
dataType: "json",
error: function(xhr){
console.log("error");
}
});
You need to pass the label value in a variable. Now since on the PHP page you are using $_POST['label'], so pass the variable like this :
data: {label: label},
So your complete ajax code would look like :
$.ajax({
type: "POST",
url: "doingSQL.php",
data: {label: label}, // changed here
success: function(result) {
$("#p").html("All my book: <br>"+ result);
console.log(result);
},
dataType: "json",
error: function(xhr){
console.log("error");
}
});

Send Array of Json from Ajax to PHP

I try to send an array of json objects from the javascript to a Php code. Unable to get a response from the php file.
function getData() {
var jsonObject = [];
var genderMenu = document.getElementById("gender");
var levelMenu = document.getElementById("level");
jsonObject[0] = {
psid: document.getElementById("psid").value,
fName: document.getElementById("fname").value,
lName: document.getElementById("lname").value,
gender: genderMenu.options[genderMenu.selectedIndex].value,
};
for(var i = 1; i <= varCount; i++) {
if(document.getElementById("fName"+(i))) {
jsonObject[i] = {fName : document.getElementById("fName"+(i)).value,
lName: document.getElementById("lName"+(i)).value,
};
}
}
var jsonObjectString = JSON.stringify(jsonObject);
var result = "";
$.ajax({
type: 'POST',
url: '/inviteProcessing.php',
data: {myData: jsonObject},
success: function(response) {
if(response.success)
alert(response.message);
else
alert(response.message);
}
});
alert(jsonObject);
}
Php File has the following code
<?php
$input = $_POST['myData'];
$input_string = json_decode($input, true);
echo json_encode( array('success' => true, 'message' => $input_string) );
?>
Do u see any problem?
Prior to echoing your output, try...
header('Content-type: application/json');
echo $encodedjsonstring;
exit;
Please try below points.
First check if path of the php file is correct.
Then add below line in ajax call.
type: 'POST',
dataType: "json", //add dataType
url: '/inviteProcessing.php',
data: {myData: jsonObject},
try to put exit or die() at the end of php file

Empty $_POST when posting from jquery.ajax

I am doing some Add, Edit, and Delete for my project in school. The codes in the add module went well, in fact I've added few records. Then, here comes the Edit module, at first it was quite good, similar codes was used from the add module. But as I try and try, the post in the edit module was empty.
here's my edit codes:
$(".careersEdit").click(function () {
var careersTableSelect = encodeURIComponent($("input:radio[name=careersTableSelect]:checked").val());
if (careersTableSelect > 0) {
$(".careersEditForm_load").show();
$(".careersEditForm_error").hide();
$(".careersEditForm").hide();
var dataStringCareersEdit = 'careersTableSelect=' + careersTableSelect;
$.ajax({
type: "POST",
url: "admin/careers/process/careersEditGet.php",
data: dataStringCareersEdit,
beforeSend: function(){
alert(dataStringCareersEdit);
},
success: function () {
setTimeout("", 5000);
fetchResult();
},
error: function () {
alert("Post Error");
}
});
function fetchResult() {
$.ajax({
url: "admin/careers/process/careersEditGet.php",
type: "POST",
dataType: "json",
success: function (result) {
if (result) {
$("input#careersEditPosition").val(result['position']);
$("input#careersEditCompany").val(result['company']);
$("input#careersEditLocation").val(result['location']);
$(".careersEditForm_load").hide();
$(".careersEditForm").show();
}
},
error: function () {
alert("Fetch Error");
}
});
}
} else {
$(".careersEditForm").hide();
$(".careersEditForm_load").hide();
$(".careersEditForm_error").show();
}
});
Here's the careersEditGet.php:
<?php
include('connect.php');
error_reporting(0);
$careersTableSelect = $_POST['careersTableSelect'];
//$careersTableSelect = $careersTableSelect + 1;
//echo $careersTableSelect;
$query = "SELECT * FROM atsdatabase.admincareers WHERE refNum ='" . $careersTableSelect . "' LIMIT 0 , 30";
$runQuery = mysql_query($query);
if (!$runQuery) {
die('Could not enter data: ' . mysql_error());
}
$result = mysql_fetch_row($runQuery);
$array = array(
'position' => "" . $result[1] . "",
'company' => "" . $result[2] . "",
'location' => "" . $result[3] . "",
);
echo json_encode($array);
mysql_close($connection);
?>
Yes, the code is ugly/wrong/crap, I'm quite new to jquery stuffs, about 3-4 days. To those that will help, please do correct me. I wanna learn this jquery ajax stuff. Gracias
Maybe try passing data in more common way:
change
data: dataStringCareersEdit,
to
data: { "careersTableSelect" : careersTableSelect },
Call your ajax function once like,
$.ajax({
url: "admin/careers/process/careersEditGet.php",
type: "POST",
dataType: "json",
data: {careersTableSelect: careersTableSelect},
success: function (result) {
if (result) {
$("input#careersEditPosition").val(result.position);// json not array
$("input#careersEditCompany").val(result.company);// json not array
$("input#careersEditLocation").val(result.location);// json not array
$(".careersEditForm_load").hide();
$(".careersEditForm").show();
}
},
error: function () {
alert("Fetch Error");
}
});
Thanks guys for all the effort to answer this question, I've consulted to a friend who's a web developer, taught me how to properly use ajax in jquery. ;)
You are doing something fundamentally wrong when u are posting Data from jQuery.Ajax..
The data should be an object and the key should be the name of the server side POST variable which will be used later in the PHP ...
Example :
data : {"server_side_vriable" : "Your_data_to_Post" }
......
var dataStringCareersEdit = 'careersTableSelect=' + careersTableSelect + "&careersTableSelect=" + careersTableSelect;
$.ajax({
type: "POST",
url: "admin/careers/process/careersEditGet.php",
data: {"careersTableSelect" : dataStringCareersEdit},
beforeSend: alert(dataStringCareersEdit),
success: function () {
alert("Fetching Result");
setTimeout("", 3000);
$.ajax({
url: "admin/careers/process/careersEditGet.php",
type: "GET",
dataType: "json",
success: function (result) {
if (result) {
$("input#careersEditPosition").val(result['position']);
$("input#careersEditCompany").val(result['company']);
$("input#careersEditLocation").val(result['location']);
$(".careersEditForm_load").hide();
$(".careersEditForm").show();
}
},
error: function () {
alert("Fetch Error");
}
});
},
error: function () {
alert("Post Error");
}
});

double json response

I don't know why this double json response are not successful:
[{"first_content":"content",...}][{"second_content":"content",...}]
So i am getting the message Oops! Try Again.
if(isset($_GET['start'])) {
echo get_posts($db, $_GET['start'], $_GET['desiredPosts']);
echo get_posts1($db, $_GET['start'], $_GET['desiredPosts']);
$_SESSION['posts_start']+= $_GET['desiredPosts'];
die();
}
var start = <?php echo $_SESSION['posts_start']; ?>;
var desiredPosts = <?php echo $number_of_posts; ?>;
var loadMore = $('#load-more');
loadMore.click(function () {
loadMore.addClass('activate').text('Loading...');
$.ajax({
url: 'profile.php',
data: {
'start': start,
'desiredPosts': desiredPosts
},
type: 'get',
dataType: 'json',
cache: false,
success: function (responseJSON, responseJSON1) {
alert(responseJSON);
loadMore.text('Load More');
start += desiredPosts;
postHandler(responseJSON, responseJSON1);
},
error: function () {
loadMore.text('Oops! Try Again.');
},
complete: function () {
loadMore.removeClass('activate');
}
});
});
What is the solution to get a double json response ? With one there is no problem
"Double JSON response" as you call them is basically invalid JSON. You should have something like so:
{"first_content":"content", "second_content":"content",...}
Or as a couple of people mentioned:
[{"first_content":"content",...}, {"second_content":"content",...}]
You probably need to modify some server side code, your get_posts function could return a PHP array instead of a JSON array. Example:
function get_posts(){
$array = array('content' => 'foo', 'title' => 'bar');
return $array;
}
Then in your profile.php:
if(isset($_GET['start'])) {
$posts = get_posts($db, $_GET['start'], $_GET['desiredPosts']);
$posts1 = get_posts1($db, $_GET['start'], $_GET['desiredPosts']);
echo array($posts, $posts1);
$_SESSION['posts_start']+= $_GET['desiredPosts'];
die();
}

Categories

Resources