Send html answer from PHP to Ajax - php

Here is what I'm trying to do:
I use an Ajax call to select messages from my database, I echo the content in my PHP and i try to get the echoed html in the Ajax success. But it does not work. Here is the code.
JQUERY:
function SelectMessages()
{
console.log("Selecting messages");
console.log("Talk = " + talk);
$.ajax({
url: "select_messages.php",
type: "GET",
data: "talk=" + talk,
success: function (html) {
alert(html);
console.log("In success");
$("#message_box").prepend(html)
},
error: function (html) {
alert(html);
console.log("In error");
}
});//ajax()
}//SelectMessages()
PHP:
<?php
//SELECTING MESSAGES
require 'dbconnect.php';
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
if ($_GET['talk'] != "") {
$request = $bdd->prepare('SELECT AUTHOR,CONTENT FROM MESSAGE WHERE TALK = :talk');
$request->execute(array("talk"=>$_GET['talk']));
while ($data = $request->fetch(PDO::FETCH_ASSOC)) {
echo' <p> '.$data['CONTENT'].'</p>';
}
}
?>
Using this code, I get "In error" displayed on the console and the code in the alert is "[object Object]". However, the status of my query is "OK" in my browser and the echoed result in the network window is the one expected with all the right values of messages.
I just don't understand why I get through the error instead of success.
Please do not mark this as a duplicate as I have already checked and tested the Ajax/PHP solutions and did not get any result.

In your php file you have set content type header as follows
header('Content-type: application/json');
but normally echoed the response as plain text/html. Either you have to send the response in json.
echo json_encode($data['CONTENT']);
Or remove content-type header as json.

Related

Why isn't my Ajax call Asynchronous

