JQuery/AJAX Unable to Get Response from PHP file - javascript

I am trying to run a server side python script for my wordpress site. I can call the python file inside a php function and run it on the site as shortcode. So, the php file is working. The issue I am having is building my JQuery and getting the response from the php file. I am trying to do a hello_world set-up to debug the issue
AJAX Query:
function myFunction() {
alert("Testing button");
}
function HelloWorldShortcode() {
jQuery(document).ready(function($) {
$.ajax({
dataType: 'json',
method: 'POST',
url: "http://localhost/wp-content/helloworld.php",
data: {
action: 'helloworld'
},
error: function(data) {
alert("bad");
},
success: function(response) {
alert(response);
}
});
})
}
and the php file:
<?php # -*- coding: utf-8 -*-
ini_set('display_errors', 1);
function hello_world() {
$test = 'hello';
return $test;
}
if (isset($_POST['helloworld'])) {
return hello_world();
}
I have also tried using GET instead of POST. When I access the php file in the browser I do not get any errors and the success part of the ajax query is being reached, as i do not get any error messages. What can I do to access the hello_world() function inside of the php file and display the output?
Thanks

You are using the value of the parameter, not the parameter itself...
if (isset($_POST['action'])) {
echo hello_world();
// Or json_encode(hello_world()); for returning an Array
}
or
if ($_POST['action'] == 'helloworld') {
return hello_world();
// Or json_encode(hello_world()); for returning an Array
}

You would do something like:
if (isset($_POST['helloworld'])) {
echo hello_world();
// Or json_encode(hello_world()); for returning an Array
}

Related

Wordpress Ajax is Returning a Fatal Error

I am trying to make an AJAX call in a child theme I am playing around with, and I am receiving the following error:
Fatal error: Call to undefined function add_action() in
Basically my ajax call goes to functions.php file and in the functions.php I am requiring once the file (ajax.php) with the PHP logic. If in ajax.php file all i am doing is echoing a string, it works fine, but if I try to use an add_action function, it then returns the Fatal Error.
Here is some code.
JS:
$.ajax({
url: 'url to functions.php file',
data: {'my-ajax': 'something'},
type: 'POST',
cache: false,
success: function(data, status) {
if(status == "success") {
$('.container').append(data);
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
});
PHP - functions.php File:
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
if($_POST['my-ajax'] != "") {
require_once('prod-cats.php');
die();
}
}
PHP - ajax.php:
add_action( 'testing_ajax', 'testing_ajax_func' );
function testing_ajax_func(){
echo "Hey There";
}
The above code fails, but if I remove everything from the ajax.php file and leave behind the echo, it then works.
What is it with the add_action function that is causing the issue?
Thanks.

Retrieve JSON return from PHP called from AJAX

I'm trying to call an PHP file via POST and retrieve its result back in the calling AJAX code. But unfortunately it doesn't seem to work. After fiddling around with my code I either get "undefined", "a page reload" or "an error in the console that my parameter used in the success function isn't defined"
Here's the ajax code:
function postComment(formdata) {
if (formdata.comment != '') {
$.ajax({
type: 'POST',
url: '../../includes/post_comment.php',
data: formdata,
headers: {
'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'
},
success: postSuccess(data), // function to handle the return
error: postError // function to handle errors
});
} else {
alert('Empty please write something!');
}
}
function postSuccess(data) {
console.log(data);
$('#commentform').get(0).reset();
displayComment(data);
}
and here is my PHP handler:
$ajax = ($_SERVER['REQUESTED_WITH'] === 'XMLHttpRequest');
$added = add_comment($mysqli, $_POST); // contains an array
if ($ajax) {
sendAjaxResponse($added);
} else {
sendStandardResponse($added);
}
function sendAjaxResponse($added)
{
header("Content-Type: application/x-javascript");
if ($added) {
header('Status: 201');
echo(json_encode($added));
} else {
header('Status: 400');
}
}
this is what added looks like in PHP:
$added = array(
'id' => $id,//integer example: 90
'comment_post_ID' => $story_ID, //integer example: 21
'comment_author' => $author, //String example: Dominic
'comment' => $comment, //String example: This is a comment
'comment_date' => $date); //DateTime/String example: 08/02/2016 1970-01-01 00:00:00
UPDATES
I changed the ajax code to the following:
$.ajax({
type: 'POST',
url: '../../includes/post_comment.php',
success: postSuccess,
data: formdata,
headers: {
'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'
},
error: postError,
});
Now I get the full HTML-Code of the page calling this ajax function
I tried to set aysnc: false in the ajax request but it didn't help, always getting the html code of the source (calling the ajax function).
As for now I´m moving to a different approach which doesn´t need the return data. But thanks for the help
The browser tries execute server response because of
header("Content-Type: application/x-javascript");
change to
header("Content-Type: application/json");

Ajax post not received by php

I have written a simple code. In order to avoid flooding a JSON server, i want to break up the JSON response in pieces. So my jquery code should be parsing one variable ("page") to the php page that handles the JSON Oauth Request. On success, it should append the DIV with the latest responses.
My code should be working, except for the fact that my ajax post is not being received by my php file.
Here goes
archief.html
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: page,
success: function() {
console.log(page);
$.get("trytocombinenewageandgettagsendates.php", function(archief) {
$('#archief').append(archief);
});
},
error: function(err) {
alert(err.responseText);
}
});
return false;
});
The php file doesn't receive anything.
var_dump($_POST);
gives me array(0) { }.
Very strange, i'd really appreciate the help!
You are sending a string instead of key-value pairs. If you want to use $_POST you need to send key-value pairs:
...
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function() {
...
If you send a single value or string, you would need to read the raw input.
Also, you are sending 2 GET requests and 1 POST request to the same file. Is that intentional? Note that only the POST request will have the $_POST variable set.
Thank you for your help and not letting me post "this still doens't work" posts :)
I made the mistake of loading the "unConsulted" php file [$.get("trytocombinenewageandgettagsendates.php"] upon success. Instead, i append the response of the PHP.
The working code below:
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
//$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function(response){
$("#archief").append(response);
},
error: function(err) {
alert(err.responseText);
}
});
return false;

