$HTTP_RAW_POST_DATA Error - Not posting data - javascript

I am trying to perform an AJAX request through jquery-confirm plugin loading the file data from a form through its ajax-load function and then updating the information to a PHP file and ultimately to a database.
However, this is resulting in the following error.
Deprecated: Automatically populating $HTTP_RAW_POST_DATA is deprecated and will be removed in a future version. To avoid this warning set 'always_populate_raw_post_data' to '-1' in php.ini and use the php://input stream instead. in Unknown on line 0
Warning: Cannot modify header information - headers already sent in Unknown on line 0
I have attempted to even throw in a blank variable as the meaning of this error is it not POSTing the data across to the page. This simply throws back an undefined index, confirming that it isn't posting the data.
Some posts on this site have said to change the php.ini files etc, as I am using a university server, we do not have access to change these files.
Here is my JS file which is performing the AJAX function
function addSubject(){
$("#addBtn").on('click', function() {
$.confirm({
title: 'Manage Subjects',
content: 'url: addSubjectForm.html',
buttons: {
addSubject: {
text: 'Add New Subject',
btnClass: 'btn-info',
action: function () {
var findSubject = this.$content.find('input#newSubject');
var findDescript = this.$content.find('input#newDescript');
var newSubject = findSubject.val();
var newDescript = findDescript.val();
if (newSubject === '' || newDescript === '') {
$.alert({
content: 'One of the fields from the form was empty',
type: 'red'
});
return false;
} else {
$.ajax({
url: "../ajax/admin/addSubject.php",
type: "POST",
data: {title: newSubject, description: newDescript, blank: 'blank'},
cache: false,
contentType: false,
processData: false,
success: function (result) {
$.alert({
content: result,
type: 'green'
});
}
});
console.log(newSubject + " " + newDescript);
}
}
},
close: {
text: 'Close',
btnClass: 'btn-danger'
}
}
});
});
}
The PHP page where I access the variables is here:
<?php
$title = filter_input(INPUT_POST, "title");
$description = filter_input(INPUT_POST, "description");
$test = $_POST['blank'];
echo $test;
echo "$title $description";
The blank variable in these files are simply for testing purposes only.
Thanks in advance.

As said in the warning $HTTP_RAW_POST_DATA is deprecated, instead use:
$raw_post_body = file_get_contents("php://input");
For reading raw body content.
But from what I can see in JS code you're sending a normal www-url-encoded form so use of $_POST is recommended.
If it still doesn't work, please do a var_dump or print_r on $_POST so you can debug if really nothing is sent over POST request.