I'm using JQuery and AJAX to call a slow function in a PHP file, but I don't get a response until the PHP function is complete. I can't figure out why, despite 2 days of searching. I've shrunk it down to two test files, that exhibit exactly the same behaviour. My php function is thus, in a file called "ajaxfuncs.php":
<?php
Class AjaxFuncs{
public function __construct() {
$this->testbuffer ();
}
function testbuffer(){
echo 'Starting Test Buffer Output. There should be a 2 second delay after this text displays.' . PHP_EOL;
echo " <br><br>";
echo '<div id="testdata" class="testdata">0</div>';
// The above should be returned immediately
flush();
// Delay before returning anything else
sleep(2);
for ($a = 0; $a < 3; $a++) {
echo '<script type="text/javascript">document.getElementById("testdata").innerHTML="' . (int)($a + 1) . '"</script>';
flush();
// Delay for 1 second before updating the value
sleep(1);
}
}
}
$AjaxFuncs = new AjaxFuncs();
?>
The above works if I open the "ajaxfuncs.php" file in the browser. It does exactly as I'd expect, and the output updates every second until complete. So I know I've buffering sorted on the server.
But when I call it using the following $.ajax it's not right. I've put everything except the php for the ajax function into another php file called "testindex.php" for convenience. This is it:
<?php
header( 'Content-type: text/html; charset=utf-8' );
header("Cache-Control: no-store, must-revalidate");
header ("Pragma: no-cache");
header("Expires: Mon, 24 Sep 2012 04:00:00 GMT");
?>
<body>
<a>Test Page. Wait for it...</a>
<div id="maincontent">
</div>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<script>
$(document).ready(function(){
console.log ('Document Ready');
function callajax(){
var ajaxfilepath = "ajaxfuncs.php";
return $.ajax({
url: ajaxfilepath,
data: {action: 'testbuffer'},
type: 'get',
cache: false,
dataType: "text",
beforeSend: console.log('Starting Ajax Operation')
})
.done(function(result){
processajaxcalloutput(result);
})
.always(function(){
console.log(' Ajax Internal Complete Detected');
})
.fail(function( jqXHR, textStatus ) {
console.log( "Ajax Request failed: " + textStatus );
});
}
function processajaxcalloutput(result){
var message = 'Processing Ajax Response' ;
console.log(message);
$("#maincontent").append(result);
}
callajax();
});
Everything works without error. Console is clear - no errors (I'm testing with Chrome & Firefox). But I can't seem to get a response until the entire PHP function is done. I've tried everything I can find, in particular hundreds of different things to force caching off, but to no avail. Any help is much appreciated. Thanks.
Update:
So based on the feedback so far, it's clear the call is asynchronous and the code is fine, but asynchronous does not mean I'll get a continuous stream of output data from the php function as it executes. Instead the entire response will be returned at the end of the execution. Rather than divert this question into one about streaming, I'll leave it at this until I resolve the streaming issue.

unable to update data in db. jQuery, php

I was working with jQuery in the front end and php in the backend. I had some cross origin problem which I have fixed. but now I am filling up forms (sign up) but db is getting updated, not even empty row. Before I was getting some empty row in db ( I am sure about that, my memory is little hazy about that day! sorry!! ) I am unable to find any problem as errors or success message are not getting hit in jQuery file. I tried http://localhost/signup.php and its showing success message upon connecting to db. So I am sure that its connected to the proper db. I also tried to manual input using that php and i was able to import data as well.
I am adding the jQuery and php code below. I am using all this in XAMPP. Thanks in advance. :)
jQuery:
$("#userReg_btn").click(function(e)
{
//user registration in
var array = [];
var flag = false;
var fullName = $("#uFn").val();
var email = $("#uEa").val();
var mobile = $("#uMn").val();
var nID = $("#uNm").val();
var zip = $("#uZc").val();
var prof = $("#uPc").val();
array.push(fullName);
array.push(email);
array.push(mobile);
array.push(nID);
array.push(zip);
array.push(prof);
alert(array);
console.log(array);
$.ajax({
url:"http://localhost/signup.php",
data:
{
fullName: array[0],
email: array[1],
mobile: array[2],
nID: array[3],
zip: array[4],
prof: array[5],
},
type:"POST",
dataType:"json",
success:function(e){
alert("in success");
alert(e);
console.log("success");
},
error:function(e)
{
alert("error is hit");
alert(e);
console.log(e);
}
});
});
and php file:
<?php
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 01 Jan 2016 00:00:00 GMT');
header('Content-type: application/json');
$con=mysql_connect("localhost","root", "");
mysql_select_db("tester",$con);
$name = $_GET['fullName'];
$email= $_GET['email'];
$mobile= $_GET['mobile'];
$nID = $_GET['nID'];
$zip = $_GET['zip'];
$prof= $_GET['prof'];
$query="INSERT INTO user_reg(fullName,email,mobile,nID,zip,prof) VALUES('$name','$email', '$mobile','$nID','$zip','$prof');";
echo $name;
if(mysql_query($query))
{
echo "success";
}else{
echo mysql_error();
}
//}
?>
Thanks in advance again :)
I found a problem in your php script. In your AJAX call you are declaring the HTTP request as post. But in your php script you are using the $_GET method to look for the variable. Use $_POST.
In your PHP script:
$name = $_GET['fullName']
turns into
$name = $_POST['fullName'];
Do this for all your variables.
The reason why you were getting a blank row is because the variables were blank. By changing the method to $_POST your script will be able to find the variables
Your data object contains an extra ,, that shouldn't be there. Also, if you're sending json (note, I'm not sure you want to, but the headers suggest it):
data: JSON.stringify({
fullName: array[0],
email: array[1],
mobile: array[2],
nID: array[3],
zip: array[4],
prof: array[5]
}),
You will also need to set the contentType of the ajax post:
contentType: 'application/json',

Can't echo Ajax variable pass

I'm passing 2 variables with ajax to the same .php file. I see them in the console.log but I can't seem to echo them. I already tried several things I found in other questions but it doesn't seem to work. What do I need to add/change?
My code:
<script>
$(document).ready(function () {
$("#slider").bind("valuesChanged", function (e, data) {
$.ajax({
type : "POST",
url : "../wp-content/themes/twentytwelve/fields/test.php",
data : {
minValue : data.values.min,
maxValue : data.values.max
},
cache : true,
async : false,
success : function (data) {
console.log(data);
},
error : function (xhr) {
alert('fail')
}
});
});
});
</script>
and the php part:
<?php if ( $_POST ) {
echo $_POST['minValue'];
}
?>
Btw: it only passes the first value (minValue) and not the other one. How to pass them both? Thanks!
Maybe by printing both values?
<?php
if (!empty($_POST)) {
echo $_POST['minValue'];
echo $_POST['maxValue'];
}
?>
Can you see your request details in the Debug panels like Firebug in FF or (I don't know how it called) in Chromium-based browsers?
Are there all the passed data?
If no then the error in JS.
Also print out the whole POST data on server side to see the POST content.
To pass more values try something like this on php side:
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-type: application/json");
echo json_encode(array(
'a' => 1,
'b' => 2
));

JSONP data in PHP to JS

I'm using JSONP to dynamically add data into my Android Phonegap app. Since Phonegap 2.5 (and upwards) allows application cache, I would like to use that. Only problem is that at this moment, my data is in a php-file. I read that data from a php-file cannot be cached by the cache manifest, so I'm thinking about changing it to js or something. Any idea how I would do this? I already tried a lot of tutorials on JSONP, but the only way I can get JSONP to work is in PHP. They are also quite vague about how I should save my data file (currently called home.php).
home.php
<?php echo $_GET["callback"] ?> (
[
{
"expo":"pit",
"datum":"05.06.2011 - 05.06.2016",
"img":"images/pit_home.jpg",
"link":"exp1_index.html"
},
{
"expo":"Space Odessy 2.0",
"datum":"17.02 - 19.05.2013",
"img":"images/so_home.jpg",
"link":"exp2_index.html"
}
]
);
script in index.html that calls data from home.php
<script type="text/javascript">
$.ajax({
type: 'GET',
jsonpCallback: 'jsonCallback',
contentType: 'application/json',
dataType: 'jsonp',
url: 'http://mllsdemode.be/Ex-cache/home.php',
success: function(json) {
var $home = $("#home");
$home.empty();
$.each(json, function(i, el) {
$home.append("<td><div class='dsc'>" + el.expo + "<br><em>" + el.datum + "</em></div></td>");
});
},
error: function() { alert("Error reading jsonP file"); }
});
</script>
Well, if I understood well, this is cached, you want it to be cached but not to develop? Then add some headers to develop!
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
To easily forge your JSON, you can use Simple JSON for PHP, it allows you to build complex JSON/JSONP.

jQuery POST handling errors

Explanation
I am sending a POST, and in PHP I am checking if username already exists in database.
If yes, return an error.
But the thing is, I can't use the same function(data) because I want the error to be located in another div.
$.post("events.php?action=send", { data : $(this).serialize() }, function(data)
{
$("#processing").html('');
$("#comments").html(data);
});
Problem
I can't have two variables in anonymous function, like function(data, error), then how am I supposed to fetch the 'error' PHP printed e.g 'User already exist's in database', and then put it in the #errors div?
It depends on how you are handling the error in your PHP code.
In order to even end up in the error handler you need to set the HTTP statuscode to "5XX".
What you probably want to do is to serialize an error object in case the user already exists, and handle it in the success handler like you are doing now:
PHP:
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
$data = array('error' => 'something went wrong');
echo json_encode($data);
JS:
function(data){
if(data && data.error){
//there was an error, handle it here
console.log(data.error);
} else {
//do something else with the user
console.log(data);
}
}
In PHP you can return json error, like print '{"error":'.json_encode($error).'}' and then, in your js put in desired div
$.post("events.php?action=send", { data : $(this).serialize() }, function(data)
{
$("#processing").html('');
$("#comments").html(data);
$("#error").append(data.error);
});
I suggest you to return data as a json string from your server. If you do that, you can get an object from $.parseJSON(data);
// In your php code
$result = new stdClass();
$result->userExists=false;
echo json_encode($result);
Now inside your anonymous function:
// Javascript
data = $.parseJSON(data);
console.log(data);
if (data.userExists) alert("User exists!");

Categories