Passing via GET json to ajax jquery, - php

I'm getting from a php page a json after a json encode. I correctly see the json in page that i want to pass to ajax. The data i send are taken via get from a form in php, saved in an array and then passsed with json encode.
But i get the error object from ajax:
What i'm missing? Should i copy and paste part of my backend too?
$.ajax({
method: "GET",
url: "queries/queries.php",
dataType: "json",
succes: function(data){
console.log(data);
console.log('json found');
},
error: function(error){
console.log(error);
console.log('json not found');
}
});
backend:
$calls= "text";
for ($i=0;$i<count($array);$i++) {
$schemaTab = $array[$i] . $calls;
$query = "SELECT * from 'schema'.'table'"; // this is just a sample query
$res=$db->getQuery($query); // this is a function that output the db query
header('Content-Type: application/json');
echo json_encode($res); // the json i pass
}
json:
[{"Schema":"schemaName1","DATEHOUR":"10\/05\/2021 11:56","count":"4"}]
[{"Schema":"schemaName2","DATEHOUR":"10\/05\/2021 10:21","count":"3"}]
[{"Schema":"schemaName3","DATEHOUR":null,"count":"0"}]
[{"Schema":"schemaName4","DATEHOUR":null,"count":"0"}]

Your JSON is invalid. JSON must consist of one thing such an a string, object, or array. (Objects and arrays can nest as many other things as they like inside them).
You have an array ([{"Schema":"schemaName1","DATEHOUR":"10\/05\/2021 11:56","count":"4"}]) which would be valid JSON but then you have another array and so on.
Gather up all your data into a variable in your PHP.
Then have header('Content-Type: application/json'); echo json_encode($that_variable) once, outside the loop.

Related

Problem sending an array containing some JSON string to AJAX from PHP

Am working on a form whereby am passing values from the frontend to the backend using AJAX. From the frontend, all the data is being passed fine except that after performing some logic on the backend, I need to transport the data to the frontend. The data is contained in 2 separate variables whereby I have converted each to a JSON object for transmission.
When I dd() the data in the backend I get it in form of a string.
The problem is when I log response in the console tab (from the AJAX code), I don't get any response from the backend.. Please assist?
Controller file containing PHP code
public
function validatePlanEntries(Request $request)
{
//dd($request->all());
//Other PHP logic
//Convert data to JSON format
$form = json_encode($oldata);
//dd($form);
$planJson = json_encode($plans_benefits);
$plans = compact(['planJson' , 'form']);
//dd($plans);
return $plans;
}
AJAX code getting the response from the controller above
<script>
//Other Js code
form.parsley().validate();
//Returns true if Parsley validation has no errors
if (form.parsley().isValid()){
$.ajax({
type: "POST",
url: "getplans",
data:JSON.stringify(type),
contentType: 'application/json',
dataType: "json",
success: function(response){
console.log(response);
},
failure: function(errMsg) {
alert(errMsg);
}
});
};
</script>
I wouldn't convert them to 2 separate JSON encoded values an instead add them to 1. So instead of...
//Convert data to JSON format
$form = json_encode($oldata);
//dd($form);
$planJson = json_encode($plans_benefits);
$plans = compact(['planJson' , 'form']);
//dd($plans);
return $plans;
Something like, build an array with both pieces of data and json_encode() the result...
return json_encode([ "form" => $oldata, "plan" => $plans_benefits]);
You will need to update your Javascript to extract the relevant parts of the response.
Update:
I'm not a Laravel person, but it seems you can use...
return \Response::json([ "form" => $oldata, "plan" => $plans_benefits]);

Passing a jQuery array to PHP (POST)

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?

How to access all elements in an array from php that is passed by an ajax call?

I am finding difficulty in accessing elements in an array from php file. The array is passed through an ajax call. Please find below the ajax call.
var data = ['test1', 'test2', 'test3'];
$(document).ready(function () {
$("button").click(function () {
$.ajax({
type: "POST",
url: "getResult.php",
data: {
testData: data
},
success: function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
}
});
return false;
});
});
The server side [PHP] code is
$myArray = $_POST["testData"];
echo $myArray;
However $myArray always returns last element[test3 here] in the array. How do I access first [here test1] and other elements?
Pls help.
What you need to do is convert the JavaScript array to JSON and then send over that JSON.
On the PHP side you should decode the JSON back into an array. Finally, you should re-encode the array as JSON before sending it back.
On your client side change one line:
data: {testData : JSON.stringify(data)},
On your server side do:
$myArray = json_decode($_POST["testData"]);
header('Content-Type: application/json');
echo json_encode(array('pheeds' => $pheeds, 'res' => $res));
JS:
JSON.stringify(data)
PHP:
$myArray = json_decode($_POST['data']);
For simple structures you can use jQuery Param
data : $.param({testData:data})
With this you should be able to access your data with
echo $_POST["testData"][0]...[2];
Try this when passing JS vars by ajax.
use Firebug to see on the console what is being poted to the PHP file, this will save you a lot of trouble.
you will see that array is an OBJECT , So you want to send this array as a JSON / STRING to the PHP file.
use :
var data = ['test1','test2','test3'];
data = JSON.stringfy(data);
at the PHP:
$data = var_post('test_data');
$data=json_decode($data);
$print_r($data);

