AJAX PHP - response is an object with null values - javascript

I have a small problem maybe because i am a beginner in ajax programming, i make a function in ajax jquery that calls a php file, which makes a request to the database for informations about a player. When the php file replies to the ajax function, i get an object with null values as an answer.
Is there a line i've missed in my code? or something i forgot to do?
Here is my code,
AJAX function:
$.ajax({
method: 'GET',
url: "webservices/get_infos.php",
timeout: kTimeout,
success: function(response) {
alert(response);
},
error: function() {
alert('error');
}
});
And the php file :
<?php
include("connexion_bdd.php");
$_GET['mail'] = $mail;
$req = $bdd->prepare('SELECT * FROM joueurs WHERE mail = ?');
$req->execute(array($mail));
$reponse = $req->fetch();
$return = array();
$return["user_name"] = $reponse["nickname"];
$return["profile_pic"] = $reponse["profile_pic"];
$return["user_id"] = $reponse["id"];
print(json_encode($return));
?>
In the success of the ajax function, i get this :
{"user_name":null,"profile_pic":null,"user_id":null}
Although the database is not null.
Where do you think is my mistake? php file or ajax function? or both?
Thanks for helping :)
Edit :
I've changed my code according to the remarks i had on the way i pass the variable AJAX->PHP.
I've tested my sql query on my database and it works fine, but i still have the problem of null values after i pass the object from my php file to the succes function of the AJAX/JS file.
Any ideas about what's wrong with my code?
Thanks again.

You have two problems here.
First, you are not sending the mail parameter in your jQuery AJAX request. You need to append the GET parameter to the end of the URL under the url key:
$.ajax({
method: 'GET',
url: "webservices/get_infos.php?mail=youremail#gmail.com",
timeout: kTimeout,
success: function(response) {
alert(response);
},
error: function() {
alert('error');
}
});
The second problem is that you have your $mail variable assignment in your PHP script backwards. It should be
$mail = $_GET['mail'];
$_GET['mail'] is automatically set by PHP when you call the script with a GET request. But since you are referencing $mail in your prepared SQL statement, you want to assign the value of $_GET['mail'] to $mail.

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

Add javascript variable inside PHP code to decrypt JSON

