Ajax getting response undefined and Uncaught ReferenceError - php

Code:
query = "http://localhost:8080/working_login.php?name=" + name + "&password=" + pass;
console.log(query);
$.ajax({
type: "GET",
url: query,
dataType: "script",
success: function(data){
console.log(data);
console.log("success");
},
error:function (msg) {
console.log("error on page");
}
});
I am getting undefined in data and as I am returning 'valid_user' from the server side made in php, getting error.
Uncaught ReferenceError: valid_user is not defined
(anonymous function)
Php server side code:
$sql = "SELECT id FROM users WHERE name ='$name' AND password = '$password';";
$result = mysql_query($sql) or die('Can not Register user' . $sql );
$rows = mysql_num_rows($result);
if($rows > 0)
{
echo("valid_user");
exit();
}
else
{exit("not valid user");}

when using the script dataType in the jquery ajax reqeust, the returned result is interpreted as javascript code, but you return plain text
simply change dataType: "script" to dataType: "text".

You probably didn't mean to tell jQuery that you were expecting a script in return. What's being returned isn't a properly formatted script, so it's giving you an error when the browser parses as a script.
You could just do the following:
$.get("http://localhost:8080/working_login.php?name=" + name + "&password=" + pass, function(data) {
if(data == 'success')
{
alert("Success");
}
else
{
alert("Failed");
}
});

Related

Ajax success function not working with json answer

