Get Response from PHP File Using Ajax

Get response from PHP file using AJAX

<?php echo 'apple'; ?> is pretty much literally all you need on the server.

as for the JS side, the output of the server-side script is passed as a parameter to the success handler function, so you'd have

success: function(data) {
alert(data); // apple
}

How to get response from PHP file as an array using Ajax?

HTML

<form name="frmRegistration" id="signup-form" method="post">
<div>
<input type="text" name="address" id="address" class="findaddress" placeholder="Postal code"/>
<input type="button" name="addressbutton" class="addressbutton" value="Find" id="findaddress" />
<input type="text" name="address2" id="address2" class="findaddress" placeholder="Line 1"/>
<input type="text" name="address3" id="address3" class="findaddress" placeholder="Line 2"/>
<input type="text" name="address4" id="address4" class="findaddress" placeholder="Line 3"/>
<input type="text" name="address5" id="address5" class="findaddress" placeholder="Line 4"/>
</div>
</form>

Javascript

$(document).ready(function(){
$('.addressbutton').click(function(){
ss = document.getElementById("address").value;
$.ajax({
url: 'findaddress.php',
type: 'post',
data: {address:ss}, //added an index address here
success: function(response){
var replay = response.postal_code;
//innerHTML is not an attribute of text boxes, so changed it to value
document.getElementById('address').value = response.postal_code;
document.getElementById('address2').value = response.route;
document.getElementById('address3').value = response.locality;
document.getElementById('address4').value = response.postal_town;
document.getElementById('address5').value = response.administrative_area_level_2;
},
error: function(response) {
alert("Error: "+response);
}
});
return false;
}); //added closing brace and bracket
});

added comments in script about changes made.

PHP FILE (findaddress.php)

<?php
header('Content-Type: application/json');
$ss = $_POST['address'];
$postcode = urlencode($ss);
$url = 'http://maps.googleapis.com/maps/api/geocode/xml?address='.$postcode.'&sensor=false';
$parsedXML = simplexml_load_file($url);

if($parsedXML->status != "OK") {
echo "There has been a problem: " . $parsedXML->status;
}

$myAddress = array();
foreach($parsedXML->result->address_component as $component) {
if(is_array($component->type)) $type = (string)$component->type[0];
else $type = (string)$component->type;
$myAddress[$type] = (string)$component->long_name;
}

echo json_encode($myAddress);
die();
?>

taken out irrelevant indexing again, and irrelevant statements.

Fetch Only PHP Response using AJAX

You can use exit() function to get the correct return :

  if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST["txtField"])) {
echo "OK";
exit();
} else {
echo "NOT OK";
}
}

When you send an Ajax call, the server return all the printed value on your file. So the HTML is printed too.
Like that, you print only 'OK' because exit() stops the execution file, and only OK is printed.

Note, it's more appropriate to use a separate PHP file and HTML file, when you use AJAX.

JQuery/AJAX Unable to Get Response from PHP file

You are using the value of the parameter, not the parameter itself...

if (isset($_POST['action'])) {
echo hello_world();
// Or json_encode(hello_world()); for returning an Array
}

or

if ($_POST['action'] == 'helloworld') {
return hello_world();
// Or json_encode(hello_world()); for returning an Array
}

How do I get response data from php with ajax (one file)?

Because I wanted everything in one file I decided to use data.slice(0, 1); to trim off everything except the first character which will be a 0 or 1, and thanks to David for reminding me that there may be a whitespace issue, which there was. Now I added text.trim() to remove all of the whitespace from the input and array_filter(array_map('trim', $file)); to remove all of the whitespace from the strings written in the file.

This is the finished code:

<?php
if (isset($_POST['table'])) {
$file = file("testing.txt");
$file = array_filter(array_map('trim', $file));
if (in_array($_POST['table'], $file) == true) {
echo "1";
} else {
echo "0";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
var text;
document.getElementById('button').onclick = function () {
text = document.getElementById('text').value;
post(text.trim());
};
function post(vally) {
var table = vally;
console.log(vally);
$.post('test.php', {table:table}, function(data) {
var cut = data.slice(0, 1);
if (cut == 1) {
console.log("the output is 1")
} else {
console.log(cut);
}
});
console.log('posted');
}
</script>
</body>
</html>

I would like to thank everyone who helped me resolve my issue, which has been bugging me for the last 2 days.

How to ajax call a php file hosted on remote server and receive a response?

This is because your PHP script is hosted on a different server and your AJAX call code is on local.

For AJAX to run, there is same-origin policy. Under this policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin (means both are on same domain). Read more about same origin policy here.

The same-origin policy prevents some Ajax techniques from being used across domains, although the W3C has a draft of the XMLHttpRequest object that would enable this functionality. Methods exist to sidestep this security feature by using a special Cross Domain Communications channel embedded as an iframe within a page, or by the use of JSONP, websockets, cross-domain messaging or cross-domain resource sharing.

So in short you will not be able to access the PHP request residing on a 000webhost server to be accessed using AJAX code on local.

Either you host the AJAX code on the same 000webhost domain as well or enable cross-domain resource sharing on 000webhost domain where your PHP code is running.

As far I know, 000webhost is a free server and doesn't supports these changes. So you will have to either get a better server or test this all in a local.

Also as you mentioned in your query, all HTTP requests like GET, POST, PUT works cross domain. But for AJAX, no its not so straight forward.

Hope this helps!

AJAX not receiving PHP response

Use json_encode to send data back with AJAX.

<?php

/* AUTOMATED VARIABLES */
$upload_dir = "images/external/doodles/";
$url = md5(uniqid(rand(), true));
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = $upload_dir.$url.'.png';

$img = $_POST['data'];
$img = substr($img,strpos($img,",")+1);
$data = base64_decode($img);
$file = $upload_dir . $url . ".png";
$success = file_put_contents($file, $data);
if(!$success) {

echo json_encode(['filename' => false]);
exit(); // Prints success and exit the script

} else {

echo json_encode(['filename' => $file]);
exit();
}

?>

In your AJAX do this

function doodleSave() {
var canvas = document.getElementById("doodle-canvas");
var canvasData = canvas.toDataURL("image/png");
$.ajax({
url:'test.php',
type:'POST',
data:{ data:canvasData },
success: function(response){
var data = JSON.parse(response);
if (data.filename != false) {
alert(data.filename);
}else {
alert('unable to upload');
}
},
error: function(){
alert('failure');
}
});
}

You can also use $.post() which is a shorthand for $.ajax() for POST request.

function doodleSave() {
var canvas = document.getElementById("doodle-canvas");
var canvasData = canvas.toDataURL("image/png");

$.post('test.php', {data: canvasData}, function (response) {
var data = JSON.parse(response);
if (data.filename != false) {
alert(data.filename);
} else {
alert('unable to upload');
}
})
}

Sending data using ajax to php file not working

Answer from comment:

  • Change from $_GET to $_POST in PHP
  • Remove contentType: 'application/json', from the Ajax request


Related Topics



Leave a reply



Submit