Basically I have a combination of PHP codes and javascript codes. My mySQL data are encrypted using CodeIgniter, thus to load the data (view and edit) in json, i need to decrypt it again. My question is how to make my "$x" variable dynamic?
Thanks.
function edit_person(id)
{
save_method = 'update';
$('#form')[0].reset();
$('#modal_form').modal({backdrop: 'static', keyboard: true, show: true });
<?php
$x = 13; //<== **i need to make this $x dynamic based on "edit_person(id)"** //
$url = "http://myurlhere.com/main/ajax_edit/".$x;
$datax = file_get_contents($url);
$string = json_decode($datax, TRUE);
?>
$.ajax({
url : "<?php echo site_url('main/ajax_edit')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="id"]').val(data.id);
// ** below code "firstName" is my decryption requirement ** //
$('[name="firstName"]').val("<?php echo $this->encryption->decrypt($string['firstName']); ?>");
$('#modal_form').modal('show');
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
You are probably confusing the server-side and the client-side code.
In simple terms: First, the client sends a request to the server. The target PHP code gets executed on the server-side only. It then generates an HTML file, which contains your JS code. This file is sent to the client and is executed on the client-side only. At that time, on the client-side, there is JS code only and no PHP code anymore. All the PHP code gets replaced by some value or is simply removed or ignored.
If you want to access some PHP functionality from your JS code, you have to send a request from the client to the server. As you are doing with the AJAX call.
So in order to make your $x dynamic, you have to call some PHP code and pass the ID as a parameter.
In a strongly simplifyed way you could achieve this by:
$.ajax({
url : "your url to some file.php/?id=" + id,
type: "GET",
})
some file.php
<?php
$x = $_GET["id"]; //<== $_GET["id"] will return the value of the parameter "id" in the url
?>
Starting from here, you should read more about AJAX calls, input sanitation and validation in order to secure your requests.

Send array with Ajax to PHP script in wordpress

I'm trying to send an array from a JS file to a PHP file in the server but when I try to use the array in php, I got nothing.
This is my function in JS:
var sortOrder = [];
var request = function() {
var jsonString = JSON.stringify(sortOrder);
$.ajax({
type: "POST",
url: '<?php echo get_template_directory_uri(); ?>/MYPAGE.php',
data: { sort_order : jsonString },
cache: false,
success: function() {
alert('data sent');
}
})
};
and this is my php file MYPAGE.php:
<?php
$arrayJobs = json_decode(stripslashes($_POST['sort_order']));
echo($arrayJobs);?>
This is the first time that I use ajax and honestly I'm also confused about the url because I'm working on a template in wordpress.
Even if I don't use json it doesn't work!
These are the examples that I'm looking at:
Send array with Ajax to PHP script
Passing JavaScript array to PHP through jQuery $.ajax
First, where is that javascript code? It needs to be in a .php file for the php code (wordpress function) to execute.
Second, how do you know that there is no data received on the back-end. You are sending an AJAX request, and not receiving the result here. If you read the documentation on $.ajax you'll see that the response from the server is passed to the success callback.
$.ajax({
type: "POST",
url: '<?php echo get_template_directory_uri(); ?>/MYPAGE.php',
data: { sort_order : jsonString },
cache: false,
success: function(responseData) {
// consider using console.log for these kind of things.
alert("Data recived: " + responseData);
}
})
You'll see whatever you echo from the PHP code in this alert. Only then you can say if you received nothing.
Also, json_decode will return a JSON object (or an array if you tell it to). You can not echo it out like you have done here. You should instead use print_r for this.
$request = json_decode($_POST['sort_order']);
print_r($request);
And I believe sort_order in the javascript code is empty just for this example and you are actually sending something in your actual code, right?
the problem is in your url, javascript cannot interprate the php tags, what I suggest to you is to pass the "get_template_directory_uri()" as a variable from the main page like that :
<script>
var get_template_directory_uri = "<?php get_template_directory_uri() ?>";
</script>
and after, use this variable in the url property.
Good luck.
I hope it helps

PHP JSON Encoded Object causes Ajax Error

This has been bugging me for the last few hours, and I've tried various searches but never found exactly this issue with an answer. Maybe asking and showing some code will help me get this figured out.
I am using ajax to do a post to PHP, which I want to just give a notification so that I may update a div on the page. In this case, I just need the PHP to say something like "Cfail" which the javascript would use to update page content.
Originally, I was going to try just text responses. So, my PHP for example would be like this:
<?php
session_start(); //Because have an encoded captcha answer.
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
echo 'Cfail';
}
?>
The Javascript would be:
$(document).ready(function(){
$('form#Contact').submit(function(e){
e.preventDefault();
var $form = $(this);
var formdata = $form.serialize();
var myurl = $form.attr('action');
$('#loader').stop(true).fadeTo(300,1);
$.ajax({
url: myurl,
dataType: 'text',
cache: 'false',
type: 'POST',
data: formdata,
success: function(returned){
$('#loader').stop(true).fadeTo(300,0);
if(returned=='Cfail'){
alert("I read it right!");
}
}
});
});
});
It would run through the script just fine, but the result never would be what I was asking for. Alert showed the corrct text, however, research indicated that the issue with this was PHP apparently adding white space. The common answer was the encode a JSON response instead. So, I tried that.
Updated PHP:
<?php
sesson_start(); // Captcha Stored in Session
header('Content-type: application/json');
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
$result = array('result' => 'Cfail');
echo json_encode($result);
exit;
}
?>
Updated Javascript:
$(document).ready(function(){
$('form#Contact').submit(function(e){
e.preventDefault();
var $form = $(this);
var formdata = $form.serialize();
var myurl = $form.attr('action');
$('#loader').stop(true).fadeTo(300,1);
$.ajax({
url: myurl,
dataType: 'json',
cache: 'false',
type: 'POST',
data: formdata,
success: function(returned){
$('#loader').stop(true).fadeTo(300,0);
if(returned.result=='Cfail'){
alert("I read it right!");
}
}
});
});
});
Which now no longer runs successfully. The alert doesn't come up, and the loader object remains visible(indicating the success never goes through). I tried putting an error section to the ajax, and it indeed fired that. However, I had no idea how to parse or even figure out what the error was exactly. The most I got in trying to get it was what PHP was outputting, which was {"result":"Cfail"} .... Which is what I would EXPECT PHP to give me.
I can work around this, I've done a similar set-up with just echoing a number instead of words and it used to work just fine as far as I knew. I'd just like to figure out what I am doing wrong here.
EDIT:
I managed to figure out what the issue was in my case. I had a require('config.php'); between the session start and the json_encode if statement. For some reason having the external file added, which was just me setting a couple variables for the code further down, some hidden character was added before the first { of the JSON object.
No idea why. As I said, it was just a $var='stuff'; situation in the require, but apparently it caused the issues. :/
Use this like
<?php
sesson_start(); // Captcha Stored in Session
header('Content-type: application/json');
if(empty($_POST['captinput']) || md5($_POST['captinput']) !== $_SESSION['captchacode']){
//$result = array('result' => 'Cfail');
$data['result'] = 'Cfail';
echo json_encode($data);
exit;
}
?>
This works for your javascript
use the below code, in your success call back, first parse the encoded json object that you are recieving from the back end and access the object property result to check it's value
success: function(returned){
returned = JSON.parse(returned);
$('#loader').stop(true).fadeTo(300,0);
if(returned.result=='Cfail'){
alert("I read it right!");
}

unable to get the data value of ajax on another page

I'm trying to update the user votes into database. This below ajax codes returns correct rating datas. But, I'm unable to get the alert data on another page. In my car_user_rating.php page I have tried this echo $post_rating = $_POST['performance_rating'];. But it doesn't get the performance_rating data value.
I have checked my console. It returns the rating values (4). I'm confused why it doesn't get the data value?
ajax request
$(function () {
$('#form').on('submit', function (e) {
performance_rating = $('input:radio[name=rating]:checked').val();
e.preventDefault();
$.ajax({
type: 'POST',
url: "<?=CAR_USER_RATINGS?>",
data: { performance_rating: performance_rating },
success : function(data){
alert(performance_rating)
},
});
});
});
you should alert the data which you pass in success: function()
like
success : function(response){
alert(response);
},
use 'var' in submit handler, may it's because of scope:
var performance_rating = $('input:radio[name=rating]:checked').val();
I am not sure of your context so cant say exactly. Also i dont know if you are using exact same code as above or you have written teh above code in a hurry since there are mistakes there!!!
However Firstly try these
data: { "performance_rating": performance_rating },
url: "<?php=CAR_USER_RATINGS?>" //you have forgotten php
success : function(data, testStatus, xhr){
},
and check each values of data, testStatus, xhr
Also what is the value of
performace_Rating before $.ajax
"<?php=CAR_USER_RATINGS?>" before $.ajax
Just to summarize. I could figure out from your comment that your php is as below:
no. I have this codes on my php page inside the body tag
<?php echo $post_rating = $_POST['performance_rating'];
/*var_dump($get_rating); echo $sql = "UPDATE ".TBL_CAR_USER_RATINGS." SET performance = '$get_rating' WHERE model_id = '2'"; die(); mysql_query($sql, $CN) or die(mysql_error()); */ ?>
This is present inside the body tag!!! Well if you are using body tag i presume you are using other html, header(optional) tags as well
For a ajax response page the reply to client should "ONLY" be the value you want to send back.
Having tags will result in the the ajax response containing these tags as well.
So if you want your ajax page to return performance rating do the below:
//car_return_Rating.php
<?php echo $_POST['performance_rating']; ?>
If you have below code your response is shown below
//car_Return_rating.php
<html>
<body>
<?php echo $_POST['performance_rating']; ?>
</body>
</html>
then response i.e. data in success(data){}
will be equal to
data = "<html><body>4</body></html>"; //assuming 4 to be equal to $_POST['performance_rating'];

Categories