PHP/AJAX only works when something gets echoed? - javascript

I'm trying to include the Wordpress blog header in a php file to use it as an AJAX call function.
define('WP_USE_THEMES',false);
echo 'Something';
require(explode("wp-content",realpath(dirname(__FILE__)))[0].'wp-blog-header.php');
Original snippet found in: Wordpress include("../../../wp-blog-header"); failing, current by Ole Sauffaus.
The code only works when there is something echoed or printed between the define and the require function. Without it the server responds with a 404-error.
This behavior occurs only when I target the php via an AJAX request as follows.
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('directory_results').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "http://localhost:8888/appsconnected/wp-content/themes/appsconnected/ajax-loop.php");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("platform=" + platforms + "&category=" + category + "&orderby=" + order);
What causes this behavior?

Try this:
<?php
define('WP_USE_THEMES',false);
require(explode("wp-content",realpath(dirname(__FILE__)))[0].'wp-blog-header.php');
?>

Related

Ajax fails to find PHP file location

I have a simple code in a Javascript file that calls a PHP file using Ajax. At the moment it's a simple call and I don't need to pass any variables.
I'm using IIS and the folders structure is the following:
ROOT > sendMail.php
ROOT > JS > chat.js
The call starts from chat.js and it's the following:
function sendEmail(params){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("POST", "sendMail.php?q=" + params, true);
xmlhttp.send();
}
But I receive "404 Not Found". Someone can help me?
Thanks in advance!

XMLhttprequest.send() doesn't send variables to PHP

I have this code.
JAVASCRIPT
function removeAndReplace(id, sezione){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert(xhttp.responseText);
}
}
xhttp.open("POST", "removeAndReplace.php", true);
xhttp.send("id=" + id + "&sezione=" + sezione);
}
PHP
print_r($_POST);
$id = $_POST['id'];
$sezione = $_POST['sezione'];
.
.
.
HTML
<input type="button" value="Elimina" class="btn_elimina" onClick="removeAndReplace(1, 'Shopping')">
I want to call a PHP function after the button click so I read that the better way is to use AJAX.
Firefox and Chrome return this error message:
Array
(
)
Notice: Undefined index: id in C:\pweb\tools\xampp\htdocs\Bazaar\php\removeAndReplace.php on line 6
Notice: Undefined index: sezione in C:\pweb\tools\xampp\htdocs\Bazaar\php\removeAndReplace.php on line 7
Line 6 is: $id = $_POST['id'];
Line 7 is: $sezione = $_POST['sezione'];
Where am I going wrong?
You are dumping your data into the request body without telling the server how it is formatted.
Since PHP doesn't know you have sent it data in an encoding it understands, it ignores the request body.
You need to add:
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
… before you send the request.
Aside
While your hard coded data is free of special characters, it is best practice to encode your data. This will save you headaches in the future:
xhttp.send("id=" + encodeURIComponent(id) + "&sezione=" + encodeURIComponent(sezione));
You can save yourself the trouble of manually encoding the data and having to set your own content-type by using the FormData API:
var data = new FormData();
data.append("id", id);
data.append("sezione", sezione);
xhttp.open("POST", "removeAndReplace.php", true);
xhttp.send(data);

POST value from JavaScript to PHP via AJAX without jQuery

I'm trying to send a JavaScript variable to be processed server-side by PHP then echo back the result. My ajax request results in readyState == 4 and status == 200 yet PHP keeps echoing back an empty array/value.
I'm pretty sure this comes from my Ajax call sending an empty request but everything I tried didn't work, so maybe I'm going all wrong here.
JS (from index.html) :
var valueToSend = Math.random();
var request = false;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
function send_ajax() {
if (request) {
request.open('POST', 'test.php', true);
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
}
}
request.send(valueToSend); //this line is probably not sending the value the way I expect it to
}
}
PHP (from test.php) :
echo $_POST['name']; //simple echo to check if PHP indeed receives valueToSend
My last try was to change request.send(valueToSend); with .send(encodeURI('name=' + valueToSend)); but it just made the ajax call redirect the page location to a non-existing one.
What am I doing wrong ?
There are few things wrong in your code, such as:
Even through you defined send_ajax() function, you didn't call it anywhere in the code.
With POST request you need to send an HTTP header setRequestHeader() along with the request, like this:
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
echo $_POST['name']; in test.php page won't work because name is undefined here. Your send() method call should be like this:
request.send("name="+valueToSend);
So the complete JavaScript code would be like this:
var valueToSend = Math.random();
var request = false;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
function send_ajax() {
if (request) {
request.open('POST', 'test.php', true);
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
}
}
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send("name="+valueToSend);
}
}
send_ajax();

Using AJAX to execute a PHP script through a JavaScript function

