Getting 'undefined is not a function' when requesting JSON - javascript

I am having issues when requesting data from a PHP file.
When I call the variable msg[0} I am told it is undefined but it should have been populated in the JSON request. The JS is below and you can find the PHP output at the link:
$.ajax({
type: "GET",
url: "https://bluecode.org.uk/intranet/otd/index.php",
dataType: "json"
})
.done(function (msg) {
console.log(msg[0])
});
The actual PHP is:
mysql_query("INSERT INTO uniquedownload (downloadkey, file, expires) VALUES ('{$strKey}', 'hello.html', '".(time()+(60*60*24*5))."')");
$a = array($strKey);
echo json_encode($a);
Thanks

I'd recommend logging msg so you can see how the data looks, and maybe adding a debugger; into your .done() callback to give yourself a way of experimenting with different ways of accessing the properties of msg.

I needed to add this to the PHP:
header('Content-Type: application/json');

Related

How to post to php with ajax, I consistently get error 400 bad request?

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');
?>

Why are my PHP/AJAX with JSONP scripts returning HTML, JSON, and invalid JSON?

I am having some trouble with communication between my php script and my javascript file. It seems the javascript is receiving html, json, and "invalid json" from the php script that I have written.
In the Javascript code, the data variable evaluates to:
{"readyState":4,"status":200,"statusText":"success"}
This is not of the JSON format that I echo below (in either spot in the code where I do so). Based on my research, this is because the JSON echo in the PHP code is returning invalid JSON (which causes the PHP to return this as a result instead). However, when I check the console, I find the following:
<br />
<b>Warning</b>: mysqli::mysqli() [<a href='mysqli.mysqli'>mysqli.mysqli</a>]: (28000/1045): Access denied for ... in <b>..../.php</b> on line <b>xx</b><br />
{"status":"failure","message":"Access denied for ...."}
This is not printed because of any console.log statements I have in my code, this is printed as a result of Firefox's automatic console entry from the GET http://...../.php call.
The top line of code is the html that the PHP would return if this were not a JSON return, and the bottom line of the code above is the actual JSON object that I have created, and that I want to work with.
The reason I am posting here is because I cannot think of why the PHP would return html, my JSON, and JSON indicating invalid JSON.
I should also mention that I am receiving another error on the console:
SyntaxError: expected expression, got '<' --> file.php:1
This suggests to me that the browser is trying to interpret the php on the client end for some reason, but I'm not sure if that's accurate or not.
I think that I have an error somewhere that is the root of all of these symptoms, but after some time and research, I have not been able to find this error on my own.
The code I am using is shown below:
Javascript AJAX:
$.ajax({
url: "...url.../file.php",
crossDomain: true,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
data: {
name: email,
email: email
},
complete: function(data) {
console.log(JSON.stringify(data));
//this is where the {"readyState":4,"status":200,"statusText":"success"} appears
}
});
PHP (contents reduced to scope of this problem):
<?php
header("Content-type: application/json");
header("Content-Disposition: attachment;Filename=\"gamesUser.json\"");
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Max-Age: 1000');
.........
$data = array();
$conn = #new mysqli($servername, $username, $password, $dbname, $port);
//check the connection
if ($conn->connect_error) {
$data['status'] = 'failure';
$data['message'] = $conn->connect_error;
echo json_encode($data);
} else {
.........
$data['status'] = 'success';
$data['message'] = 'operations complete';
$data['fileURL'] = $fileURL;
echo json_encode($data);
.........
}
.........
?>
SOLVED!
The code:
echo $_GET['callback'].'('.json_encode($data).')';
along with changing ajax parameters:
type: "GET",
dataType: 'jsonp',
jsonpCallback: 'handleResponse',
data: data
Have fixed the problems. Thanks to everyone who assisted in the discussion.
I think , what you need is the callback function from jsonp , please go through the below example , you will get the idea
function myfunc(json) {
alert(json);
}
$.ajax({
type: "GET",
url: "http://example.com?keyword=r&callback=jsonp",
dataType: 'jsonp',
jsonpCallback: 'myfunc', // the function to call
jsonp: 'callback', // name of the var specifying the callback in the request
})
;
When an error happens in PHP, it displays the error information using HTML so you can see it properly in the browser. That's why you get the unexpected HTML, so you should make sure the PHP script doesn't show errors
You can suppress warnings for mysqli constructor (which I think is the one causing the problem) by prepending the at (#) sign:
...
#mysqli(...)
...
There are other ways of avoid showing errors, check http://php.net/manual/es/errorfunc.configuration.php#ini.display-errors
http://php.net/manual/es/errorfunc.configuration.php#ini.error-reporting

jQuery AJAX PUT request data submission not working

I have a PHP file which contains the following:
if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
echo '{ "response": "' . $_REQUEST['id'] . '" }';
}
Now I want to make an AJAX call to this file via jQuery:
var send = {
id: 10
};
$.ajax({
data: send,
method: 'PUT',
url: "myphpfile.php",
success: function(responseData) {
console.log(responseData.response);
}
});
This should return 10 as a response, however the output is empty. In the PHP file I also tried writing the id to a text file, which turned out to be empty as well. This means that my PHP code isn't the problem here, it's JavaScript.
When I change the AJAX url to myphpfile.php?id=10 however, the response is correct and 10 is logged to the console.
I have tried a lot of things to fix this, nothing worked. This includes setting contentType: 'application/json; charset=utf-8', dataType: 'json' and data: JSON.stringify(send). I can't find any more forum questions or articles on this and the ones I found didn't work.
Any help is appreciated.
You cant access the data from a PUT request via $_REQUEST. You'd need something like:
if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
parse_str(file_get_contents("php://input"),$sent_vars);
echo json_encode(['response'=>$sent_vars['id']]); // use an array and json_encode to avoid messy string concatenation
}
See also Accessing Incoming PUT Data from PHP
So there are a couple of issues here:
PUT requests handle data parsing differently to POST, which is how you've formatted your request. So Delighted's response for more details.
You return a json string but don't convert it into a js object. You need something like $.parseJSON(...) for the object to return properly. So something like:
success: function(responseData) {
var r = $.parseJSON(responseData);
console.log(r.response);
}

Send data from PHP script to jQuery Ajax request

I'm new to web development, so please pardon any silly mistakes!
I'm using the following code send a jQuery Ajax request:
var d = "email=" + email + "&password=" + password;
$.ajax({
url: 'login/c_login_form.php',
data: d,
dataType: "text", //expected type from server
type: "POST",
success: function(str, status) {
console.log(str + ": " + status);
},
error: function(obj) {
alert("Fatal error. Failed to send Ajax request.");
}
});
For simplicity, let us assume that login/c_login_form.php is currently blank (but has the php tags, of course) and is to return a set data every time.
I was under the impression that whatever I echo from the server will be passed to the success function, but it's not working that way. What is the way to send data from PHP script back to Ajax? Although I've used text datatype, I'd be happy if somebody can tell me how to return JS objects.
To summarize comments in a concrete answer:
<?php
header('Content-Type: application/json');
$data = array("status" => 1, "err" => "example_error_code");
echo json_encode($data);
?>
Please note, as Anthony Grist suggests, that you need, on your Javascript:
dataType: "json"
instead of:
dataType: "text"
See also jQuery ajax docs:
...
dataType (default: Intelligent Guess (xml, json, script, or html))
...
You can refer this answer for Ajax post request.
To send back data from PHP file to JS you need to use echo.
If you are passing more than one variable then you can use echo json_encode($array_of _variables);. If there is only one variable than please you can use just echo $variable.

Get Ajax POST data on php via Javascript call

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>";
}

Categories

Resources