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");
}
});
Related
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']));
I've been looking for a week now and I can't find an answer for this situation.
I request data through jsonp.
$.ajax({
type:'GET',
dataType: "jsonp",
url: "http://www.domain.com/app/loadFeedsApp.php",
sync: true,
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
console.log(data);
}
});
In my server side i sent info like this:
$jarr = array();
$af = 0;
while( $row = mysql_fetch_array($result) )
{
$html = array("Appfeed".$af."" => array(
"cnty" => stripcslashes($row['cnty']),
"feed" => stripslashes($row['feed']),
"feedId" => stripslashes($row['feedId']),
"nickname" => stripslashes($row['nickname']),
"state" => str_replace("\r\n",'', $row['state']),
"date" => date("d/m/y", strtotime($row['date'])))
);
array_push($jarr, $html);
$af++;
}
echo $_GET['callback'] . '(' . json_encode($jarr) . ');';
And it returns the data:
jQuery21007744578921701759_1395250905357({
"Appfeed0":
{
"cnty":"MEXICO",
"feed":"text",
"feedId":"201",
"nickname":"chaparra",
"state":"Tamaulipas",
"date":"27\/02\/14"
}
});
jQuery21007744578921701759_1395250905357({
"Appfeed1":
{
" cnty ":"MEXICO",
"feed":"text ",
"feedsId":"198",
"nickname":"estudiante",
" state ":"Tamaulipas",
"date":"26\/02\/14"
}
});
jQuery21007744578921701759_1395250905357({
"Appfeed2":
{
" cnty ":"MEXICO",
"feed":"text ",
"feedsId":"197",
"nickname":"el roger",
" state ":"Tamaulipas",
"date":"26\/02\/14"
}
});
But when I try to loop through this in java script It just shows the last feed (Appfeed2). Also in when I print the data in console.log(). It looks like just received the last feed too.
Object {Appfeed2: Object}
1. Appfeed2: Object
1. state: "Tamaulipas"
2. date: "26/02/14"
3. feed: "Ayer fui a sacar mi licencia, sin saber manejar, no hice fila y solo me costo 200 pesos mas. Creo que sere taxista "
4. feedId: "197"
5. nickname: "el roger"
6. cnty: "MEXICO"
7. __proto__: Object
2. __proto__: Object
Any ideas? I was thinking about the way jsonp is returning the data, so I tried with square brackets, with and w/o the get callback, but it fails.
Thank you so much for your help!
You need to make sure that in your PHP code, you are only echoing out the JSON(P) once after the loop finishes. You need to build the array you want then echo it out at the end.
$jarr = array();
$af = 0;
while( $row = mysql_fetch_array($result) )
{
$jarr["Appfeed".$af] = array(
"cnty" => stripcslashes($row['cnty']),
"feed" => stripslashes($row['feed']),
"feedId" => stripslashes($row['feedId']),
"nickname" => stripslashes($row['nickname']),
"state" => str_replace("\r\n",'', $row['state']),
"date" => date("d/m/y", strtotime($row['date'])))
);
$af++;
}
echo $_GET['callback'] . '(' . json_encode($jarr) . ');';
P.S. Your AJAX call has a few too many options:
$.ajax({
type:'GET',
dataType: "jsonp",
url: "http://www.domain.com/app/loadFeedsApp.php",
success: function(data) {
$.each(data, function(i, v){
console.log(i);
console.log(v);
});
}
});
i have an array , which has to be passed from backend to frontend using ajax, i am new to ajax i know the syntax but got stuck , below is my code
backend(PHP)
$s_q = "SELECT `ans` FROM `bec_log_response` WHERE session_id=1 AND paper_id=2";
$s_res = mysql_query($s_q, $db2);
while($row= mysql_fetch_array($s_res))
{
echo $row['ans'];
}
$result = array('ans' => $row['ans'] );
Javascript code
function get_solution()
{
$.ajax({
url: 'waiting.php',
dataType: 'json',
type: 'GET',
timeout: 30 * 1000,
data: {sol:row},
success: function(json){
$('#saved').html(json.ans);
},
error: function(){}
});
}
i am getting an error in this code data: {sol:row}.
The response data from php is not in json format..
$result = array('ans' => $row['ans'] );
echo json_encode($result);
add this in your php code
Create a JSON on the PHP Side and catch it with $.getJSON jquery
Server Side:
$row_1 = array();
$s_q = "SELECT `ans` FROM `bec_log_response` WHERE session_id=1 AND paper_id=2";
$result = mysql_query($s_q) or die (mysql_error());
while($r = mysql_fetch_assoc($result)) {
$row_1[] = $r;
}
$post_data = json_encode(array('ans' => $row_1));
echo $post_data;
Client Side:
$.getJSON("result.php", function(json) {
console.log(json)
$.each( json, function( key, data ) {
//loop through the json if necessary
});
});
I have array containg image path ,
GenerateReport[0] ="../images/Desert1.jpg"
GenerateReport[1] ="../images/Desert2.jpg"
GenerateReport[2] ="../images/Desert3.jpg"
GenerateReport[3] ="../images/Desert4.jpg"
GenerateReport[4] ="../images/Desert5.jpg"
I am trying to pass this array with following code,
$.ajax({
type: "POST",
url: "generatePdf.php",
data: {
genRep: "sample value"
},
success: function(data) {
alert(data);
console.log('getting '+data);
}
});
sample value is passed successfully , but how can i pass array to ajax and use it on another page?? i tried passing array and using with below code but it is not working
$data1 = $_REQUEST['genRep'];
echo "tested".$data1[0];
Try like
genRep = [];
$.ajax({
type: "POST",
url: "generatePdf.php",
data: {
genRep: GenerateReport
},
success: function(data) {
alert(data);
console.log('getting '+data);
}
});
It will send your array as genRep
try to use json object. in object you can store your images path
var data=[]; // array
var data[0] = 'something';
var data[1] = 'something1';
var data = { 'name': name, 'email' : email, 'contact' : contact, 'type' : type, 'msg' : msg }; // object
$.ajax({
url : 'contact.php',
type : 'POST',
data : {contact:JSON.stringify(data)}, // for json object
data : {contact: data}, // for array
success : function (msg)
{
alert(msg);
}
})
contact.php
$info = $_POST['contact'];
$info = json_decode($info,true); // for json object
echo $info.name; // for json object
echo $info[0]; // will print something...
$arr = array();
$arr[0] = "Mark Reed";
$arr[1] = "34";
$arr[2] = "Australia";
echo json_encode ($arr);
use this on the php page
and use the following to get the output
success:function(msg){
id_numbers = JSON.parse(msg);
alert(id_numbers)
}
Try:
$.ajax({
url: "generatePdf.php",
type: 'POST',
data: form_data,
dataType:"json",
success: function(data) {
alert(data[0]);
}
On the PHP side, you'll be wanting to print:
print json_encode($photos);
Made Some Change
print json_encode(array("photolist"=>$photos));
Then on the server, you'd access these with:
data.photolist[0]; //First photo
I have tested it, this will definitely work !
JS:
var GenerateReport = [];
GenerateReport[0] ="../images/Desert1.jpg";
GenerateReport[1] ="../images/Desert2.jpg";
GenerateReport[2] ="../images/Desert3.jpg";
GenerateReport[3] ="../images/Desert4.jpg";
GenerateReport[4] ="../images/Desert5.jpg";
$.ajax({
type: 'POST',
url: 'generatePdf.php',
data: 'image_array='+GenerateReport,
success: function(msg) {
alert(msg);
}
});
generatePdf.php :
<?php
$image_string = $_POST['image_array'];
$image_array = explode(",", $image_string);
print_r($image_array);
?>
Then you can loop over the $image_array to get the values.
try this
GenerateReport[0] ="../images/Desert1.jpg"
GenerateReport[1] ="../images/Desert2.jpg"
GenerateReport[2] ="../images/Desert3.jpg"
GenerateReport[3] ="../images/Desert4.jpg"
GenerateReport[4] ="../images/Desert5.jpg"
corrected code:
var imagedata = '';
$.each(GenerateReport,function(index,value))
{
if(imagedata=='')
{
imagedata = imagedata +'image'+index+'='+value;
}
else
{
imagedata = imagedata +'&image'+index+'='+value;
}
});
$.ajax({
type: "POST",
url: "generatePdf.php",
data: imagedata //pass string imagedata
success: function(data) {
alert(data);
console.log('getting '+data);
}
});
imagedata should have sting like this:
image1=../images/Desert1.jpg&image2=../images/Desert2.jpg and so on
if(isset($_REQUEST['genRep']))
{
$data = $_REQUEST['genRep'];
print_r($data1);
echo "tested".$data1[0];
createPdf($data);
}
My code was correct , there was no value on index 0 , thats why it was not printing anything .My Mistake !!!
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");
}
});