sending data to php from js via ajax post - error - javascript

I'm trying to pass data from my js file to a php file by using ajax (as you can see below).
I've checked the php error log and saw that the data I sent via POST isn't recognized by php (getting "trying to get property of non-object" error).
I've also posted my php code below if fails on the last line, when I refer to $json->func.
Am I doing it right? I've seen some examples of using jquery's post function, but I like the ajax way with the success and error, so I've been trying to stick to it.
Appreciate the help :)
js:
$.ajax({
type: "POST",
url: url,
dataType : "json",
data: {func:'getSummId' ,summName: summonerName},
success: function(json){
//bla bla bla
}
error: function(){
//bla bla bla
}
php:
<?php
header("Content-Type: application/json", true);
header("Access-Control-Allow-Origin: *");
$client_data = file_get_contents("php://input");
$json = json_decode($client_data);
switch ($json->func) {
...

dataType refers to the data being returned, not how you are sending the data.
So your data is going to be in the $_POST global variable, and using php://input will not work in this case with json_decode
So you can either use
$func = $_POST['func'];
$summName = $_POST['summName'];
Or you can try setting the content type option in your jQuery ajax request (though i have never tried this so you will have to test it)
$.ajax({
type: "POST",
url: url,
contentType: "application/json",
dataType : "json",
data: {func:'getSummId' ,summName: summonerName},
When contentType is not set it defaults to
application/x-www-form-urlencoded; charset=UTF-8
PHP automatically parses that type of request into the $_GET/$_POST/$_REQUEST globals. PHP does not natively know how automatically parse application/json requests sent to it. So when wanting to send request data as json you have to read php://input yourself.

Try to change: type: "POST" to method: "POST"

Related

Trying to pass variable from JavaScript to PHP using Ajax but got error " Undefined array key"

I have had this error for multiple days now, I have tried searching this error up but whenever I search this error up it gives a different reason for the error and when I try to add what other sites say it doesn't work which is why I am asking here as I don't see what else I can do.
I am trying to pass a variable from JavaScript to PHP but it is not working and I have no idea why.
Here is my JavaScript code:
<head>
<script type="text/javascript" src="jquery.js"> </script>
</head>
<script>
var variable = "hello";
console.log(variable);
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function() {
alert("Success");
}
});
</script>
Here is my PHP code:
$variable = $_POST['pass'];
echo($variable);
Everything seems to work perfectly. It writes the variable to the console, it comes up with the alert saying success. However I get an error message saying: 'Undefined array key "pass"'
What is causing this? Thank you?
Edit: People have told me to use isset, I have added that it removed the error however it still does not echo the PHP variable, meaning it is still not been passed to PHP, I am still trying to find how to fix this.
Your front end code looks OK, but I don't know your target PHP environement, but maybe your environnement doesn't accept formData.
By default, jQuery send ajax POST data as formData.
Try to send data as JSON
$.ajax({
url: "ajax.php",
type: "POST",
data: JSON.stringify({pass : variable}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data){alert(data);},
});
And then you will probably have to adapt your php code:
$json = file_get_contents('php://input');
// Converts it into a PHP array
$data = json_decode($json, true);
$variable = $data['pass'];
echo($variable);
Can you please use the developer tools in chrome browser that will help you to find if data is properly sent to php file.
Also you can try $_REQUEST instead of post just to check what data is coming in REQUEST as it works for GET & POST both. If it still does not help you.
Also can you please use
data: {'pass':variable}
instead of
data: {pass:variable}
let me know if it works for you.
If you get this error in your ajax.php file which you Post the data to it, I say it's normal because when you open that file (ajax.php) it's like that there is no $_POST['pass'] because you just opened that file without running JS to send data.
If you want to receive data that you send you can do this:
Your JS code I call this file index:
var variable = "hello";
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function(res) {
alert(res);
}
});
The PHP file:
$variable = $_POST['pass'];
echo($variable);
Then if You open up that index file, after running the JS code it'll send that post data to your PHP file and your PHP file will echo that, then the value will store in that res variable which when every thing went fine, you can see the alert of that res in the page (index file).
Notice that as I said you can't open up the PHP file lonely because it doesn't receive a post data on its own, it is normal for undefined to return.
Re: #puckloe your code is working, php echo wouldn't be printed with ajax(correction echo is working but wouldn't show on page if you don't print it with JS too), you have to catch the response in ajax success function ( like success: function(response) ) and print or alert the response --> success: function(response) { alert("hi look this is echo from php"+response) }
you ajax code should look like
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function(response) {
alert("hi look this is echo from php" + response);
}
});

Read PHP output from array with AJAX

