What goes into Responce in jQuery AJAX? - javascript

I'm sorry to add this broad question here, but I cannot seem to google it myself, I tried, and I really can't grasp the idea behind this, so here goes.
So I have a web-site that uses AJAX to login a user without full page reload. I kind of understand how AJAX works, and I'm sorry for my ignorance, but in my case:
$.ajax({
url: './',
type: 'POST',
data: {auth: auth, login: login, pass: pass}
success: function(res){
// Code that checks if **res** is a specific string
},
error: function(){
alert("Error!");
}
I understand that this sends POST request to the same page with 3 parameters. What I don't understand is what specifically does it get as a responce? In my case, in res is the $_SESSION element that contains the string message.
My question is: how do I know what gets in the responce? If I would just echo something in my function, would that get in the responce? Is there like a documentation about what can be passed to the arguments of success function?
I'm really confused about this.

The "res"... or commonly "data" in most examples, is simply the reply data from your page that your posting to..
So say in the case of PHP... you yes would simply echo anything back to it.
commonly people use JSON, so with php you would create a array with all the data you want to send back and then simply do
YOUR PAGE THAT SENDS THE POST
<script>
// JUST USING SUCCESS HERE ATM (Tthis does not show the full ajax command)
// Refer to original question for full javascript
success: function(res){
var myData = $.parseJSON(res);
if(myData.hasOwnProperty('name')){
alert(myData.name);
}
if(myData.hasOwnProperty('object1') && myData.object1.hasOwnProperty('items')){
alert(myData.object1.items.one);
}
},
</script>
YOUR PHP PAGE THAT RESPONDS
<?php
$myResponse = array();
$myResponse['name'] = "John Doe";
$myResponse['number'] = 123456789;
$myResponse['other'] = "and so on";
$myResponse['object1'] = array();
$myResponse['object2'] = array();
$myResponse['object1']['name'] = "john";
$myResponse['object1']['items'] = array();
$myResponse['object1']['items']['one'] = "one one 1";
$myResponse['object1']['items']['two'] = "two two 2";
$myResponse['object2']['name'] = "jane";
echo json_encode($myResponse);
?>
By using a "multidimensional" array in php, you can then treat each part of the array as a separate section/object
This might help: http://www.thecave.info/pass-a-php-array-to-javascript-as-json-using-ajax-and-json_encode/

Well, I think that what you "echo" is what you will retrieve in the "res",
try to see it in the console with:
console.log(res);
Or with an alert
alert(res);

try console.log(res); and check the browser console
ctrl + shift + k (firefox)
f12 (Chrome & IE)

For you task I would recommend using getJSON, instead of .ajax. It's just a shorthand for the same function, but really handy.
$.getJSON('/ajax-get-session/login/value/pass/value', function(json){
if (!json.error) { //check if there wasn't error on the server side
console.log(json.session);
} else {
console.log(json.error);
}
});
And on the server side.
$response = array();
try {
$response['session'] = $_SESSION;
}
catch (e) {
$response['error'] = e;
}
echo json_encode($response)

Related

What is wrong with the way I am handling these variables in PHP?

Originally I wanted to use node.js, but after an entire day of frustration, I switched to using jquery and mySQL. The logins seem to be working, but something is wrong in the way it is handling variables. All I want to do is update the database with two things: score and name. Here is the code I modded for my project in PHP:
<?php
$db = "myDatabaseNameIsCorrect";//Your database name
$dbu = "soIsMyUsername";//Your database username
$dbp = "AndMyPassword";//Your database users' password
$host = "localhost";//MySQL server - usually localhost
$dblink = mysql_connect($host,$dbu,$dbp);
$seldb = mysql_select_db($db);
if(isset($_GET['name']) && isset($_GET['this.score'])){
//Lightly sanitize the GET's to prevent SQL injections and possible XSS attacks
$name = strip_tags(mysql_real_escape_string($_GET['name']));
$score = strip_tags(mysql_real_escape_string($_GET['this.score']));
$sql = mysql_query("INSERT INTO `$db`.`scores` (`id`,`name`,`score`) VALUES ('','$name','$score');");
if($sql){
//The query returned true - now do whatever you like here.
echo 'Your score was saved. Congrats!';
}else{
//The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
echo 'There was a problem saving your score. Please try again later.';
}
}else{
echo 'Your name or score wasnt passed in the request. Make sure you add ?name=NAME_HERE&score=1337 to the tags.';
}
mysql_close($dblink);//Close off the MySQL connection to save resources.
?>
And here is the JS! that runs the PHP:
let gameoverScene = new Phaser.Scene('GameOver');
gameoverScene.create = function(){
this.laughSound=this.sound.add('laughSound')
this.gameW = this.sys.game.config.width;
this.gameH = this.sys.game.config.height;
this.goToTitle=function(){
var name = prompt('Enter your name');
jQuery.ajax({
type: "POST",
url: 'savescores.php?name=' +name +'&score=' + this.score,
dataType: 'text',
data: {functionname: 'add', arguments: [name, this.score]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
yourVariable = obj.result;
}
else {
console.log(obj.error);
}
}
});
this.scene.start('Title')
};
I also tried changing the data type and that didn't work, but I'm not ruling it out yet as a problem.
Here are links to the project and the database:
www.igglepud.com/DeerDefender/Testing
www.igglepud.com/DeerDefender/Testing/getscores.php
This is the error I get:
gameover.js:20 Uncaught TypeError: Cannot use 'in' operator to search for 'error' in
Your name or score wasnt passed in the request. Make sure you add ?name=NAME_HERE&score=1337 to the tags.
at Object.success (gameover.js:20)
at fire (jquery.js:3268)
at Object.fireWith [as resolveWith] (jquery.js:3398)
at done (jquery.js:9305)
at XMLHttpRequest.<anonymous> (jquery.js:9548)
So, the error you're getting is because, in the JavaScript, obj (or the parameter in obj's position) is a string, not an array.
You can see some examples here of how you can properly check for and catch errors.
Edit:
So, in regards to your question about the score variable.
It's important to note that there are 2 types of variables at play here.
The first one is PHP GET variables. PHP GET variables are set via the following format:
var=value
You can set these variables by calling a PHP script like this:
script.php?var1=value1&var2=value2&var3=value3 // etc...
You can access them like this:
echo $_GET["var1"];
echo $_GET["var2"];
echo $_GET["var3"];
Which produces the result:
value1
value2
value3
The second variable at play is a JavaScript variable. Those can only be accessed in JavaScript. a JavaScript variable means nothing in PHP.
So, let's examine what you're doing from the JavaScript:
url: 'savescores.php?name=' +name +'&score=' + this.score,
For the purpose of explaining let's say name = Chipster, and this.score = 123.
What this code will do is try to open the following file:
savescores.php?name=Chipster&score=123
Remembering that PHP GET variables are set by the format script.php?var1=value1&var2=value2&var3=value3 // etc... we can see that there are 2 GET variables available from the PHP script called name and score. Thus, to access score from PHP you need to do it like this:
echo $_GET["score"];
This will output 123 in our example.
This may not solve your problem, but one issue I see with your code is calling strip_tags (or another function that alters the string) after it has already been quoted for insertion with mysql_real_escape_string may defeat the purpose of mysql_real_escape_string. It should be the very last function called on data before it's inserted.
Also, if score is an integer string, intval serves just as well as mysql_real_escape_string for sanitizing integers for insertion.
EDIT: You're also checking for GET variables in the PHP when the submission method used in the jQuery is POST. Try looking at $_POST instead of $_GET on the PHP side. You don't need to put variables in a query string if you're putting them in the request body via POST either.

Failing to send to $_POST but $_SESSION says something else

I do not know what is happening with my code, when I run it, sometimes SESSION says there is an array is stored and sometimes it doesn't. I am using a debugger to check the session. When I use isset($_POST), the return value is always false. I am using ajax to pass an array to php.
<?php
session_start();
if(isset($_POST['jExam'])){
$decode = json_decode($_POST['jExam']);
$_SESSION['receive'] = $decode;
$product = $_SESSION['receive'];
}
else{
echo "Failed to hold<br>";
}
?>
Javascript:
$(document).ready(function(){
$(".class").click(function(event)){
event.preventDefault();
window.location.href = 'example.php';
var jExample = JSON.stringify(array);
$.ajax({
data:{'jExam':jExample},
type: 'POST',
dataType: 'json',
url: 'example.php'
});
});
EDIT:
Figured out why the arrays are stored into SESSION, once I click on the button that opens the other page, and then type in the page before in the url, the array is stored into the SESSION. Don't know why. Still can't figure out why ajax is not sending to post.
EDIT 2:
I created a file that handles the request called handle.php. So the php script on top is added into handle.php instead of the webpage. But I am getting a "Parse error: syntax error, unexpected 'if' (T_IF)". The code is still the same on top.
handle.php:
<?php
session_start();
if(isset($_POST['jExam'])){
$decode = json_decode($_POST['jExam']);
$_SESSION['receive'] = $decode;
$product = $_SESSION['receive'];
}
else{
echo "Failed to hold<br>";
}
?>
EDIT 3:
I am using the ajax to pass an array to php in order to store it into session, in order to use the array in another page. The problem is that the array is not passing into $_POST. What I am hoping is that the array can actually pass so I can use it on another page.
SOLVED:
All i did was add a form that has a hidden value. And the value actually post
<form id = "postform" action = "cart.php" method = "post">
<input type = "hidden" id="obj" name="obj" val="">
<input type = "submit" value = "Show Cart" id = "showcart">
</form>
In the Javascript:
$(document).ready(function(){
$("#showcart").click(function(){
var json = JSON.stringify(object)
$('#obj').val(json);
$('#obj').submit();
});
});
Thank you for everyone at has answered but hope this helps others.
If example.php is the php file which handles the request, you need to change your js code to
$(document).ready(function(){
$(".class").click(function(event)){
event.preventDefault();
var jExample = JSON.stringify(array);
$.ajax("example.php", {
data:{'jExam':jExample},
type: 'POST',
dataType: 'json'
});
});
And you should add the complete-Parameter if you want to handle the response.
Your mistake is, you are redirecting the page using window.location.href before you even send your request. Therefore, your request never gets sent and the PHP-File is called directly instead, not via AJAX, not with the nessecary data. Therefore, you are missing the data in the PHP-File.
You will want to try and make this setup a bit easier on yourself so here are a few things that can help you simplify this. You may or may not have some of these already done, so disregard anything you already do:
Use a config file with concrete defines that you include on 1st-level php files
Just pass one data field with json_encode()
Don't send json as a data type, it's not required, troubleshoot first, then if you need to, make it default as the send type
Use a success function so you can see the return easily
Make functions to separate tasks
/config.php
Add all important preferences and add this to each top-level page.
session_start();
define('URL_BASE','http://www.example.com');
define('URL_AJAX',URL_BASE.'/ajax/dispatch.php');
define('FUNCTIONS',__DIR__.'/functions');
Form:
Just make one data that will send a group of data keys/values.
<button class="cart" data-instructions='<?php echo json_encode(array('name'=>'Whatever','price'=>'17.00','action'=>'add_to_cart')); ?>'>Add to Cart</button>
Gives you:
<button class="cart" data-instructions='{"name":"Whatever","price":"17.00","action":"add_to_cart"}'>Add to Cart</button>
Ajax:
Just send a normal object
$(document).ready(function(){
// Doing it this way allows for easier access to dynamic
// clickable content
$(this).on('click','.cart',function(e)){
e.preventDefault();
// Get just the one data field with all the data
var data = $(this).data('instructions');
$.ajax({
data: data,
type: 'POST',
// Use our defined constant for consistency
// Writes: http://www.example.com/ajax/dispatch.php
url: '<?php echo URL_AJAX; ?>',
success: function(response) {
// Check the console to make sure it's what we expected
console.log(response);
// Parse the return
var dataResp = JSON.parse(response);
// If there is a fail, show error
if(!dataResp.success)
alert('Error:'+dataResp.message);
}
});
});
});
/functions/addProduct.php
Ideally you would want to use some sort of ID or sku for the key, not name
// You will want to pass a sku or id here as well
function addProduct($name,$price)
{
$_SESSION['cart'][$name]['name'] = $name;
$_SESSION['cart'][$name]['price'] = $price;
if(isset($_SESSION['cart'][$name]['qty']))
$_SESSION['cart'][$name]['qty'] += 1;
else
$_SESSION['cart'][$name]['qty'] = 1;
return $_SESSION['cart'][$name];
}
/ajax/dispatcher.php
The dispatcher is meant to call actions back only as an AJAX request. Because of the nature of the return mechanism, you can expand it out to return html, or run several commands in a row, or just one, or whatever.
# Add our config file so we have access to consistent prefs
# Remember that the config has session_start() in it, so no need to add that
require_once(realpath(__DIR__.'/../..').'/config.php');
# Set fail as default
$errors['message'] = 'Unknown error';
$errors['success'] = false;
# Since all this page does is receive ajax dispatches, action
# should always be required
if(!isset($_POST['action'])) {
$errors['message'] = 'Action is require. Invalid request.';
# Just stop
die(json_encode($errors));
}
# You can have a series of actions to dispatch here.
switch($_POST['action']) {
case('add_to_cart'):
# Include function and execute it
require_once(FUNCTIONS.'/addProduct.php');
# You can send back the data for confirmation or whatever...
$errors['data'] = addProduct($_POST['name'],$_POST['price']);
$errors['success'] = true;
$errors['message'] = 'Item added';
# Stop here unless you want more actions to run
die(json_encode($errors));
//You can add more instructions here as cases if you wanted to...
default:
die(json_encode($errors));
}

How to use AJAX to get data from DB and display on page [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm working in a project and I'm stuck here, I don't know why I can't get the list from my database\
Here is my JAVASCRIPT
$(document).ready(function(){
$.ajax({
url:'datos.php?accion=ac',
success:function(datos){
for(x = 0;x<datos.length;x++){
//$("#PAIS").append("<option value='"+datos[x].id_pais+"'>"+datos[x].pais+"</option>");
$("#PAIS").append(new Option( datos[x].pais, datos[x].id_pais));
}
}
})
$("#PAIS").change(function(){
//var felix=$('#PAIS option:selected').val();
//alert(felix);
$.ajax({
url:'datos.php?accion=ad',
alert('hola22');
success:function(datos1){
console.log("hola");
for(x = 0;x<=datos1.length;x++){
//$("#PAIS").append("<option value='"+datos[x].id_pais+"'>"+datos[x].pais+"</option>");
$("#REGION").append(new Option( datos1[x].region, datos1[x].id_region));
}
}
})
});
})
And my functions.php:
<?php
$server="localhost";
$usr="root";
$passwd="";
$data="combo";
$db=mysqli_connect($server,$usr,$passwd,$data) or die ("Error en la conexion1");
$Accion = $_GET['accion'];
if($Accion=="ac"){
header('Content-Type: application/json');
$paises = array();
$Consulta = mysqli_query($db,"SELECT * FROM paises")or die ("Error en la conexion7");
while($Fila=mysqli_fetch_assoc($Consulta)){
$paises[] = $Fila;
}
echo json_encode($paises);
}
if($Accion=="ad"){
header('Content-Type: application/json');
$regiones = array();
$Consulta1 = mysqli_query($db,"SELECT * FROM regiones WHERE id_pais=4");//.$_REQUEST['id_pais']);
while($Fila=mysqli_fetch_assoc($Consulta1)){
$regiones[] = $Fila;
//echo json_encode($Fila);
}
echo json_encode($regiones);
}
?>
Well, my problem it's that I really don't know how the first really works :D, but when I'm calling url:datos.php=ad this block doesn't work :/
First, you will find it helpful to review these simple examples about AJAX. Do not just read them, copy them to your server and make them work. Change a few names or values -- see how they work.
AJAX request callback using jQuery
Next, here is a post that gives an overview to how PHP / web page / AJAX all work together. Take a few minutes and read it carefully. See if you can follow the logic. I bet the lightbulb will come on for you.
PHP - Secure member-only pages with a login system
Make your code as standard as possible. Don't take any shortcuts. Use the full $.ajax() structure, not the shortcuts of $.post() or $.get() (these are both shortcut forms of $.ajax(). Don't skip anything. As you get better, you can start to take some shortcuts. But for now, make sure your AJAX code block looks like this:
var var_value = $('#someElement').val();
$.ajax({
type: 'post',
url: 'your_ajax_processor.php',
data: 'post_var_name=' +var_value,
success: function(dataz){
if (dataz.length) alert(dataz);
$('body').append(dataz);
}
});
In your PHP, you will receive the value you posted in the $_POST array variable. If, in AJAX, you named your variable post_var_name (as we did in the example above), then that is how you access the contents:
$myVar = $_POST['post_var_name'];
When you are having trouble, a great idea is to put in some tests. (1) On the PHP side, comment out everything and at the top put in an echo command, like:
<?php
echo 'I got here';
die();
Back on the web page, in the AJAX success function, just alert what you get:
success: function(d){
alert(d);
}
At that point, you know two things:
Your AJAX -to- PHP communications are working, and
You see what value got passed over to PHP.
Then, you might do something like this
js/jQuery:
var var_value = $('#someElement').val();
$.ajax({
type: 'post',
url: 'your_ajax_processor.php',
data: 'post_var_name=' +var_value,
success: function(dataz){
if (dataz.length) alert(dataz);
$('body').append(dataz);
}
});
PHP:
<?php
$myVar = $_POST['post_var_name'];
//Now you can do something with variable `$myVar`, such as:
$out = '
<div class="red-background"> '.$myVar.' </div>
';
//This content is received in the AJAX code block using the variable name you specified: "dataz"
echo $out;
is this in french? lol, luckily it's still all code.
try this:
inside of your success(datos1) function replace datos1 with datos1.data. Ajax gives you the whole response, you just want the data from the response generally.
success:function(datos1){
console.log(datos1);
console.log(datos1.data);
for(x = 0;x<=datos1.data.length;x++){
//$("#PAIS").append("<option value='"+datos.data[x].id_pais+"'>"+datos.data[x].pais+"</option>");
$("#REGION").append(new Option( datos.data[x].region, datos.data[x].id_region));
}

Ajax gets stuck in the beforeSend phase and does not send data to PHP

I have a bit of an issue here - I am quite familiar with PHP, but a novice where it concerns jquery and ajax and I have an issue on which I am breaking my teeth on for a week now, so I wonder if you could help me.
I have a big form with about 25 fields to fill in by users in order to create their profile page on my site. I am using jquery to validate all required fields and want to use Ajax to post the data to PHP which then inserts it in a table on the DB.
The problem is that Ajax gets stuck in the "beforeSend" routine and does not send the values of the fields to PHP and nothing gets inserted. What am I doing wrong?
Here is my code:
(form has the id "creaform" and the code contains a bunch of validation code which all works and is irrelevant for the questions, so I left that out)
$(document).ready(function() {
$("#createbtn").click(function (e) {
var self = this;
$.ajax({
type : "POST",
url : "profilereg.php",
data : $('#creaform').serialize(),
beforeSend : function() {
$(self).hide();
$('#creastatus').html( "<img src='mysuperduperanimatedgif.gif'/>" );
},
success : function(html){
var response = "Your data has been saved. You will now be taken to your profile page.
$('#creastatus').html( response );
}
});
}
});
});
And here is the receiving PHP file:
(be aware that this is still in the development phase - once this is working, I will add protection agains sql injection to the PHP - first want to have it working)
include("db_conx.php");
$_uname = "TestUser";
$_fname = $_POST['fname'];
$_lname = $_POST['lname'];
$_email = $_POST['email'];
$_wmail = $_POST['wmail'];
$_gender = $_POST['gender'];
$_country = $_POST['country'];
$_dob = $_POST['datepicker'];
$_aboutme = $_POST['aboutme'];
$_genre1 = $_POST['genre1'];
$_genre2 = $_POST['genre2'];
$_genre3 = $_POST['genre3'];
$_style = $_POST['style'];
$today = date("d M Y, G:i");
$_lastvisit = $today;
$sql = "INSERT INTO `uuu`(`username`, `fname`, `lname`,
`email`, `wriyonmail`, `gender`, `dob`, `country`, `genre1`, `genre2`,
`genre3`, `style`, `lavis`, `aboutme`) VALUES ('$_uname', '$_fname',
'$_lname', '$_email', '$_wmail', '$_gender', '$_dob', '$_country',
'$_genre1', '$_genre2', '$_genre3', '$_style', '$_lastvisit', '$_aboutme')";
Again, what is wrong with this - it gets stuck in the beforeSend display of the animated gif. When I remove the beforeSend, it just does not do anything. Any help would be greatly appreciated :) Thanks!
John
Try changing
var response = "Your data has been saved. You will now be taken to your profile page.
to
var response = "Your data has been saved. You will now be taken to your profile page."
You seem to be missing the closing quotation mark which will cause a script error
Try this
$(document).ready(function() {
$("#createbtn").click(function (e) {
$.ajax({
type : "POST",
url : "profilereg.php",
data : $('#creaform').serialize(),
beforeSend : function() {
$(self).hide();
$('#creastatus').html( "<img src='mysuperduperanimatedgif.gif'/>" );
},
success : function(html){
var response = "Your data has been saved. You will now be taken to your profile page.";
$('#creastatus').html( response );
}
});
});
});
Sorry for getting back at you guys so late - been very busy last couple of days. I have fixed this issue by making it just a standard HTML and PHP-post with some jquery functionality hanging around it to give the user the IMPRESSION that ajax is doing the thing. It waits before submitting, showing a please wait thingie and them redirects to the page it's supposed to go. It inserts the data in all tables, except one, but I will figure that out. In the meantime thanks a million for your replies and efforts to try to solve this. Thanks!

Strange output in JSON that I make in my PHP after an AJAX call

I am a bit new at this and totally messing something up. I have a PHP result set through which I iterate like this:
$rows = array();
while($r = mysql_fetch_assoc($result))
{
$rows[] = $r;
}
echo json_encode($rows);
and then I output it like this in jQuery code:
success: function(json)
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
// Here can update the right side of the screen with the newly entered information
alert (json);
var ob = $.parseJSON(json);
alert (ob.creator_member_id);
alert (ob.problem_title);
alert (ob.problem_description);
alert (ob.problem_date);
}
But there is an error on the var ob = $.parseJSON(json); line it seems. My JS console gives this error:
Uncaught TypeError: Object function (D,E){return new n.fn.init(D,E)} has no method 'parseJSON'
What can this mean and how can I fix this?
Thanks!!
If you are getting JSON results via jQuery ajax call you don't need parsing resultant json - jQuery does it for you.
Just specify the
dataType: 'json'
[http://api.jquery.com/jQuery.ajax/], and your success handler will have the already parsed object.
If you want parsing JSON anywhay, try adding json2.js to your project. You'll have to call JSON.parse(json) then.
I'm new to Jquery, too. eval is just plain JS and it suits my needs. I don't see any evil with this code but of course it's possible to inject bad code into a response. Probably it's not very good practise. It can be exploited for a reverse shell for example.

Categories