I have an anchor link with no destination, but it does have an onClick event:
<li><a href onClick='deletePost()'> Delete </a> </li>
I understand that I cannot directly execure PHP code blocks in JavaScript due to the nature of PHP and it being a server side language, so I have to utilize AJAX to do so.
When the delete link is clicked, I need it to execute this query (del_post.php)
<?php include("connect.php");
$delete_query = mysqli_query ($connect, "DELETE FROM user_thoughts WHERE id = 'id' ");
?>
I have tried to understand AJAX using similar past questions, but due to being relatively new, I cannot completely grasp it's language. Here is what I have tried:
function deletePost() {
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
xmlhttp.open("GET", "del_post.php", false);
xmlhttp.send();
}
}
}
But clicking the link just changes the URL to http://localhost/.
I believe the (main) problem is your empty "href" attribute. Remove that, or change it to href="#" or old school href="javascript:void()" (just remove it, imo).
It's been a while since I used XMLHttpRequest and not something like jQuery's .ajax, but I think you need to do it like so (mostly you need to .open/send before you watch for the state change):
var xmlHttpReq = new XMLHttpRequest();
if (xmlHttpReq) {
xmlHttpReq.open('GET', 'your-uri-here.php', true/false);
xmlHttpReq.onreadystatechange = function () {
if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
console.log('success! delete the post out of the DOM or some other response');
}
else {
console.log('there was a problem');
}
}
xmlHttpReq.send();
}
Can you please provide your : del_post.php file?
Normally you can show a text or alert in a
<div id="yourname"></div>
by using callback in an AJAX request :
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("yourname").innerHTML = xmlhttp.responseText;
}
This response is coming from your PHP file for example :
function remove_record(ARG){
if ($condition==true)
echo "TRUE";
else
echo "FALSE";
}
You should remove href attribute from anchor tag and style the element with CSS.
Also, your script should look like this:
<script>
function deletePost() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Do something if Ajax request was successful
}
};
xhttp.open("GET", "del_post.php", true);
xhttp.send();
}
</script>
You are trying to make the http request inside the callback.
You just need to move it outside:
function deletePost() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "del_post.php", false);
xmlhttp.send();
}
Removing the href attribute will prevent the refresh. I believe that is valid in HTML5.
Ok... I'm just a hobbyist, so please forgive me any inaccuracies in the typing but this works: A format I use for an ajax call in an <a> element is:
<a href="javascript:" onclick="functionThatReallyCallsAjax()">
So that I have more flexibility(in case I need to check something before I send the ajax). Now, for an ajax call you need:
What file to call
What to do with the response from the file you called
What to do if an I/O error happens
So we have this function - not mine, leeched amongst thousands from somewhere - probably here :) - and probably well known, my apologies to the author, he is a genius: This is what you call for the ajax thing, where 'url' is the file you want to 'ajax', 'success' is the name of the function that deals with results and error is the name of the function that deals with IO errors.
function doAjaxThing(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
You will naturally need to include the success+error functions:
function dealWithResponse(textFromURL)
{
//textFromURL is whatever, say, a PHP you called in the URL would 'echo'
}
function ohNo()
{
//stuff like URL not found, etc.
alert("I/O error");
}
And now that you're armed with that, this is how you compose the real call inside the function you called at the <a>:
function functionThatReallyCallsAjax()
{
//there are probably many scenarios but by having this extra function,
//you can perform any processing you might need before the call
doAjaxThing("serverFile.php",dealWithResponse,ohNo);
}
One scenario might be when you need to pass a variable to the PHP you didn't have before. In this case, the call would become:
doAjaxThing("serverFile.php?parameter1=dogsRock",dealWithResponse,ohNo);
And now not only you have PHP sending stuff to JS, you have JS sending to PHP too. Weeeee...
Final words: ajax is not a language, its a javascript 'trick'. You don't need to fully understand what the first 'doAjaxThing' function does to use this, just make sure you are calling it properly. It will automatically 'call' the 'deal WithResponse' function once the response from the server arrives. Notice that you can continue doing your business (asynchronous - process not time-tied) till the response arrives - which is when the 'deal WithResponse' gets triggered -, as opposed to having a page stop and wait (synchronous - time tied) until a response arrives. That is the magic of ajax (Asynchronous JAvascript and Xml).
In your case you want to add the echo("success") - or error! - in the PHP, so that the function 'dealWithResponse' knows what to do based on that info.
That's all I know about ajax. Hope this helps :)

My data posts to a new page rather than the specified div

Why does my post data appear on a new blank page rather than the div I specified? This script is in the head of a page called order.php. I want the data submitted to be written in the "message" div I created on order.php. But when I submit, I am redirected to update.php where the data is written on a blank page.
<script type="text/javascript">
function insert() {
if (window.XMLHttpRequest) {
xmlhttp = new XLMHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("message").innerHTML = xmlhttp.responseText;
}
}
parameters = 'child_name'+document.getElementById('child_name').value;
xmlhttp.open('POST', 'update.php', true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(parameters);
}
</script>
you current page is order.php and your posting it to update.php by doing this xmlhttp.open('POST', 'update.php', true);
This might be due to normal form submission event.
use a simple jquery
$("#form").submit(function(){
$.post("update.php",{paramertes:'child_name_'+$("#child_name").val()},function(data){
$("#message").html(data);
})
return false;//don't forget to use this
})

Categories