I have the following code on my PHP page which gets a message from the client and stores it into a log file on the server. This function is called by a jquery AJAX function(given below). The AJAX request sends the data properly and the PHP code works fine. However when the response to the AJAX request is sent back the page suddenly redirects to index.php(my main page):
PHP Code
function store_chat_msg_function()
{
//Check if session is active
if(isset($_SESSION['NAME']))
{
$data = $_POST;
$text = $data["message"];
$filepath = $data["filepath"];
$fp = fopen($filepath, 'a');
fwrite($fp, "<div class='msgln'>(".date("g:i A").") <b>".$_SESSION['NAME']."</b>: ".stripslashes(htmlspecialchars($text))."<br></div>");
fclose($fp);
//Push data array to be sent into array
$json = array();
$bus = array(
'message' => "1"
);
array_push($json, $bus);
//Encode to JSON format
$jsonstring = json_encode($json);
//Specify type of data being sent
header("content-type:application/json"); //<-----(error:line 179)
//Finally send the data
echo $jsonstring;
}
else
{
}
}
And the AJAX function is:
//On submit message
$("#submitmsg").click(function(){
var ptarget = $(this).html();
//get some values from elements on the page:
//Set parameters...
var clientmsg = $("#usermsg").val();
//Clear the text box
$("#usermsg").val("");
var data = {
"action": "send_chat_msg",
"message": clientmsg,
"filepath": globalrefreshfile
};
data = $(this).serialize() + "&" + $.param(data);
//Send the data using post and put the results in a div
$.ajax({
url: "post.php",
type: "POST",
data: data,
datatype: "json",
success: function(data) {
if(data[0].message!="1"){
alert("Message was not sent.");
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
alert(errorThrown);
$("#chatbox").html('There was an error updating chat window');
$("#chatbox").fadeIn(1500);
}
});
});
I removed header("content-type:application/json"); and datatype: "json" in the AJAX function and found that the data is muddled by error data sent by the ZEND server i'm debugging on. The error is:
"Warning: session_start(): Cannot send session cache
limiter - headers already sent in C:\Program Files
(x86)\Zend\Apache2\htdocs\ChatServer\post.php on line 2Warning: Cannot modify header information - headers
already sent in C:\Program Files
(x86)\Zend\Apache2\htdocs\ChatServer\post.php on line
179[{"message":"1"}]
So i understand that I think i may have messed up the headers based on the ZEND debugger error which is interfering with my JSON data(seen appended at the end of the error)? What gives? Thank you for your time and patience.
Add ob_start(); as the first line in your script if you can't move the header("content-type:application/json"); to the top of the page for some reason.
You cannot modify headers, so move your code to top of page:
header("content-type:application/json");
Top means top of proccessed page, Not a top of function.
Regards
Related
I have an ajax-script that retrieves jsondata from php - so far ok, but the data could not be parsed since other outputs (echoes) comes along with the jsonstring. I searched this issue and it seems one should add header information when sending relevant output (json) from php back to clientside (ajax). When I do that nothing is sent back. How could I solve this?
this is how it looks like on the client side retrieving json (together with other prints)
connected to database { jsondata comes here .. } success
So, how to isolate the jsondata sending it back?
clientside (ajax) , snippet
$(function(){
$.ajax({
type:'POST',
url: 'endpoint.php?function=getJson',
data: {name: 'Stockholm'},
success: function (data){
console.log('success',data);
var jsonData = JSON.parse(data); //error here when parsing!!!
serverside (php), snippet
//header('Content-Type: application/json'); //if I add thos row no data is sent back
$result = $_GET['function']($_POST['name']);
echo $result;
function getJson($name) {
...
return $json;
}
I solved the problem by cleaning stdout (output buffer), putting the function call just a line before echo $result
that is:
$result = $_GET['function']($_POST['name']);
ob_clean(); // this call solved the problem
echo $result;
source:
https://www.php.net/manual/en/function.ob-clean.php
I'm working with the Laravel framework and I'm making an AJAX request to send an email. The request works fine and the mail is sent, the problem is I can't get the server response if the mail has been sent successfully or not.
Here's the code (short version) wich is located under views/contact/mail.blade.php :
if( mail($to, $subject, $body,$headers) ) {
$data = array( 'text' => Lang::line('contact.mail-success')->get() );
return Response::json($data);
} else {
$data = array( 'text' => Lang::line('contact.mail-error')->get() );
return Response::json($data);
}
and here's the jquery :
$('#contact-form').submit(function() {
var request = $.ajax({
url: BASE+'/contact',
type: 'post',
data: { name: $('#name').val(), mail: $('#email').val(), message: $('#msg').val() },
dataType:"json",
success: function(data){
var message = $.parseJSON(data);
alert(message.text); // here I get the "cannot read property of null" in the console log
}
});
return false;
});
What am I doing wrong? Thanks for your help.
Since Laravel sends the correct headers with Response::json there's no need to parse the JSON in your Javascript, simply change the line
var message = $.parseJSON(data);
to
var message = data;
You shouldn't return Response::json() from a view file, the view are supposed to echo whatever output generated from the view but in this case you need to return the response from the route itself, as json would also include header information.
While sending a response in form of JSON must be encoded using json_encode(); in PHP. after successful reach of done method then parse the object as JSON.parse();
Example :
Modify the line in php file as
return response()->json(json_encode($data));
add the line in javascript files as
done(function (data){
console.log(JSON.parse(data));
console.log(data.text);
});
I need to send some data to an external php page and that page has to send the required data back to jQuery. My question is how can I send the data from the external page back to jQuery on the page that send it.
This is the jQuery code that sends the data to the external page:
function LoadImageData(url)
{
$.ajax({
url: 'get_image_data.php',
dataType: 'json',
data: {'url': url },
success: SetTag()
});
}
This is the PHP code htat receives the data and is required to send some data back:
<?php
require_once('FaceRestClient.php');
$apiKey = '**********************';
$apiSecret = '**********************';
$api = new FaceRestClient($apiKey, $apiSecret);
$active_url = $_POST['url'];
$photos = $api->faces_detect($active_url);
return $photos;
?>
So my problem is, how can I send the data backto jQuery. Just a simple return does not seem to work.
Thanks in Advance,
Mark
You need to echo the resulting JSON:
echo $photos;
If $photos is not already JSON, use json_encode:
echo json_encode( $photos);
One would think the REST API would give you JSON, but you need to check if it's valid JSON (JSONP is not valid here) ?
You could just drop the dataType in your Ajax function and let jQuery figure it out, that way atleast you'll get something back if it's not valid JSON.
Try this:
$.ajax({
url: 'get_image_data.php',
type: 'POST',
data: {'url': url }
}).done(function(data) {
console.log(data);
}).fail(function() {
console.log('Your ajax just failed');
});
Open the console, and see what is printed
At the end of a PHP function I tend to do :
exit(json_encode($someData));
To return the data as JSON, but anything that prints the data is ok.
try this
echo json_encode( $photos);
you need to echo
echo $photos;
and as metntoned by #nickb if $photo is not already a json then convert it into json first and then echo.
echo json_encode($photos)
in jQuery if you want to fetch the data
onSuccess: function(data, status) {
//var data contains the returned json.
}
jQuery
var result='';
jQuery.ajax
({
contentType: "application/json; charset=utf-8",
dataType: "json",
url: <?php echo '"' .plugins_url('/test.php', __FILE__); ?>?Query="+ jQuery('#test').val(),
success: function(data)
{
//process results
},
error: function(jqXHR, textStatus, errorThrown){
console.log(arguments);
alert('HTTP Error: '+errorThrown+' | Error Message: '+textStatus);
return;
}
});
test.php
$file = $rootPath.'wp-content/uploads/test/'.$query.".txt";
if (file_exists($seoCacheFile) && is_readable($seoCacheFile))
{
$retarr = file_get_contents($file);
if($retarr !=="")
{
print_r($retarr);die;
}
}
if(count($ret)){
$retarr = json_encode(array('response' => array('test' => array('Results'=>$ret))));
print_r($retarr);
flush();
//PROBLEM IS HERE
//If an error occurs here, the json is mangled, flush() does not help. Can I send the json and deal with PHP errors separately?
/* if (!is_dir($rootPath.'wp-content/uploads/test/')){mkdir($rootPath.'wp-content/uploads/test/');}
$seoCacheFile = fopen($rootPath.'wp-content/uploads/test/'.$query.".txt",'w');
fwrite($File, $retarr);fclose($File);
*/
}
Or do I need to move the write operation out of the php and create a second ajax call, passing the json to it?
You need to display from being displayed with ini_set('display_errors', 'Off'); at the top of your script. You should then log all errors by putting this at the top:
ini_set('log_errors','On');
ini_set('error_log','path-to-phperror-log.log');
You then need to handle the possible error in your code, sending back the appropriate information if an error is encountered. For example:
json_encode(array('result' => 'error', 'error' => 'File I/O error.'));
Also, make sure $query is escaped properly. You don't want someone passing in a path like ../../../wp-login.php.
I am attempting to create a simple comment reply to posts on a forum using the AJAX function in jQuery. The code is as follows:
$.ajax({type:"POST", url:"./pages/submit.php", data:"comment="+ textarea +"& thread="+ currentId, cache:false, timeout:10000,
success: function(msg) {
// Request has been successfully submitted
alert("Success " + msg);
},
error: function(msg) {
// An error occurred, do something about it
alert("Failed " + msg);
},
complete: function() {
// We're all done so do any cleaning up - turn off spinner animation etc.
// alert("Complete");
}
});
Inside the submit.php file I have this simple if->then:
if(System::$LoggedIn == true)
{
echo "Yes";
} else {
echo "No";
}
This call works on all other pages I use on the site, but I cannot access any of my variables via the AJAX function. I've tested everything more than once and I can echo back whatever, but anytime I try to access my other PHP variables or functions I just get this error:
Failed [object XMLHttpRequest]
Why am I unable to access my other functions/variables? I must submit the data sent into a database inside submit.php using my already made $mySQL variable, for example. Again these functions/variables can be accessed anywhere else except when I call it using this AJAX function. After hours of Googling I'm just spent. Can anyone shed some light on this for me? Many thanks.
The PHP script that you have only returns a single variable. Write another script that that returns JSON or if you are feeling brave XML. below is a quick example using JSON.
In your javascript
$.ajax({
type: 'GET'
,url: '../pages/my_vars.php'
,dataType: 'json'
,success: function(data){
// or console.log(data) if you have FireBug
alert(data.foo);
}
});
Then in the php script.
// make an array or stdClass
$array = array(
'foo' => 'I am a php variable'
,'bar' => '... So am I'
);
// Encodes the array into JSON
echo json_encode($array);
First thing, you have a space in the Data Parameter String for the URL - will cause problems.
Secondly, your success and error functions are referencing a variable msg. It seems you are expecting that variable to be a string. So, the question then becomes - What is the format of the output your PHP script at submit.php is producing?
A quick read of the jQuery API suggests that, if the format of the response is just text, the content should be accessible using the .responseText property of the response. This is also inline with the response you say you are getting which states "Failed [object XMLHttpRequest]" (as you are trying to turn an XHR into a String when using it in an alert.
Try this:
$.ajax( {
type: "POST" ,
url: "./pages/submit.php" ,
data: "comment="+ textarea +"&thread="+ currentId ,
cache: false ,
timeout: 10000 ,
success: function( msg ) {
// Request has been successfully submitted
alert( "Success " + msg.responseText );
} ,
error: function( msg ) {
// An error occurred, do something about it
alert( "Failed " + msg.responseText );
} ,
complete: function() {
// We're all done so do any cleaning up - turn off spinner animation etc.
// alert( "Complete" );
}
} );