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.
Related
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.
I'm able to send some POST requests to a php file. On this php file, I use this to check if my POST request is what I want:
<?php
if(isset($_POST['message'])) {
// Some stuff here
}
?>
I would like to know if I can do the same thing in AJAX / JQuery ?
Not something like this:
<script>
$.post("page.php", $("form[name=addMessage]").serialize(), function(data) {
//Do something here
}).error(function() {
//error
})
</script>
EDIT:
I don't want to send POST request in AJAX / JQuery. I just want to check if I receive a POST request, send from another page.
Indeed, I send a POST request with a field named "message". And I my question is: Is it possible to check if the field "message" is set, but not in PHP, in AJAX / JQquery.
Thank you so much for your help.
Regards,
Lapinou.
If I understand what you are trying to do: No.
Do you want to just listen for an incoming request in Javascript without calling any Ajax-methods? This is not possible. Javascript needs to be told that "I am sending a request now, and I want a response". It is not possible to say "If any request is sent, deal with it here".
Think about it. How would this work? If Javascript would listen to any request incoming, how would it know the difference between an user submitting a form and you sending a request using Postman?
Also, once you load the website in your browser, this is said to be clientside. Everything that happens after that is bound to your computer and your instance of the website. Any request sent to the site would be sent to the server, not your browser.
An other way of doing a post is this:
$.ajax({
type: "POST",
url: "page.php",
cache: false,
data: "message=" + $(".msgBox").val(), //Or Json format { "message" : $(".msgBox").val() },
success: function(html){
$(dashboard_id).html(html);
}
});
Try this:
$("form[name=addMessage]").submit(function(e) {
e.preventDefault();
$.post("page.php", $(this).serialize(), function(data) {
//Do something here
}).error(function() {
//error
})
});
*Update
As per your comment you want to check POST value using JavaScript / jQuery, I don't think so you can access POST data using JavaScript / jQuery. But you want to mix php then you can do something like this
var post = '<?php json_encode($_POST); ?>';
if (post.message !== undefined) {
}
You have to put var post = '<?php json_encode($_POST); ?>'; in a php file
My PHP script, 'getNews.php', (which works when I run it in the terminal and returns the correct data) is as follows:
<?php
header('Content-Type: application/json');
$db = new PDO('mysql:host=hostname;dbname=table', 'name', 'password');
$sql = "SELECT * from `news` ORDER BY date";
$result = $db->query($sql);
echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
?>
In my Javascript (I have JQuery loaded), I am attempting to pull this data in the following manner:
$(document).ready(function() {
$.getJSON("getNews.php", function(data) {
console.log(data);
});
});
which does nothing. When I change it to:
$(document).ready(function() {
$.get("getNews.php", function(data) {
console.log(data);
});
});
It writes the entire text of the php script to the console. Basically, it doesn't seem to be executing the php script or retrieving the json object at all. Thoughts?
Do you have a web server (like apache or nginx) installed? "It writes the entire text of the php script to the console." = You aren't invoking a PHP processor. Are you loading it like file:///something, or via http://something?
If you are using HTTP, make sure your web server knows to process PHP files. This usually involves editing a .ini or .cfg file; I can't tell which, because you don't mention what web server you are using.
It writes the entire text of the php script to the console
It could be that your server doesnt have php installed/configured. If thats not the case then see if this works for you
function prsJSN() {
$.ajax({
type: "get",
url: "getNews.php",
success: function(json) {
var dataArray = jQuery.parseJSON(json);
},
error: function(request, status, error) {
alert(request.responseText);
}
});
}
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.
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>";
}