I have an array that is created in my ajax php file that looks like this
[[1,2,3],[1,2,3]]
So I echo it with a json_encode
echo json_encode($array);
This is my ajax code
$.ajax(
{
url: "ajaxfile.php" + "?something=" + something + "&something2=" + something2 + "&something3=" + something3,
type: "POST",
data: JSON,
success: function (data) {
object = data;
functionIwantthearraytobepassedto();
}
}
)
In the console all I get is
Notice: Array to string conversion in
ajaxfile.php on line
78 "[Array]"
Where am I going wrong? And how can I fix it?
Please try to add a header:
header('Content-Type:text/json');
echo json_encode($array);
Try adding to your ajax
dataType: 'json'
and
cotentType: 'application/json; charset=utf-8'
Related
I know that PHP is a Server-Side and Javascript is Client-side , But I'm wondering if it's possible to do the following .
I have a javascript function that calls an Ajax call to a PHP file , Here is the code:
function reloadData(fileName){
$.ajax({
//I want to insert the fileName parameter before .php
url: '<?php echo $filePath ."/fileName.php";?>',
type: 'GET',
async: true,
success: function( data ){
//Do Some Thing With Returned Data.
}
});
}
I want to pass PHP file name to the reloadData function
reloadData('get_data');
So that the url within ajax will be:
url: 'get_data.php',
Is it possible?
Do like this, where you use the filename variable and split the url string like this ' + fileName + '
function reloadData(fileName){
$.ajax({
//I want to insert the fileName parameter before .php
url: '<?php echo $filePath ."/' + fileName + '.php";?>',
type: 'GET',
async: true,
success: function( data ){
//Do Some Thing With Returned Data.
}
});
}
As a note though, when PHP echo this server side you might need to do something like this
'<?php echo $filePath ."/"?>' + filename + '.php'
Set your filepath as a global variable in your js so that you can make use of it throught you code. Then make use of this variable like this in your function:
var filePath = "<?php echo $filePath ?>/";
function reloadData(fileName){
$.ajax({
//I want to insert the fileName parameter before .php
url: filePath + fileName.trim() + '.php',
type: 'GET',
async: true,
success: function( data ){
//Do Some Thing With Returned Data.
}
});
}
Just change
url: 'fileName.php',
To:
url: `${fileName}.php`,
Not able to pass PHP encoded array to js.
index.php
echo '<script src="script.js"></script>';
$a=array(1,2,3,4,5);
echo json_encode($a);
?>
script.js:
$.ajax({
method: 'GET',
url: 'index.php',
dataType: 'json',
success: function (Data) {
alert("Success!" + Data);
},
error: function (Data) {
alert("Wrong");
}
});
I always got message - "Wrong".
You have not pass html tags in your json value generated from php
echo '<script src="script.js"></script>';
simply delete the code above. also, you have to parse your JSON string after your function is succssed, :
function (data) {
JSON.parse(data).forEach(function (x) {
alert(x);
});
}
use post method i think It work
method: 'POST',
Hi guys this script was working fine when I add a console.log but as soon as I replaced the console.log with the $.ajax() function it wont give me the result back from the php file the ajax function I used was working from my other projects but I cant seem to find out why it wont work on this snippet
Here is my js code :
$(document).ready(function(){
$("#qs").find(".chs").each(function(i,obj){
$(this).addClass("chs"+i);
$(".chs"+i).on("click",function(){
var s = $(this).data("lvs"),carrier= {"vars":s};
$.ajax({
url: aScript.php,
type: "POST",
data: carrier,
dataType: "json"
success: function(data) {
console.log(data) }
});
});
});
});
my php file looks like this
<?php
$json = $_POST['carrier'];
$data = json_decode($json);
$d = $data->vars;
echo $d;
?>
<input type="hidden" id="ss" value="<?=$d?>" />
can someone review this file for me cause I cant seem to find whats wrong please help me find out whats wrong with this script
You should wrap the filename inside quotes, as it is a string variable
$.ajax({
url: 'aScript.php',
type: "POST",
data: carrier,
dataType: "json",
success: function(data) {
console.log(data) }
});
});
There are some issues with your code
in this line url: aScript.php, the url string is not quoted, it should be url: 'aScript.php',
you set dataType: "json" but aScript.php returns html instead of json, remove that line
the data you're passing is not json, it will be serialized into key=value pairs and you'll be able to access it via $d = $_POST['vars'];
I am trying to use javascript to call a php script which then will return multiple variables back to my javascript so I can manipulate them.
This is my JS.
$.ajax({
url: 'test.php',
data: { id : lastFileId },
success: function(output) {
alert(output);
}
});
my PHP
<?php
$fileId = ($_GET['id']);
$num1 = 1;
$num2 = 2;
?>
From here, how can I return variables $num1 and $num2 so i can use them in my javascript. Is it possible?
also this is a very basic idea of what I have planned to do if I can achieve this.
You can return as many variables as you want with json_encode().
Try in your PHP:
<?php
echo json_encode(array($num1, $num2));
?>
You can add to that array , $num3, $num4, ... and so on.
In your JS, you can access each number as follows.
First, you will need this line of code to parse the encoded JSON string, in your success function.
var result = $.parseJSON(output);
That sets result as a JSON object. Now you can access all fields within result:
result[0] -- $num1 in PHP
result[1] -- $num2 in PHP
You can go for Json in PHP and javascript if you want array in response for a ajax request
PHP Code
<?php
$fileId = isset($_GET['id'])?$_GET['id']:0;
echo json_encode(array("field"=>$fileId,"num1"=>1,"num2"=>2));
?>
Js Code
jQuery.ajax({
type: "GET",
url: 'test.php',
dataType: "json",
success: function(response) {
console.log(response);
alert(response.num1);
}
});
convert json to object
jQuery.ajax({
type: "GET",
url: 'test.php',
dataType: "json",
success: function(response) {
item=JSON.parse(response);
console.log(item);
alert(item.num1);
}
});
Use a simply string and explode(split) it further in ajax response. Here is PHP code
<?php
$fileId = ($_GET['id']);
echo $num1."|".$num2;
?>
Now split(explode) the response with JavaScript
$.ajax({
url: 'test.php',
data: { id : lastFileId },
success: function(output) {
var my_arr = output.split("|");
console.log(my_arr[0] + "" + my_arr[1]);
}
});
you can simply return it like that
return ['num1'=>$num1,'num2' => $num2];
and also, you can access it as followed,
respone.num1
I am a newbie in coding. I am trying to display all the pictures in the database on the client side. I could do that on my php file, but I couldn't get the json_encode data with jQuery.
Could somebody help me? Thank you in advance!
Here is my PHP code:
foreach ($pictures as $picture){
$photos = "<p><img src='".$picture['link']."' width='200' height='200'></p><p id='title'>".$picture['title']."</p><p id='descr'>".$picture['descr']."</p>";
echo json_encode($photos);
}
And here is my JavaScript:
$.ajax({
type: 'GET',
url: 'server/picture_client.php',
dataType: 'json',
success: function(photos){
if(photos){
var data = $.parseJSON(photos);
$("#grid").append(data);
}else{
alert("oops nothing happened :(");
}
}
Thank you again!
You don't really need json in this case you can just send the html:
foreach ($pictures as $picture){
$photos .= "<p><img src='".$picture['link']."' width='200' height='200'></p><p id='title'>".$picture['title']."</p><p id='descr'>".$picture['descr']."</p>";
}
echo $photos;
Then append the html to your element:
$.ajax({
type: 'GET',
url: 'server/picture_client.php',
dataType: 'html',
success: function(photos){
if(photos){
$("#grid").append(photos);
}else{
alert("oops nothing happened :(");
}
}
Since you've provided dataType: 'json', you don't need to do $.parseJSON your data again, you can just use:
$("#grid").append(photos);
Try this,
foreach ($pictures as $picture){
$photos[] = "<p><img src='".$picture['link']."' width='200' height='200'></p><p id='title'>".$picture['title']."</p><p id='descr'>".$picture['descr']."</p>";
}
echo json_encode('photos' => $photos);
jquery:
$.ajax({
type: 'GET',
url: 'server/picture_client.php',
dataType: 'json',
success: function(results){
$.each(results.photos, function(i, item) {
$("#grid").append(item);
});
}
});