I want to make an api request in my php file.
But my api request depends on the user's input which will be passed from the front-end.
And in order to do so, my front-end js file is making ajax call to the php file. But php file is keep returning null in its global variable, $_POST.
in function.js file, I have
$.ajax({
type: "POST",
url: "/model/validate.php",
data: data,
dataType: "JSON",
success: function(response){
console.log(response);
},
error: function(response){
console.log("Error: " + response);
}
});
and in my validation.php file i have
<? php
if(is_ajax()){
echo "ajax works"
}
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
is_ajax is a helper function that checks if there was any ajax call.
So every time I run these files, I get error and i'm not sure why.
Once this is done, I plan to make api call using curl in my php file but for some reason, $_POST is always returning null. Can anyone help?
Related
So I am trying to learn AJAX requests, and in testing purposes, I am trying to use it in my personal project. I set up some test functions here and there, to test out how I can use AJAX in my project, and I got on an issue.
I'm making an AJAX call from script tags in my html, but it appears to just return all the html of that page.
AJAX call code is:
$.ajax({
URL: "<?php echo URLROOT;?>tasks/setcompleted",
type: "GET",
data: {id:'3'},
contentType: "application/json; charset=utf-8",
success: function(res){
console.log(res);
}
});
PHP Tasks controllers method setcompleted() code is just a simple echo of data passed from AJAX request via GET:
public function setcompleted(){
if(isset($_GET['id'])){
echo $_GET['id'];
}
}
I did some research, and found similar questions here, that suggested to check the URL that is passed to AJAX request. I did that, the URL that is passed in AJAX request is correct and works, if I manually write it into browser and add necessary parameters for the GET.
Can anyone suggest what am I doing wrong here?
Your function returns nothing.
public function setcompleted()
{
if(isset($_GET['id']))
{
$output = json_encode($_GET['id']);
}
return $output;
}
I am trying to send a "POST" request to my backend PHP code, which resides in functions.php in Wordpress. I get a readystate:4 and bad request(400 status) error when I run the code, if I change the "POST" to "GET" it works.
This is not the first time I encounter this, but previously it has been in my spare time projects, this time it is for work. as mentioned above I can "solve" it by changing the method to "GET", but that is not the method you are supposed to use when you add to your database. I've tried to comment out the lines with "dataType", "contentType", and "processData", but it doesn't make a difference I still just get a bad request(400) error. I have several "GET"s that work fine elsewhere in functions.php and urlen is pointing directly to functions.php.
JS
function AddToTable(){
Data={"action":"CreateProduct","Password":Password.value,"Varenr":Varenr.value,"Produkttype":Produkttype.value,"Navn":Navn.value,"Billede":Billede.value,"BilledeAlt":BilledeAlt.value,"Farve":Farve.value,"Tykkelse":Tykkelse.value,"Pris":Pris.value};
jQuery.ajax({
type: "POST",
url: urlen,
dataType: "json",
contentType: "application/json",
processData: false,
data: JSON.stringify(Data),
success: successfunction,
error: errorfunction,
});
function successfunction(data){
RefreshTable();
}
function errorfunction(data, status) {
alert("error: "+status+" Content: " + JSON.stringify(data));
};
}
Functions.php
<?php
function CreateProduct(){
exit;
}
add_action('wp_ajax_CreateProduct','CreateProduct');
add_action('wp_ajax_nopriv_CreateProduct','CreateProduct');
?>
I expect it to send the data to the server function, so I can do more with it there. But I get a readystate:4 and state 400 errorcode.
UPDATED: to include the Functions.php part of the code.
I guess your data to be posted is malformed.
You have prepared it like
Data={"action":"CreateProduct","Password":Password.value,"Varenr":Varenr.value,"Produkttype":Produkttype.value,"Navn":Navn.value,"Billede":Billede.value,"BilledeAlt":BilledeAlt.value,"Farve":Farve.value,"Tykkelse":Tykkelse.value,"Pris":Pris.value};
Variables to be posted should not be in quotes so your code there should begin like
Data={action:"CreateProduct",Password: Password.value,Varenr: Varenr.value, .....
and so on
A GET request to a URL will simply tell you whether or not it exists, in basic terms. If you send a GET request to cnn.com it will respond with a 200, if send a GET to cnnbootyshort.com, you will get no response.
In your case, rather than using exit, you could try using die(), along with an echo of what you want to send back to the browser.
<?php
function CreateProduct(){
echo "200";
die();
}
add_action('wp_ajax_CreateProduct','CreateProduct');
add_action('wp_ajax_nopriv_CreateProduct','CreateProduct');
?>
And your JS
function successfunction(data){
console.log(data); // for debugging
RefreshTable();
}
function errorfunction(data, status) {
console.log(data); // for debugging
alert("error: "+status+" Content: " + JSON.stringify(data));
};
Alternatively you can use wp_die() if you want to use a Wordpress specific function. Here is some documentation regarding its use.
<?php
function CreateProduct(){
wp_die();
}
add_action('wp_ajax_CreateProduct','CreateProduct');
add_action('wp_ajax_nopriv_CreateProduct','CreateProduct');
?>
I am trying to send some data to my server using an AJAX Post call. However, whenever I run the function containing the ajax call I get a server error. Here is my AJAX call (I am trying to send a string and put it inside json for the purposes of this call):
function sendFileName(){
data_to_send={"name": scriptName};
data_to_send=JSON.stringify(data_to_send);
$.ajax({
url: '/filename',
type: 'POST',
dataType: 'json',
data: data_to_send,
error: function(resp){
console.log("Oh no...");
console.log(scriptName);
console.log(resp);
},
success: function(resp){
console.log('Sent file name!');
console.log(resp);
}
});
}
When I log the scriptName I get it in the console, so the data exists. I'm assuming the issue has to do with the way in which I'm sending it?
Here is the server-side code as well, where when I log the req it shows up as undefined:
app.post("/filename", function(req,res) {
file = req.body.name;
console.log(file);
});
Would really appreciate any help I can get with this!
First I am conface that I am Newbie to php,
I am using jquery(knockout js) at client side & PHP at server side. my code.
Client side: I am using knockout js(Javascript). to call my PHP service.
My Code:
self.VMSaveEditUserMode = function () {
try {
var params = { "ClientData": [controllerVM_.ClientID(), controllerVM_.VMList[0].ClientName(), controllerVM_.VMList[0].ShortName(), controllerVM_.VMList[0].Address(), controllerVM_.VMList[0].CreatedBy(), controllerVM_.VMList[0].CityName(), controllerVM_.VMList[0].PostalCode(), controllerVM_.VMList[0].ContactEmail(), controllerVM_.VMList[0].ContactPhone(), controllerVM_.VMList[0].IsCorporate()] };
$.ajax({
type: "POST",
url: URL + "index.php/phpService/SaveClient/" + controllerVM_.TokenKey(),
data: JSON.stringify(ko.toJS(params)),
contentType: "application/json",
async: true,
dataType: 'json',
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
if (ErrorResponse.statusText == "OK") {
}
else {
alert("ErrorMsg:" + ErrorResponse.statusText);
}
}
});
}
catch (error) {
alert("Catch:" + error);
}
}
Server Side My Code, I am using this PHP code to connect with DB.
PHP Code:
public function SaveClient($userToken)
{
$value = json_decode($Clientdata);
echo $value->ClientData[0];
}
*My Question *:
I am not clear on how to POST data in PHP ? I tried with $_POST[''] method as well as many more.
I am using eclipse as a php framework. so, not able to debug it when i post the data.Normally mode i am able to debug my code.but not from remotely.for that i made changes on php.ini file also.
How to get Response of Post Data on php code ?
How to debug via remote post ?
My Request sample:
suppose i use:
For, data: params, only at that time my request format is.
ClientData%5B%5D=4&ClientData%5B%5D=kamlesh&ClientData%5B%5D=KAM&ClientData%5B%5D=Junagadh&ClientData%5B%5D=me&ClientData%5B%5D=SANTA+ROSA&ClientData%5B%5D=76220&ClientData%5B%5D=kamlesh.vadiyatar%40gmail.com&ClientData%5B%5D=9998305904&ClientData%5B%5D=false
For, data: JSON.stringify(ko.toJS(params)),
{"ClientData":["4","kamlesh","KAM","Junagadh","me","SANTA ROSA","76220","kamlesh.vadiyatar#gmail.com","9998305904",false]}
If I understand correctly you need to create a PHP service which is able to receive REST-like requests from client.
In order to do thad you need to access raw POST data. In PHP its being done like this:
$ClientData = file_get_contents('php://input');
You can read more about php://input in the wrappers documentation.
Of course from the client's side the data need to be sent using the POST method and as raw data, i.e. as a string. You can obtain a string from object using JSON.stringify() which you already do.
If you pass an object, it will be converted to string internally by jQuery using query-string format. More on that in the jQuery documentation for $.ajax (the most importatnt options being data and processData).
Just pass the ajax data param as an object, don't convert it into JSON. Then in PHP use $_POST directly.
Use firebug or chrome dev tools to analyze the ajax request and see which data is sent
Use this simple jquery function to accomplish your task
$.ajax({
type: "POST",
url:"scripts/dummy.php",
data:"tbl="+table,
dataType:"json", //if you want to get back response in json
beforeSend: function()
{
},
success: function(resp)
{
},
complete: function()
{
},
error: function(e)
{
alert('Error: ' + e);
}
}); //end Ajax
in PHP use:
if(isset($_POST['ClientData'])){
$client_data = $_POST['ClientData']
}
now $client_data variable should contain the array.
For debugging purpose you can use php's built-in print_r() function. It's pretty handy.
here's is an example:
//make sure it's post request
if(isset($_POST)){
//now print the array nicely
echo "<pre>";
print_r($_POST);
echo "</pre>";
}
I am trying to utilise JQuery Ajax to call a javascript file. I need to pass it some parameters but I am not certain how to when using javascript (PHP seems simpler). Here is my call:
function getDocument(parameters) {
$.ajax({
type: "GET",
url: "js/document.js",
dataType: "script",
data: "info=hellothere",
success: function(msg) {
},
error: function(jqXHR, textStatus, errorThrown){
}
});
}
All I would like to do, is print out the contents of the parameter 'info' in document.js
So essentially is should print 'hellothere'.
You're better off using PHP.
Change the URL to document.php, and within that file do the following:
echo $_GET['info'];
url: "js/document.js"
Should be the path to the Server file
You cannot send ajax request to your .js file using Ajax request
Send the request to the .php file and write up your method in there to process the data.
Ajax Request is primarily used to send data to and forth from the Client side to server side ..
If you want to access the data between two .js files better store that data in a cookie or a local storage