My PHP is outputting data like this:
$data['full_feed'] = $sxml;
$data['other_stuff']= $new;
echo json_encode($data);
So, in my jQuery, I'm doing this.
$.ajax({
url: 'untitled.php',
type: 'GET',
success: function(data) {
console.log(data['full_feed']);
});
This comes back undefined. So does console.log(data.full_feed). I'm getting back from PHP a valid JSON object, but missing how I can "parse" it correctly.
Parse "data" parameter in response with jQuery.parseJSON function. Then use parsed.full_feed value. Like below:
$.ajax({
url: 'untitled.php',
type: 'GET',
success: function(data) {
data = jQuery.parseJSON(data);
console.log(data.full_feed);
});
You can do like #tilz0R said or for your example to work you need to tell the browser you are sending a json response. So need to set content type header like
header('Content-Type: application/json');
echo json_encode($data);
to see what the server is returning do console.log(typeof data). If its a string you need to parse it. if its an object, it is already parsed.
Also you can put dataType:'json' in your ajax call to let jquery know you are excepting a json response.

Extract Json response

I am trying to to extract a Json response in jquery sent from a php file.
This is the .js code:
$.ajax({
url: 'index.php?page=register', //This is the current doc
type: 'POST',
datatype: 'json',
data: {'userCheck': username},
success: function(data){
// Check if username is available or not
},
error: function(){
alert('Much wrong, such sad');
}
});
This is the response from the php file:
if($sth->fetchColumn()!=0){
//$response = array("taken");
$response = array("username"=>"taken");
echo json_encode($response);
//echo '{"username':'taken"}';
}else{
//$response = array("available");
$response = array("username"=>"available");
echo json_encode($response);
//echo '{"username":"available"}';
}
I have tried all combinations I can think of in both files, but nothing seems to work. It is a simple check for a username in the database. If I console log the data I get from the response, I get this:
{"username":"available"}<!DOCTYPE html>
// The rest of the page html
So the info is there, but how do I access it? I have tried several syntaxes found around the internet, but no luck so far. I seem to recall that a json response only can contain valid json, so is the problem the html? I don't think I can avoid this due to the structure of my application, so hopefully it is possible to access the json with my present structure.
in you Ajax
EDIT:
change
datatype:"json",
the case of parameter name was not respected, the t must be T
dataType:"json",
now retry please
$.ajax
({
url: 'index.php?page=register', //This is the current doc
type: 'POST',
dataType: 'json',
data: {'userCheck': username},
success: function(data)
{
// Check if username is available or not
switch(data.username)
{
case "available":
// do you want
break;
case "taken":
// do you want
break;
}
},
error: function()
{
alert('Much wrong, such sad');
}
});
in PHP
simply that, and don't forget to exit; to avoid include html page in your json response !
This is the code coming after the }".... who break your json output
and make it unreadable by javascript (worste, it simply break your javascript !)
echo json_encode(["username"=> ($sth->fetchColumn()!=0) ? "taken":"available"]);
exit;
When you're responding to an AJAX call, you should just return the JSON response, not the HTML of the page. Add:
exit();
after this code so you don't display the HTML after the JSON.
In the JS code, use if (data.username == 'available') to tell whether the username is available.
The other problem in your code is that you have a typo here:
datatype: 'json',
It should be dataType, with an uppercase T.
You can also put:
header("Content-type: application/json");
before echoing the JSON in the script, and jQuery will automatically parse the response.
Also you can set request headers in your jQuery ajax call beforeSend function like follows
beforeSend: function (xhr) {
xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
xhr.setRequestHeader('Accept', 'application/json');
}
So you're strictly declaring the data type to be json

json_encode to send data back to js

Im creating a simple upload script. I use a simple form to let people upload a picture and then a external php script will upload the picture and return some vars to the upload page.
But I cant get the part to return some vars to work. currently im using this:
The page that also contains the form:
form_data.append('file', file_data);
$.ajax({
url: 'upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(response){
document.getElementById("titel" + amount).innerHTML = response['naam'];
});
The upload page that should return some data:
echo json_encode(array('naam'=>$naam));
This scripts returns undefined..
If I remove the ['naam'] after response on the form page it will print out:
{"naam":"test.png"}
Hope someone know what im doing wrong.
Thanx in advance!
You said:
dataType: 'text', // what to expect back from the PHP script, if anything
… so jQuery will ignore what the server claims the data is (which seems to be HTML as you haven't changed the Content-Type header in your PHP) and process the response as if it was plain text.
response will therefore be a plain text string and not the results of parsing JSON.
Change dataType to "json".
The response you get from the server is the string. To use it as object, you need to parse it to JSON format using JSON.parse().
var obj = JSON.parse(response);
Then you can use:
obj.naam;
to get the value of naam from the object.
Please change datatype from "text" to "json" then parse that JSON using JSON.parse(//return value ").
Var jsonObject = JSON.parse("Ajax Response object");
then use it jsonObject.keyName and it will return the value.

how do i use the success function with an $.ajax call

I don't understand how the success function works in a $.ajax call with jquery.
for instance
$.ajax({
type: "POST",
url: "ajax.php",
data: "function=1",
success: function(data,response,jqxhr){
useReturnData(data /* ??? not sure how to use the data var */ );
}
};
ajax.php:
<?php
if ($_REQUEST['function'] == '1'){
$string = "this is the data i want to return and use";
}
?>
how do i use that data within the success function? No where seems to explain what the data parameter is, they just seem to use it ambiguously.
another side question, is the data: "function=1" related to the data as a parameter for the success function?
The data variable contains the output of your php file, so if in your php file you do:
echo "<p>success</p>";
data will contain <p>success</p>.
In your example you would change your php file to:
<?php
if ($_REQUEST['function'] == '1'){
$string = "this is the data i want to return and use";
}
// other stuff...
echo $string;
?>
The content of the data parameter depends on the type of the response. If the Content-Type is application/json, then it's parsed as JSON. If it's text/html or similar, the content is HTML. In your case, it looks like you're returning text. If you make your Content-Type header text/plain or similar, then data should just be a string.
To answer your second question, the data property for the Ajax request is something different; it specifies the request data that is sent. In other words, it's the query string if you have a GET request, and the post "form" variables if it's a POST request.
data is whatever is returned by the server side script, so in this case it would be
this is the data i want to return and use
Providing the if() condition is met.
Nobody really says what data contains because it can contain various different things, although it's always a string. Sometimes it's HTML, sometimes it's JSON and sometimes just a return message.
In your case, data will just be a string providing you echo the string out in your server side script.
The easiest way is to load the data into some placeholder element (div?)
E.G.
$.ajax({
type: "POST",
url: "ajax.php",
data: "function=1",
success: function(data,response,jqxhr){
$('div.selector').load(data);
}
};

Categories