Getting a specifc json object from json file in php - javascript

I'm making a map using leaflet.js right now I'm getting countries through a json file using php as data provider and sending the ajax request to get data
PHP that provides File:
<?php
header("Access-Control-Allow-Origin: *");
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$data=file_get_contents("capitals.geojson");
$data= json_decode($data, true);
$data2= $data["features"];
echo json_encode($data2);
?>
Ajax Request that is getting data from php file:
$.ajax({
url: "php/capitals.php",
type: 'GET',
dataType: 'json',
success: function(result) {
countryList=result;
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("error");
}
});
Right now I'm choosing a specific object using this code:
option.value="GB";
const selectedCountry = countryList.find( countryObj => countryObj.id === option.value);
console.log(selectedCountry);
Instead of getting specific object from this code I want to get it from the PHP routine so that when an ajax request is passed the file returns only the specific object that I need.
I tried getting the specific object from json file using javascript but I want to get it through PHP.

Related

Send JSON form JavaScript to PHP

I'm trying to pass an array from JavaScript to PHP using JSON. I created a JSON using JSON.stringify and I know to decode it in PHP using json_decode but how can I pass it? To be clear, those variables are in a one php file.
I want to use it like this:
<script>
var arr = getArray();
var myJSON = JSON.stringify(arr);
... passing myJSON to PHP ...
</script>
<?php
$arr = //get myJSON
?>
I tried this:
<script>
var signalff = ff(signal);
request = $.ajax({
type: "POST",
url: "ecg_database.php",
data: {myData:JSON.stringify(signalff)}
});
request.done(function (response, textStatus, jqXHR){
console.log("Hooray, it worked!");
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
</script>
<?php
$obj = $_POST["myData"];
echo $obj;
?>
And in console I have a message "Hooray, it worked!", but it doesn't write anything by echo from $obj.
You can't do it like that. This is what happens with your code:
The user goes to the URL
The browser requests the page
The server runs the PHP. $_POST["myData"] isn't set.
The server sounds the result to the browser
The JavaScript in the page sends the data to the URL
The server runs the PHP again. This time $_POST["myData"] is set.
The result is available in response
You have two different requests and two different responses.
The request you send in step 5 doesn't travel back in time and retroactively change the request you sent in step 2.
Separate out your PHP so you have one URL to generate the original page and another to deal with the data you send with JavaScript.
Then use JavaScript to do something with the data in the response variable.

making api request in php through ajax call in js file

I want to make an api request in my php file.
But my api request depends on the user's input which will be passed from the front-end.
And in order to do so, my front-end js file is making ajax call to the php file. But php file is keep returning null in its global variable, $_POST.
in function.js file, I have
$.ajax({
type: "POST",
url: "/model/validate.php",
data: data,
dataType: "JSON",
success: function(response){
console.log(response);
},
error: function(response){
console.log("Error: " + response);
}
});
and in my validation.php file i have
<? php
if(is_ajax()){
echo "ajax works"
}
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
is_ajax is a helper function that checks if there was any ajax call.
So every time I run these files, I get error and i'm not sure why.
Once this is done, I plan to make api call using curl in my php file but for some reason, $_POST is always returning null. Can anyone help?

Getting 'undefined is not a function' when requesting JSON

I am having issues when requesting data from a PHP file.
When I call the variable msg[0} I am told it is undefined but it should have been populated in the JSON request. The JS is below and you can find the PHP output at the link:
$.ajax({
type: "GET",
url: "https://bluecode.org.uk/intranet/otd/index.php",
dataType: "json"
})
.done(function (msg) {
console.log(msg[0])
});
The actual PHP is:
mysql_query("INSERT INTO uniquedownload (downloadkey, file, expires) VALUES ('{$strKey}', 'hello.html', '".(time()+(60*60*24*5))."')");
$a = array($strKey);
echo json_encode($a);
Thanks
I'd recommend logging msg so you can see how the data looks, and maybe adding a debugger; into your .done() callback to give yourself a way of experimenting with different ways of accessing the properties of msg.
I needed to add this to the PHP:
header('Content-Type: application/json');

JQuery gives JSON syntax error when using PHP's json_encode

I have an application that uses JQuery $.ajax to send JSON encoded data to server where I process it and then send back the results also JSON encoded. The problem is that JQuery gives a parse error when I want to process the response. (As if PHP's json_encode function outputs an invalid JSON format).
Here comes the code:
The Javascript code:
$.ajax({
type: 'POST',
url: URL+'pages/processListUIAjaxRequest',
data:{filters: filters, rebuild_params: $('#rebuild_params\\['+unique+'\\]').val()},
dataType: 'json',
success: function(response){
alert(response);
},
error: function(request, status, error){
alert('Unable to update table contents');
console.log(request);
console.log(status);
console.log(error);
}
});
This is a piece of the PHP code which outputs the response:
$response->addResult($uFilters);
header('Content-Type: application/json');
$response->toJSON(true);
The $uFilters is a simple array, and the toJSON method of the $response object is here:
public function toJSON($output = false){
$out = array();
if($this->hasErrors()){
$out['has_error'] = true;
$out['errors'] = $this->getErrors();
} else $out['has_error'] = false;
$out['result'] = $this->_result;
if($output){
echo json_encode($out);
}else{
return json_encode($out);
}
}// toJSON
Every time I run the code i get the 'Unable to update table contents', and on JavaScript console I have:
'SyntaxError: JSON.parse: unexpected character'
despite I defined dataType: as 'json' and the output is json_encode'd by PHP. On the JavaScript console I can see that the response text is:
"{"has_error":false,"result":{"page_id":"xxx"}}"
Tried copy this and validate with online JSON validator tools, the interesting thing is it was valid a few times and it was invalid a few times (without any consistency) Im a bit confused.
Tried to use other headers like:
header('Content-Type: text/json');
header('Content-Type:javascript/json');
header('Content-Type: application/json');
or with no header, but nothing.
If I edit the JQuery ajax request's dataType to 'text' (despite the output is JSON formatted and and even the header says it is a JSON content), then the success handler runs and I got the response correctly. In this case the same problem comes when I try to $.parseJSON(response).
What went wrong? Is my JSON string really invalid?
Debug your response to see what characters are there that is making it not valid. Set the dataType to text and escape the text that is returned.
dataType: 'text',
success: function(response){
console.log(escape(response));
},
You will see the characters that are returned, there is probably some weird return character that is cauing the problem.

Get Ajax POST data on php via Javascript call

First I am conface that I am Newbie to php,
I am using jquery(knockout js) at client side & PHP at server side. my code.
Client side: I am using knockout js(Javascript). to call my PHP service.
My Code:
self.VMSaveEditUserMode = function () {
try {
var params = { "ClientData": [controllerVM_.ClientID(), controllerVM_.VMList[0].ClientName(), controllerVM_.VMList[0].ShortName(), controllerVM_.VMList[0].Address(), controllerVM_.VMList[0].CreatedBy(), controllerVM_.VMList[0].CityName(), controllerVM_.VMList[0].PostalCode(), controllerVM_.VMList[0].ContactEmail(), controllerVM_.VMList[0].ContactPhone(), controllerVM_.VMList[0].IsCorporate()] };
$.ajax({
type: "POST",
url: URL + "index.php/phpService/SaveClient/" + controllerVM_.TokenKey(),
data: JSON.stringify(ko.toJS(params)),
contentType: "application/json",
async: true,
dataType: 'json',
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
if (ErrorResponse.statusText == "OK") {
}
else {
alert("ErrorMsg:" + ErrorResponse.statusText);
}
}
});
}
catch (error) {
alert("Catch:" + error);
}
}
Server Side My Code, I am using this PHP code to connect with DB.
PHP Code:
public function SaveClient($userToken)
{
$value = json_decode($Clientdata);
echo $value->ClientData[0];
}
*My Question *:
I am not clear on how to POST data in PHP ? I tried with $_POST[''] method as well as many more.
I am using eclipse as a php framework. so, not able to debug it when i post the data.Normally mode i am able to debug my code.but not from remotely.for that i made changes on php.ini file also.
How to get Response of Post Data on php code ?
How to debug via remote post ?
My Request sample:
suppose i use:
For, data: params, only at that time my request format is.
ClientData%5B%5D=4&ClientData%5B%5D=kamlesh&ClientData%5B%5D=KAM&ClientData%5B%5D=Junagadh&ClientData%5B%5D=me&ClientData%5B%5D=SANTA+ROSA&ClientData%5B%5D=76220&ClientData%5B%5D=kamlesh.vadiyatar%40gmail.com&ClientData%5B%5D=9998305904&ClientData%5B%5D=false
For, data: JSON.stringify(ko.toJS(params)),
{"ClientData":["4","kamlesh","KAM","Junagadh","me","SANTA ROSA","76220","kamlesh.vadiyatar#gmail.com","9998305904",false]}
If I understand correctly you need to create a PHP service which is able to receive REST-like requests from client.
In order to do thad you need to access raw POST data. In PHP its being done like this:
$ClientData = file_get_contents('php://input');
You can read more about php://input in the wrappers documentation.
Of course from the client's side the data need to be sent using the POST method and as raw data, i.e. as a string. You can obtain a string from object using JSON.stringify() which you already do.
If you pass an object, it will be converted to string internally by jQuery using query-string format. More on that in the jQuery documentation for $.ajax (the most importatnt options being data and processData).
Just pass the ajax data param as an object, don't convert it into JSON. Then in PHP use $_POST directly.
Use firebug or chrome dev tools to analyze the ajax request and see which data is sent
Use this simple jquery function to accomplish your task
$.ajax({
type: "POST",
url:"scripts/dummy.php",
data:"tbl="+table,
dataType:"json", //if you want to get back response in json
beforeSend: function()
{
},
success: function(resp)
{
},
complete: function()
{
},
error: function(e)
{
alert('Error: ' + e);
}
}); //end Ajax
in PHP use:
if(isset($_POST['ClientData'])){
$client_data = $_POST['ClientData']
}
now $client_data variable should contain the array.
For debugging purpose you can use php's built-in print_r() function. It's pretty handy.
here's is an example:
//make sure it's post request
if(isset($_POST)){
//now print the array nicely
echo "<pre>";
print_r($_POST);
echo "</pre>";
}

Categories

Resources