Calling a C# method from JavaScript

I want to to call a method GetAccount from my controller AccountController.cs, in my JavaScript factory LoginFactory.js. Something like this:
AccountController.cs:
public Account GetAccount(string userName)
{ ... }
LoginFactory.js:
if(x>y) {
var account = <%AccountController.GetAccount(someParam);%>
}
I've tried using [WebMethod] and Ajax, but I can't get it to work: I get a 404 response.
Assuming your GetAccount method can be reached at /Account/GetAccount when your application runs, you could use the following:
$.ajax({
type: 'GET',
url: '/Account/GetAccount',
data: { 'username' : 'a-username' },
dataType: 'json',
success: function(jsonData) {
alert(jsonData);
},
error: function() {
alert('error');
}
});
Note - this is dependant on jQuery.
This causes the browser to make a request to /Account/GetAccount as if you had done so by entering the URL in the URL bar, but of course, captures the returned json for use in your client side (javascript) script.
If this returns a 404, it would be worth checking your routing.

Jquery ajax call a php script with require once

I have an ajax request like :
$.ajax({
type: "GET",
url: "services/Test.class.php",
data: "call=getTest",
success: function (data) {
alert(data);
},
error: function (response) {
alert("Error getting php file");
}
});
So, in my class ( Test.class.php ), I have a getTest() function and a require_once('OtherPHP'),
When I test this code, I have an error in require once :
No such file or directory
in my alert(data)
how can I fix it?
It seems like you've included a wrong path of OtherPHP file in Test.class.php. Use file_exists() function to make sure that given path really exists before including/requiring in Test.class.php
if (file_exists(`OtherPHP.php`)) {
require_once(`OtherPHP.php`)
} else {
echo "The file `OtherPHP.php` does not exist";
}
You cant able to call the class directly from ajax,
create new php file say test.php
in test.php
include("Test.class.php");
$test = new Test();
$test ->getTest(); //print the getTest outpout here
Javascript:
$.ajax({
type: "GET",
url: "test.php",
.....

Categories

Resources