How to pass HTML via JSON from PHP to AJAX - properly

I'm still in AJAX stuff since morning so maybe thats the reason why some things does't work as they schould - let's forget about it. To sum up, my problem is coincident with passing HTML via JSON. An example of the PHP code:
$list = "<strong>This is test</strong>";
$response = array('success'=>true, 'src' => $list);
echo json_encode($response);
Basicly that's the main part of the code which is responsible for passing the HTML to AJAX. Now, let's have a look on part of AJAX code:
success: function(output)
{
alert(output);
json = $(output).find(".content").text();
var data = $.parseJSON(json);
if(data.success == true)
{
obj_a.parents(".row").append(data.src);
obj_a.attr("id", "rollBack");
obj_a.text("Roll back");
}
},
Some of you will ask what am I doing in this part:
json = $(output).find(".content").text();
The answer is: I retrieve the json string from the ".content" box, so when I alert variable "json: i get:
{"success":true,"src":"1. dsfasdfasdffbcvbcvb<\/span>Edytuj<\/span> <\/a>Usu \u0144<\/span><\/div>2. vbnvbnm454t<\/span>Edytuj<\/span><\/a>Usu\u0144<\/span><\/div>3. ndfhgndgfhndfhgndfhd<\/span>Edytuj<\/span><\/a>Usu\u0144<\/span><\/div><\/div>"}
The problem is that I do not get this HTML... I get only text witout any HTML tags, styles etc...
String which I get, rather than HTML:
"1. dsfasdfasdffbcvbcvbEdytujUsuń2. vbnvbnm454tEdytujUsuń3. ndfhgndgfhndfhgndfhdEdytujUsuń"
Please don't try to look for anything smart or gunius in the above string because u won't - it's only a test string.
Acording to the part of PHP code - in my case I get "This is test" rather than "This is test".
To sum up my question is, how to pass these HTML tags or whole HTML code via json from PHP to AJAX.
I think you're misunderstanding how jQuery.ajax() works. You just need to tell it that dataType: 'json' (meaning that you're expecting JSON output from the server), and it takes care of the rest. You don't need to use jQuery.parseJSON(). The success() method will be given a JavaScript object representing the server response.
success: function(output)
{
// output is a JS object here:
alert(output.success); // true
// ...
},
To get your HTML from that point, you would just access output.src.
You can specify dataType: 'json' in your ajax request and receive an object(i.e. json already parsed) in your success call. eg
$.ajax(url, {
dataType: 'json',
success: function(output)
{
if(output.success == true)
{
obj_a.parents(".row").append(output.src);
obj_a.attr("id", "rollBack");
obj_a.text("Roll back");
}
},
if you can't change dataType you would call $.parseJSON on output
function(output)
{
alert(output);
var data = $.parseJSON(output);
if(data.success == true)
{
obj_a.parents(".row").append(data.src);
obj_a.attr("id", "rollBack");
obj_a.text("Roll back");
}
},

How to send a json string back to jquery

I need to send some data to an external php page and that page has to send the required data back to jQuery. My question is how can I send the data from the external page back to jQuery on the page that send it.
This is the jQuery code that sends the data to the external page:
function LoadImageData(url)
{
$.ajax({
url: 'get_image_data.php',
dataType: 'json',
data: {'url': url },
success: SetTag()
});
}
This is the PHP code htat receives the data and is required to send some data back:
<?php
require_once('FaceRestClient.php');
$apiKey = '**********************';
$apiSecret = '**********************';
$api = new FaceRestClient($apiKey, $apiSecret);
$active_url = $_POST['url'];
$photos = $api->faces_detect($active_url);
return $photos;
?>
So my problem is, how can I send the data backto jQuery. Just a simple return does not seem to work.
Thanks in Advance,
Mark
You need to echo the resulting JSON:
echo $photos;
If $photos is not already JSON, use json_encode:
echo json_encode( $photos);
One would think the REST API would give you JSON, but you need to check if it's valid JSON (JSONP is not valid here) ?
You could just drop the dataType in your Ajax function and let jQuery figure it out, that way atleast you'll get something back if it's not valid JSON.
Try this:
$.ajax({
url: 'get_image_data.php',
type: 'POST',
data: {'url': url }
}).done(function(data) {
console.log(data);
}).fail(function() {
console.log('Your ajax just failed');
});
Open the console, and see what is printed
At the end of a PHP function I tend to do :
exit(json_encode($someData));
To return the data as JSON, but anything that prints the data is ok.
try this
echo json_encode( $photos);
you need to echo
echo $photos;
and as metntoned by #nickb if $photo is not already a json then convert it into json first and then echo.
echo json_encode($photos)
in jQuery if you want to fetch the data
onSuccess: function(data, status) {
//var data contains the returned json.
}

Categories