If I set dataType to 'json' and inside my PHP file I print whatever I want (event a letter), success function works, but if I don't print anything else besides the JSON I need, stops working. I can't handle my data with something else printed, because it turns the answer into HTML, instead of JSON. I'm able to see in Network -> Answer the JSON file (only when I don't print anything else beside the JSON), but I don't know why I can't even do an alert in success function when that is the case.
This is my ajax, which only works because I'm printing 'true' on the server:
$(document).on("click", "#btnEditarInstructor", function(event) {
event.preventDefault();
let rfc = $(this).attr("value");
$.ajax({
type: "POST",
url: "../utils/ajax/ajax_consulta_instructor.php",
data: {
rfc: rfc,
},
dataType: "json",
succes: function(response) {
if (response == true) {
// alert(response);
}
},
error: function(request, status, error) {
var val = request.responseText;
alert("error" + val);
alert(status);
alert(error);
},
});
})
This is my PHP code:
$rfc = $_POST['rfc'];
$sql = "SELECT * FROM instructores WHERE rfc = '$rfc'";
$sql_run = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($sql_run)) {
echo "true";
$datos['status'] = 'OK';
$datos['nombre'] = $row['nombre'];
$datos['apellidos'] = $row['apellidos'];
$datos['email'] = $row['email'];
$datos['tipo_promotor'] = $row['tipo_promotor'];
echo json_encode($datos);
}
By the way, with that code, I get this error on the alert:
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 5 of the JSON data
I'm using jQuery 3.6.0 (https://code.jquery.com/jquery-3.6.0.js)
If you're returning JSON, you can only echo the JSON once, not each time through the loop.
If there can only be one row, you don't need the while loop. Just fetch the row and create the JSON.
You also can't echo anything else, so the echo "true"; lines are breaking it.
And your code is wide open to SQL-injection. You should use a prepared statement with a parameter, which I've shown how to do.
$rfc = $_POST['rfc'];
$stmt = $con->prepare("SELECT * FROM instructores WHERE rfc = ?");
$stmt->bind_param("s", $rfc);
$stmt->execute();
$sql_run = $stmt->get_result();
$datos = [];
if($row = mysqli_fetch_array($sql_run)){
$datos['status'] = 'OK';
$datos['nombre'] = $row['nombre'];
$datos['apellidos'] = $row['apellidos'];
$datos['email'] = $row['email'];
$datos['tipo_promotor'] = $row['tipo_promotor'];
}
echo json_encode($datos);
$(document).on("click", "#btnEditarInstructor", function (event) {
event.preventDefault();
let rfc = $(this).attr("value");
$.ajax({
type: "POST",
url: "../utils/ajax/ajax_consulta_instructor.php",
data: {
rfc: rfc,
},
dataType: "json",
success: function (response) {
if (response == true) {
// alert(response);
}
},
error: function (request, status, error) {
var val = request.responseText;
alert("error" + val);
alert(status);
alert(error);
},
});

SyntaxError: Unexpected token C in JSON at position 0 when ajax callback json

From the network debugger, in php file, it shows {message: "Success", data: {Name: "admin"}}". However, when ajax callback, it fails. Can anyone help fix these problem that troubles me a long time. Thank you very much.
There is the errors message generated by ajax.
OK
parsererror
SyntaxError: Unexpected token C in JSON at position 0
Ps: In MYSQL database, Username & Password are varchar(20)
Html:
function User_Login(){
var Username = document.getElementById("Username").value;
var Password = document.getElementById("Password").value;
$.ajax({
type: 'POST',
url: 'Api_Login.php',
dataType: 'json',
data: {Username : Username , Password : Password},
//call back method
success: function(returnData){
JSON.parse(returnData.message);
console.log(returnData);
if (returnData.message ==='Success') {
window.location="homepage/index.html";
} else {
window.alert("No such account or wrong password");
}
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
}
PHP:
$sql = "SELECT Name
FROM `$tbName`
WHERE Name = '$userID'
AND Password = '$UserPassword' ";
$result = $conn->query($sql);
$data = $result->fetch_assoc();
if ($data){
echo json_encode(
array("message" => "Success", "data" => $data));
}else {
echo json_encode(
array("message" => "Fail"));
}
Setting datatype as json will force jQuery to convert response to JS Object. It will throw error if server has responded back with invalid json.
Again, the returnData will be a JS object, you don't need to run JSON.parse on it.
Try with this.
success: function(returnData){
console.log(returnData);
if (returnData.message ==='Success') {
window.location="homepage/index.html";
} else {
window.alert("No such account or wrong password");
}
}
You can make sure what your server is responding by removing setting line
dataType: 'json',
See what id logged in console.
$.ajax function returns JSON object {message: "Success", data: {Name: "admin"}}we can not call JSON.parse() on JSON object.
Just remove the line JSON.parse(returnData.message); from your code and it is working fine.

how to access returned data in ajax from php?

OK I might have some syntax problem that I cant locate but I think something else is the problem.
I have a .php file that selects multiple values from a database and than that result is 'echo' back to the ajax call where it comes from.
The .php looks like this:
<?php
require("../config/db.php");
$db = mysql_connect(DB_HOST, DB_USER, DB_PASS)or die("Error connecting to database.");
mysql_query("SET NAMES UTF8");
mysql_select_db(DB_NAME, $db)or die("Couldn't select the database.");
$query = "SELECT online_users, chat_messages, cards_order FROM track_changes LIMIT 1";
$result = mysql_query($query, $db) or die(mysql_error().': '.$query);
$row = mysql_fetch_array($result);
$changes = array('online_users'=>$row['online_users'],
'chat_messages'=>$row['chat_messages'],
'cards_order'=>$row['cards_order']);
echo json_encode($changes, JSON_FORCE_OBJECT);
?>
than the jQuery ajax call looks like this:
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '/kanbannew/php_scripts/track_changes.php',
data: { },
async: false,
success: function (data) {
console.log(data);
var users = data.online_users;
var chat = data.chat_messages;
var cards = data.cards_order;
console.log("Online users: " + users + "\nChat messages: " + chat + "\nCards order: " + cards);
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // ajax end
});
The problem is in the first alert i get the key:values like
{"online_users":"0","chat_messages":"0","cards_order":"0"}
but in the second alert i get undefined for every value:
Online users: undefined
Chat messages: undefined
Cards order: undefined
This prints are from chrome conzole.
Any ideas why I cant access the zero's??
Add dataType.
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '/kanbannew/php_scripts/track_changes.php',
data: { },
dataType: 'json',
async: false,
success: function (data) {
console.log(data);
var users = data.online_users;
var chat = data.chat_messages;
var cards = data.cards_order;
console.log("Online users: " + users + "\nChat messages: " + chat + "\nCards order: " + cards);
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // ajax end
});
You can add
header('Content-type: application/json');
to your php code (before you echo anything) to achieve the same result what can be helpful if you expect your code to be consumed by third parties. But i would definitly add the dataType as well as suggested by alexey

ajax - check if a username exists + return message if it does

im trying to check if a username a user wants is already taken without having to send the form, basically onBlur of the username field.
I'm having some trouble and have a few questions.
I have my input field plus js:
<script src="js/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#username').on('blur', checkdb);
function checkdb(){
var desiredUsername = $(this).val();
$.ajaxSetup({
url: "check-db.php",
type: "POST",
});
$.ajax({
data: 'desiredUsername='+desiredUsername,
success: function (msg) {
alert (msg);},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert('Error submitting request.');
}
});
}
});
</script>
<input type="text" name="username" id="username">
and my check-db.php file:
$mysqli = mysqli_connect("localhost","connection info");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$desiredUsername = $_POST['desiredUsername'];
$stmt = $mysqli->prepare("SELECT * FROM users WHERE username = '?' ");
$stmt->bind_param('s', $desiredUsername);
$stmt->execute();
firstly: im getting an error from my php code, 'number of variables doesnt match number of parameters in prepared statement', which im a bit confused about? I have 1 variable and 1 peramater, don't i?
then, once this is actually working, how do I send a message/ variable back to the input page? so if the username is taken I can say so, or if its available say so?
thanks!
On the server size (PHP in your case), simply echo the things you want to pass to the client side (Javascript) like this :
echo json_encode($datas); //can be array or whatever
Then on the Client side :
$.ajax({
method: 'POST',
dataType:'json',
data: {'username' : desiredUsername}, //then getting $_POST['username']
success: function(datas) {
console.log(datas); //Your previous data from the server side
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log(textStatus);
}
});
try
function checkdb(){
var desiredUsername = $(this).val();
$.ajaxSetup({
url: "check-db.php",
type: "POST",
});
$.ajax({
data: {
desiredUsername: desiredUsername
},
success: function (msg) {
alert(msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert('Error submitting request.');
}
});
}
You have an error when sending the data, you should send a JS Object as data, like this:
data: { desiredUsername: desiredUsername },

jquery ajax sending json to php error

Okay so here is my ajax request:
$("#scoreForm").submit(function(e){
e.preventDefault();
var nickName = $('#nickName').val();
var gameScore = parseInt($('#gameScore').text());
var result = { 'result' : '{ "nick":"'+nickName+'", "score":'+gameScore+' }' };
//var result = { "nick":nickName, "score":gameScore };
$.ajax({
url: "http://localhost:8888/snake/addScore.php",
type: "POST",
data: result,
//dataType: "jsonp",
success: function(data){
alert("siker");
},
error: function(jqXHR, textStatus, errorThrown) {
alert("bukta " + textStatus);
//console.log(data);
}
});
return false;
});
and my php process code:
$json_decoded = json_decode($_POST['result'],true);
//$nick = $_GET['nick'];
//$score = $_GET['score'];
$mysqli = new mysqli("localhost", "root", "root", "snake",8889);
//$mysqli->query("INSERT INTO scores(nickName,score) VALUES('".$nick."', ".$score.")");
$mysqli->query("INSERT INTO scores(nickName,score) VALUES('".$json_decoded['nick']."', ".$json_decoded['score'].")");
echo "true";
Now i got the data inserted into the database, but ajax still firing error event. i read that if i set the dataType to jsonp it will go trough , but then i get parse error, how do i get past that?
Wehn you access the $_POST variables in your php script, you need to refer to them the way they are packaged with the JSON object:
$_POST['nick']
$_POST['score']
If you want to refer to the items as $_POST['result'] and use your json decoding approach, youll need to package it this way:
var result = { result : { "nick":nickName, "score":gameScore } };

Categories