Getting JSON data from a PHP script using AJAX - javascript

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);
}
});
}

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.

Save a string on a server using JavaScript and PHP

I am trying to use AJAX, but it seems it's not working.
var data = 'foo bar';
$.ajax({
url: 'http://localhost/index.php',
type: 'POST',
data: {data: data},
success: function(result) {
alert('success');
}
});
index.php
<?php
$x = $_POST["data"];
file_put_contents ('data.txt', data);
I get a success alert, but data.txt is empty. I have no idea why is this not working.
I am using XAMPP to test on local server.
No, using only javascript you can not write files on a server, because your javascript runs on the client side (the browser).
You need either Ajax and a server side script (like PHP) to handle the saving, or if you only want to use it with one browser (chat with yourself?), you can store stuff with javascript in the localstorage of the browser, but be aware that this storage does not last forever.

How to make Request.JSON work cross-domain (Mootools)?

I am executing an index.html file from the server test1.com. Mootools library file is included in this index.html file.
Following is a script that calls a PHP page:
<script>
var request = new Request.JSON({
url: 'http://test1.com/ajaxtest.php',
onSuccess: function(data) {
// the request was completed.
alert(JSON.stringify(data));
}
}).send();
</script>
ajaxtest.php
<?php
$arr['age'] = 30;
$arr['place'] = 'London';
echo json_encode($arr); exit;
?>
While executing index.html, I'm getting the correct output"
{"age":30,"place":"London"}
Now, ajaxtest.php is residing on another server, say test2.com. How to change the above script to make it work as earlier?
Not sure if this will be helpful to you now.
You need to use the Request.JSONP Class object to make cross site request:
new Request.JSONP({
url: "http://search.twitter.com/search.json",
data: {
q: "Arsenal"
},
onComplete: function(tweets) {
// Log the result to console for inspection
console.info("Twitter returned: ",tweets);
}
}).send();

How to run external php script using phonegap?

I am trying to connect to a remote server and basically run my application off files on that server. I am able to connect to the server but I don't know how to execute the php files on that server. Here's my javascript function on my local directory which connects to the server:
function test2(){
$.getJSON("http://sampleserver.com/check.php?var=test&callback=?", {
success:function(data){
alert("Working"); },
error: function() {
alert("Error");
}
});
}
This alerts "Working". Here's my check.php on the remote server:
<?php
echo "hello";
echo $_GET['jsoncallback'];
?>
Why is hello not being printed to the screen? How would I actually execute this script once I am connected?
Here is just one example:
var url = '/m.profile_msg/0/send/';
var dataString = 'msg_body='+ msg_body;
$.ajax({
type: "POST",
url: url,
data: dataString,
success: function(data) {
try {
//var data = jQuery.parseJSON(data);
alert(data);
} catch(e) {
alert(data);
}
}
});
And on the PHP side:
<?php
$xxarray = array('key' => 'value');
echo json_encode($xxarray);
?>
Your script IS already executing, but you're doing an AJAX call and simply alerting with your own message, you're not doing anything with the response, which would contain your hello text.
To run remote scripts - try doing your ajax call to a PHP script and have the PHP script shell execute something. But I wouldn't wait for the reply - rather return a status code back to the mobile device saying that the script is running.

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