Try :
$title = filter_input(INPUT_POST, 'title', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
$description = filter_input(INPUT_POST, 'description', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);

Related

if else statement in AJAX success

This is how i am trying to check json data. If the data inserts correctly i want the mentioned jquery in success code. But if it is not inserted then i want else code to run. But the if else conditions are not working properly.I am including php code and ajax code which i have tried. Am i doing it right?
AJAX
$( "#frm_add" ).on('submit',(function(e) {
e.preventDefault();
var img= new FormData(this);
datas = $("#frm_add").serializeArray();
$.each(datas,function(key,input){
img.append(input.name,input.value);
});
$.ajax({
url: "response_categories.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
//data:new FormData(this),
data:img,
// data: {img:img,datas:datas}, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data) // A function to be called if request succeeds
{
if(data == true)
{
$('#add_model').modal('hide');
$("#categories_grid").bootgrid('reload');
}
else
{
$("#nameerr").html("<p id='error' style='color:red'>"+data+"</p>");
}
}
});
}));
php
function insertCategories($params)
{
$fileName = $_FILES['cat_image']['name'];
$name = $params['cat_name'];
$type = $params['cat_type'];
$switch = $params['cat_switch'];
$chk=mysqli_query($this->conn,"select * from categories where cat_name='$name'");
if(mysqli_num_rows($chk)==0)
{
$sql = "INSERT INTO `categories` (cat_name,cat_image, cat_type, cat_switch) VALUES('$name','$fileName', '$type','$switch'); ";
echo $result = mysqli_query($this->conn, $sql) or die("error to insert Categories data");
if ($result) {
if (file_exists("images/" . $_FILES["cat_image"]["name"])) {
echo $fileName . " <span id='invalid'><b>already exists.</b></span> ";
} else {
$sourcePath = $_FILES['cat_image']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "images/" .$fileName; // Target path where file is to be stored
move_uploaded_file($sourcePath, $targetPath); // Moving Uploaded file
}
}
echo json_encode($result);
}
}
Add the error command in your ajax call to execute if the command fails or returns no data in general
$.ajax({
url: "response_categories.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data:img,
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data), // A function to be called if request succeeds
{
if(data)
{
$('#add_model').modal('hide');
$("#categories_grid").bootgrid('reload');
}
else
{
$("#nameerr").html("<p id='error' style='color:red'>"+data+"</p>");
}
}
error: function (data)
{
$("#namerr".html("<p id='error' style='color:red'>"+data+"</p>");
}
});
I think You have problem with response convention: Sometimes You call die() method (PHP: 12 line), sometimes You call json_endcode() (PHP: 25 line), sometimes echo with plain string.
In this type of actions You should:
Always output JSON from backend script. Mixing response types is really pain in the ass, it's hard to parse and test.
Use response object with uniform structure - that might help with building complex applications and easy to modify
Example pseudocode:
PHP
if($success) {
die(json_encode([
'error' => false,
'message' => 'Thank You',
'data' => $some_extra_data
]));
} else {
die(json_encode([
'error' => true,
'message' => 'Sorry',
'data' => $some_extra_data
]));
}
Then in ajax.success() method, its really easy to handle:
success: function (data) {
try {
var response = JSON.parse(data)
if(response.error == true) {
$('#nameerr').text(response.message)
} else {
$('#add_model').modal('hide');
$("#categories_grid").bootgrid('reload');
}
} catch (err) {
alert('Sorry. Server response is malformed.')
}
}

How to get variable from javascript to php without form?

I'm trying to pass my topic variable from this javascript function to my php file faqs.php. I know you can do this with a form, however this function is called when clicking text on the html page. I've tried AJAX but it didn't work for me and I feel like there must be a simpler way.
getFaqs function:
function getFaqs(topicId, topic) {
$("#topic-container").html("");
//insert javascript to send 'topic' to php file here
$.getJSON("faqs.php", function(data) {
if(data == "") {
$("<div>", {class: "list-group-item", text: "Please add FAQs."}).appendTo($("#topic-container"));
}
$.each(data, function(faqId, faq){
$("<div>", {id: "faq" + faqId, class: "list-group-item", text: faq}).appendTo($("#topic-container"));
});
});
return false;
}
faqs.php:
<?php
header('Content-Type: application/json; charset=utf-8');
//insert some php to get 'topic' here
if(isset($_POST['topic'])){
$topic=$_POST['topic'];
$clean_topic = preg_replace('/\s+/', '', $topic);
}else{
echo json_encode("Please enter a topic!");
}
$musicalinstruments = array("Question1"=>"What is the best musical instrument in the world?", "Answer1"=>"The English concertina", "Question2"=>"How many double bass players does it take to change a light bulb?", "Answer2"=>"None, the piano player can do that with his left hand");
$programminglanguages = array("Question"=>"Why do programmers confuse halloween and christmas?", "Answer"=>"Because Oct 31 = Dec 25");
$varietiesofpizza = array("Question"=>"Should I eat more pizza?", "Answer"=>"Yes. Always.");
echo json_encode ($topic);
?>
Insert topic as GET variable in javascript
$.getJSON("faqs.php?topic=sometopic", function(data) {
And then read that GET variable in PHP
if(isset($_GET['topic'])){
$.getJSON makes a GET request while $.ajax is the main component to send and communicate with the server. Here's a rough code that would do this just fine.
$.ajax({
url: 'faqs.php',
type: 'POST',
dataType: 'json',
data: { topic: topics }, // topics is your topics varaible from the JS scope
success: function(data) {
if (data == "") {
$("<div>", {
class: "list-group-item",
text: "Please add FAQs."
}).appendTo($("#topic-container"));
}
$.each(data, function(faqId, faq) {
$("<div>", {
id: "faq" + faqId,
class: "list-group-item",
text: faq
}).appendTo($("#topic-container"));
});
},
error: function(xhr) {
console.log('error :(');
}
});
you can send it by url here is the code for it xmlhttp.open("GET", "phpFile.php?q=" + str, true);
xmlhttp.send();
where q is he variable which is used to access the value of perticular variable ,str in this case, in php file
If you want use POST:
$.post('test.php', { name: "Anna" }, function(response) {
// Do something with the request, data is JSON object.
}, 'json');
And read in test.php in POST variable.
$_POST['name'] // Anna

Javascript call PHP function

I am editing wordpress post template. And I want to call the PHP function in javascript, but my code doesn't work.
Here is what I want to do. When the user click the OK button, it should be showed a alert box when calling the PHP function success or failed.
Here is my js code:
(function() {
tinymce.PluginManager.add('facebook_api_tinymce', function( editor, url ) {
editor.addButton( 'facebook_api_tinymce',
{
title: 'Set friend condition',
text: 'Condition',
type: 'menubutton',
menu:
[
{
text: 'Friend',
onclick: function() {
editor.windowManager.open( {
body:[
{
type: 'textbox',
name: 'textboxName',
label: 'Set friend',
value: '20'
}
],onsubmit: function( e ) {
$.ajax({
url: 'databaseConnection.php',
type: 'GET',
data: {functionname: 'updateDatabase', post_id: 1, no_friend: 2},
error:function(){
alert("failed");
},
success: function(data) {
alert("success");
console.log(data); // Inspect this in your console
}
});
}
});
}
}
]
});
});
And here is my PHP code:
<?php
$post_id = 0;
$no_friend = 0;
//Check did it pass the functionName
if( !isset($_POST['functionname']))
$error = 'No function name!';
//Check did it pass the Post id
if( !isset($_POST['post_id']) )
$error = 'No function post_id!';
else {
$post_id = $_POST['post_id'];
}
//Check did it pass the no_friend
if( !isset($_POST['no_friend']) )
$error = 'No function no_friend!';
else{
$no_friend = $_POST['no_friend'];
}
//If no data are missed
if( !isset( $error) ) {
switch($_POST['functionname']) {
case 'updateDatabase':
updateDatabase(intval($post_id), intval($no_friend));
break;
default:
$error = 'Not found function '.$_POST['functionname'].'!';
break;
}
}
function updateDatabase($post_id, $no_friend)
{
$ans = $post_id + $no_friend;
echo $ans;
}
echo $error;
It should show an alert box. What I am going wrong?
What do you get back from you Ajax call? So what does this
console.log(data); // Inspect this in your console
actually show? If it's a whole built up Wordpress page, then maybe your PHP functions work, but they are never executed. This might be due to .htaccess rewrites and such.
You are using Type:"GET" in ajax but you are trying to get value in php using POST
Just Change Your Type:"GET" to Type:"POST" in ajax or
Change POST to GET in php code

Bootstrap 2.2.1 Typeahead

PHP, returns a JSON encoded array
$this->load->model('car_model', 'cars');
$result = $this->cars->searchBrand($this->input->post('query'));
$this->output->set_status_header(200);
$this->output->set_header('Content-type: application/json');
$output = array();
foreach($result as $r)
$output['options'][$r->brandID] = $r->brandName;
print json_encode($output);
Outputs: {"options":{"9":"Audi","10":"Austin","11":"Austin Healey"}}
JS updated:
$(".searchcarBrands").typeahead({
source: function(query, typeahead) {
$.ajax({
url: site_url + '/cars/search_brand/'+query,
success: function(data) {
typeahead.process(data);
},
dataType: "json"
});
},
onselect: function(item) {
$("#someID").val(item.id);
}
});
UPDATE: Uncaught TypeError: Object function (){return a.apply(c,e.concat(k.call(arguments)))} has no method 'process'
If I type just 'A' then typeahead shows me only the first letter of each result (a bunch of A letters). If I type a second letter I see nothing anymore.
I've tried JSON.parse on the data or using data.options but no luck.
What am I doing wrong?
I've been battling this for the last day with Bootstrap 2.2.1. No matter what I did, it would not work. For me, I always got the process undefined error unless I put a breakpoint in the process function (maybe just because FireBug was open?).
Anyway, as a patch I re-downloaded Bootstrap with typeahead omitted, got the typeahead from here:
https://gist.github.com/2712048
And used this code:
$(document).ready(function() {
$('input[name=artist]').typeahead({
'source': function (typeahead) {
return $.get('/7d/search-artist.php', { 'artist': typeahead.query }, function (data) {
return typeahead.process(data);
});
},
'items': 3,
'minLength': 3
},'json')
});
My server returns this (for 'Bo'):
["Bo","Bo Burnham","Bo Diddley","Bo Bruce","Bo Carter",
"Eddie Bo","Bo Bice","Bo Kaspers Orkester","Bo Saris","Bo Ningen"]
Of course, now it ignores my minLength, but it will get me through the day. Hope this helps.
EDIT: Found the solution here:
Bootstrap 2.2 Typeahead Issue
Using the typeahead included with Bootstrap 2.2.1, the code should read:
$(document).ready(function() {
$('input[name=artist]').typeahead({
'source': function (query,typeahead) {
return $.get('/search-artist.php', { 'artist': encodeURIComponent(query) }, function (data) {
return typeahead(data);
});
},
'items': 3,
'minLength': 3
},'json')
});
Here's what I do to facilitate remote data sources with bootstrap's typeahead:
$("#search").typeahead({
source: function(typeahead, query) {
$.ajax({
url: "<?php echo base_url();?>customers/search/"+query,
success: function(data) {
typeahead.process(data);
},
dataType: "json"
});
},
onselect: function(item) {
$("#someID").val(item.id);
}
});
And then you just need to make sure your JSON-encoded arrays contain a value index for the label and an id field to set your hidden id afterwards, so like:
$this->load->model('car_model', 'cars');
$brands = $this->cars->searchBrand($this->uri->segment(4));
$output = array();
foreach($brands->result() as $r) {
$item['value'] = $r->brandName;
$item['id'] = $r->brandID;
$output[] = $item;
}
echo json_encode($output);
exit;
$.post is asynchronous, so you can't user return in it. That doesn't return anything.

Sencha Touch ScriptTagProxy only works on localhost and not pulling a remote source?

I have been spending a few days trying to get my Sencha Touch application to work, so that it uses a JSON feed to populate a news table, the code below now works fine on localhost but as soon as I change the line
url: 'http://localhost/list.php',
to a remote server:
url: 'http://www.myserver.com/list.php',
The application then fails to load and always hits the timeout listener, I have tried increasing the timeout listener to 20000 but still it does not load?
console.log(response.responseText); also fails to display anything.
Thanks Aaron
Ext.regStore('NotesNewsStore', {
model: 'NoteNewsModel',
offLineStore: new Ext.data.Store({
model: 'photo',
proxy: {
type: 'localstorage',
id: 'notes-app-store1'
}
}),
proxy: {
type: 'scripttag',
url: 'http://localhost/list.php',
reader: new Ext.data.JsonReader({
}),
timeout:1000,
listeners: {
exception: function(proxy, response, operation) {
console.log("I Think we are offline");
console.log(response.status);
console.log(response.responseText);
}
}
}
});
Check if the remote server is configured to be used with script tag, for example:
$callback = $_REQUEST['callback'];
// Create the output object.
$output = array('a' => 'Apple', 'b' => 'Banana');
//start output
if ($callback) {
header('Content-Type: text/javascript');
echo $callback . '(' . json_encode($output) . ');';
} else {
header('Content-Type: application/x-json');
echo json_encode($output);
}

Categories