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
Related
I have been trying to work this out for hours now and cannot find any answer that helps me.
This is the code in my javascript file
function sendMovement(cel) {
var name = "test";
$.ajax({
type: 'POST',
url: '../game.php',
data: { 'Name': name },
success: function(response) {
console.log("sent");
}
});
}
This is the code from my PHP file (it is outside the js file)
if($_SERVER["REQUEST_METHOD"] == "POST") {
$data = $_POST['Name'];
console_log($data);
}
When debugging I can see that AJAX is sending a POST and it does print in the console "SENT" but it does not print $data
update: the function console_log() exists in my PHP file and it works
Try getting response in JSON format, for that your js should have dataType:'JSON' as shown below
JS Code:-
function sendMovement(cel) {
var name = "test";
$.ajax({
type: 'POST',
dataType:'JSON', //added this it to expect data response in JSON format
url: '../game.php',
data: { 'Name': name },
success: function(response) {
//logging the name from response
console.log(response.Name);
}
});
}
and in the current server side code you are not echoing or returning anything, so nothing would display in ajax response anyways.
changes in php server code:-
if($_SERVER["REQUEST_METHOD"] == "POST") {
$response = array();
$response['Name'] = $_POST['Name'];
//sending the response in JSON format
echo json_encode($response);
}
I fixed it by doing the following:
To my game.php I added the following HTML code (for debugging purposes)
<p style = "color: white;" id="response"></p>
Also added in my game.php the following
if($_SERVER["REQUEST_METHOD"] == "POST") {
$gameID = $_POST['gameID'];
$coord = $_POST['coord'];
$player = $_POST['player'];
echo "gameID: " . $gameID . "\nCoord: " . $coord . "\nPlayer: " . $player;
}
AND in my custom.js I updated
function sendMovement(cel) {
var handle = document.getElementById('response');
var info = [gameID, cel.id, current_player];
$.ajax({
type: 'POST',
url: '../game.php',
data: {
gameID: info[0],
coord: info[1],
player: info[2]
},
success: function(data) {
handle.innerHTML = data;
},
error: function (jqXHR) {
handle.innerText = 'Error: ' + jqXHR.status;
}
});
}
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);
I am making a plugin for wordpress. The plugin will add a tinymce on the edit post, and it will send the post_id to the database to do some identification later.
In my case, I am writing a javascript, which directory in wordpress\wp-content\plugins\facebook-api\js\shortcode-tinymce-button.js. And now I have no idea how I can get the post_Id in javascript.
Here is what I am doing:
user click the OK button will send the post_Id and the text box value to the database.
Here is my 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 ) {
var $hi = "php echo get_the_ID();";
alert($hi);
$no_friend_e = parseInt(e.data.textboxName);
//Pass the value the PHP file, which is doing the database update.
jQuery.ajax({
url: 'http://localhost:8080/wordpress/wp-content/plugins/facebook-api/js/databaseConnection.php',
type: 'POST',
data: {functionname: 'updateDatabase', post_id: '1', no_friend: $no_friend_e},
error:function(data){ //When Can't call the PHP function
alert("failed");
console.log(data);
},
success: function(data) { //update data successful
alert("success");
console.log(data); // Inspect this in your console
}
});
}
});
function get_post_content(id){ //Didn't use
return document.getElementById("post-"+id).innerHTML;
}//you should probably use textContent/innerText but I am not going to get into that here
}
}
]
});
});
Thanks,
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
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.