I'm a newbie in AJAX and i tried to make a simple MySQL query in AJAX but it doesn't work, the response is a 500 Internal Server error.
I searched for the answer on this forum and other websites but i've never found an answer for my problem.
Basically, on my app, the user writes a pseudo and click on 'play', and an AJAX function is called onClick, a function that make a simple MySQL query :
$.ajax({
url: "check_pseudo.php",
method: "GET",
data : { pseudo : input},
error: function() {
alert("Une erreur est survenue");
},
success: function(response) {
alert(response);
}
});
PHP / MySQL :
$pseudo = $_GET["pseudo"];
$req = $bdd->prepare('SELECT ? FROM pseudo');
$req->execute(array($pseudo));
$reponse = $req->fetch();
if ($reponse) {
echo "This pseudo does exist";
}else{
echo "Pseudo not found";
}
This code sends me 'GET http://localhost:8888/check_pseudo.php?pseudo=oianf 500 (Internal Server Error)' in the console debugger.
How could i solve this problem?
Merci :)
You can't do this:
$req = $bdd->prepare('SELECT ? FROM pseudo');
$req->execute(array($pseudo));
Using prepare() with a ? in it builds a query expecting additional input. You need to fill that ? with something. (check out PHP's mysqli::prepare).
You need to do something like:
$req = $bdd->prepare('SELECT ? FROM pseudo');
$req->bind_param("s", $pseudo);
$req->execute();
...but even that doesn't quite seem right. Usually we wouldn't be passing the fields to be selected inside query params. We would usually do something like this:
$.ajax({
url: "users.php",
method: "GET",
data : {user_id: input_id},
error: function() {
alert("Error! ...Something went wrong.");
},
success: function(response) {
alert(response);
}
});
Then inside users.php we would have:
$user_id = $_GET["user_id"];
$req = $bdd->prepare('SELECT * FROM users where user_id=?');
$req->bind_param("i", $user_id);
$req->execute();
$reponse = $req->fetch();
if ($reponse) {
echo "This user does exist";
} else {
echo "User not found";
}
Related
I'm building a simple forum on which I have a user details page with two text fields, one for the user's biography and another for his interests.
When the user clicks on the save icon, a handler on the jquery is suposed to call an ajax call to update the database with the new value of the biography/interests but the ajax call isn't being called at all and I can't figure it out since I don't find any problems with the code and would apreciate if someone could take a look at it.
this is the textarea:
<textarea rows="4" cols="50" id="biography" readonly><?php if($info['bio'] == "") echo "Não existe informação para mostrar";
else echo $info['bio']; ?></textarea>
Here is the icon the user clicks on:
<li style="display:inline;" class="infoOps-li"><img class="info-icons" id="save1" src="assets/icons/save.png" alt=""></li>
this is the jequery with the ajax call:
$("#save1").click(function(){
var bio = $("#biography").val();
alert(bio); //this fires up
$.ajax({
url:"assets/phpScripts/userBioInterest.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {functionName: "bio", info:bio},
success:function(result){
alert(result.abc); //this doesn't fire
}
});
$("#biography").prop("readonly","true");
});
I know that the jquery handler is being called correctly because the first alert is executed. The alert of the ajax success function isn't, so I assume that the ajax call isn't being processed.
On the php file I have this:
function updateBio($bio)
{
$user = $_SESSION['userId'];
$bd = new database("localhost","root","","ips-connected");
$connection = $bd->getConnection();
if($bio == "")
{
echo json_encode(array("abc"=>'empty'));
exit();
}
if($stmt = mysqli_prepare($connection,"UPDATE users SET biografia = ? WHERE user_id = ?"))
{
mysqli_stmt_bind_param($stmt,'si',$bio,$user);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo json_encode(array("abc"=>'successfuly updated'));
}
$bd->closeConnection();
}
if(isset($_POST['functionName']))
{
$function = $_POST['functionName'];
echo $function;
if(isset($_POST['info']))
$info = $_POST['info'];
if($function == "bio")
{
updateBio($info);
}
else if($function == "interest")
{
updateInterests($info);
}
}
Can anyone shed some light on why isn't the ajax call being called?
Thank you
EDIT: changed "function" to "functionName" in json data object as suggested.
A possible problem is dued to a wrong parsing of the PHP output (for example due to a PHP error). You are reading the output as JSON, so if the output is not a JSON, success callback will not be triggered.
$("#save1").click(function(){
var bio = $("#biography").val();
alert(bio); //this fires up
$.ajax({
url:"assets/phpScripts/userBioInterest.php",
type: "post", //request type,
dataType: 'json',
data: {function: "bio", info:bio},
success:function(result){
alert(result.abc); //this doesn't fire
},
error: function(result){
alert("An error has occurred, check the console!");
console.log(result);
},
});
$("#biography").prop("readonly","true");
});
Try with this code, and check if an error is printed to the console.
You can use complete too, check here: http://api.jquery.com/jquery.ajax/
I am using ajax call to grab some data from my mysql database. This is my ajax call:
$.ajax({
type: "POST",
url: "fetch.php",
data: id,
success: function(msg) {
var record = JSON.parse(msg);
$("#name").val(record.name);
$("#description").val(record.description);
switch(record.category) {
case ("Residential"):
$("#category").val("residential");
break;
case ("Modernisation & Domestic Extensions"):
$("#category").val("modernisation");
break;
case ("Feasibility Layouts"):
$("#category").val("feasibility");
break;
case ("Master Planning"):
$("category").val("master");
break;
default:
$("category").val("");
};
switch(record.featured) {
case ("y"):
$("#featured").val("y");
break;
default:
$("featured").val("n");
};
}
})
and this is my php file:
<?php
$dbc = mysqli_connect('XX','XX','XX','XX');
$id = $_POST['id'];
if($dbc) {
$row = fetchDataFromRecordWithId($dbc,$id);
}
else {
echo 'Database error';
}
function fetchDataFromRecordWithId($dbc,$id) {
$q = "SELECT * FROM Projects WHERE id = ".$id;
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
mysqli_close($dbc);
return $row;
}
echo json_encode($row);
?>
Everything work flawless but soon when I try to add if statement in my php file to check if there is any POST data than my ajax call is not getting any response. I tried different methods :
<?php if(isset($_POST)) { .. my whole php code here .. } ?>
<?php if(!empty($_POST)) { ..my whole php code here .. } ?>
<?php if($_POST) { .. my whole php code here .. } ?>
<?php if($_POST['id']) { .. my whole php code here .. } ?>
but nothing work! Ajax call is not getting json data back when I will use any of these if statements listed above.
I could not check for POST data and leave it like it is but I want to do is in proper way.
It seems like if statement is not executed (but POST data must be there as I am able to fetch $_POST['id'] value when if statement not used).
I also tried to put echo json_encode($row) outside if statement but it didn't help either. Any ideas what is wrong?
$.ajax({
type: "POST",
url: "fetch.php",
data: id,
http://api.jquery.com/jQuery.ajax/:
data: [...] Object must be Key/Value pairs.
So make that line
data: { id : id },
instead, then it should work.
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
die("Invalid request method: " . $_SERVER['REQUEST_METHOD']);
}
if (isset($_POST['id'])) {
... db code here ...
}
also note that your are WIDE open for SQL injection attacks.
you try follow testings on your code
check whether you have have the right request page for php .
see in google chromes right click inspect element then console tab any errors are showing
in your suceess:function(msg) add $("body").append(msg)
add function before success:function(result) {}
error:function(xhr,err){
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
I've been trying to figure out what I have done wrong but when I use my JavaScript Console it shows me this error : Cannot read property 'success' of null.
JavaScript
<script>
$(document).ready(function() {
$("#submitBtn").click(function() {
loginToWebsite();
})
});
</script>
<script type="text/javascript">
function loginToWebsite(){
var username = $("username").serialize();
var password = $("password").serialize();
$.ajax({
type: 'POST', url: 'secure/check_login.php', dataType: "json", data: { username: username, password: password, },
datatype:"json",
success: function(result) {
if (result.success != true){
alert("ERROR");
}
else
{
alert("SUCCESS");
}
}
});
}
</script>
PHP
$session_id = rand();
loginCheck($username,$password);
function loginCheck($username,$password)
{
$password = encryptPassword($password);
if (getUser($username,$password) == 1)
{
refreshUID($session_id);
$data = array("success" => true);
echo json_encode($data);
}
else
{
$data = array("success" => false);
echo json_encode($data);
}
}
function refreshUID($session_id)
{
#Update User Session To Database
session_start($session_id);
}
function encryptPassword($password)
{
$password = $encyPass = md5($password);
return $password;
}
function getUser($username,$password)
{
$sql="SELECT * FROM webManager WHERE username='".$username."' and password='".$password."'";
$result= mysql_query($sql) or die(mysql_error());
$count=mysql_num_rows($result) or die(mysql_error());
if ($count = 1)
{
return 1;
}
else
{
return 0;;
}
}
?>
I'm attempting to create a login form which will provide the user with information telling him if his username and password are correct or not.
There are several critical syntax problems in your code causing invalid data to be sent to server. This means your php may not be responding with JSON if the empty fields cause problems in your php functions.
No data returned would mean result.success doesn't exist...which is likely the error you see.
First the selectors: $("username") & $("password") are invalid so your data params will be undefined. Assuming these are element ID's you are missing # prefix. EDIT: turns out these are not the ID's but selectors are invalid regardless
You don't want to use serialize() if you are creating a data object to have jQuery parse into formData. Use one or the other.
to make it simple try using var username = $("#inputUsername").val(). You can fix ID for password field accordingly
dataType is in your options object twice, one with a typo. Remove datatype:"json", which is not camelCase
Learn how to inspect an AJAX request in your browser console. You would have realized that the data params had no values in very short time. At that point a little debugging in console would have lead you to some immediate points to troubleshoot.
Also inspecting request you would likely see no json was returned
EDIT: Also seems you will need to do some validation in your php as input data is obviously causing a failure to return any response data
Try to add this in back-end process:
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: application/json');
header('Content-type: text/json');
hope this help !
i testet on your page. You have other problems. Your postvaribales in your ajax call are missing, because your selectors are wrong!
You are trying to select the input's name attribute via ID selector. The ID of your input['name'] is "inputUsername"
So you have to select it this way
$('#inputUsername').val();
// or
$('input[name="username"]').val();
I tried it again. You PHP script is responsing nothing. Just a 200.
$.ajax({
type: 'POST',
url: 'secure/check_login.php',
dataType: "json",
data: 'username='+$("#inputUsername").val()+'&password='+$("#inputPassword").val(),
success: function(result) {
if (result.success != true){
alert("ERROR");
} else {
alert("HEHEHE");
}
}
});
Try to add following code on the top of your PHP script.
header("Content-type: appliation/json");
echo '{"success":true}';
exit;
You need to convert the string returned by the PHP script, (see this question) for this you need to use the $.parseJSON() (see more in the jQuery API).
I keep getting the error alert. There is nothing wrong with the MYSQL part, the query gets executed and I can see the email addresses in the db.
The client side:
<script type="text/javascript">
$(function() {
$("form#subsribe_form").submit(function() {
var email = $("#email").val();
$.ajax({
url: "subscribe.php",
type: "POST",
data: {email: email},
dataType: "json",
success: function() {
alert("Thank you for subscribing!");
},
error: function() {
alert("There was an error. Try again please!");
}
});
return false;
});
});
</script>
The server side:
<?php
$user="username";
$password="password";
$database="database";
mysql_connect(localhost,$user,$password);
mysql_select_db($database) or die( "Unable to select database");
$senderEmail = isset( $_POST['email'] ) ? preg_replace( "/[^\.\-\_\#a-zA-Z0-9]/", "", $_POST['email'] ) : "";
if($senderEmail != "")
$query = "INSERT INTO participants(col1 , col2) VALUES (CURDATE(),'".$senderEmail."')";
mysql_query($query);
mysql_close();
$response_array['status'] = 'success';
echo json_encode($response_array);
?>
You need to provide the right content type if you're using JSON dataType. Before echo-ing the json, put the correct header.
<?php
header('Content-type: application/json');
echo json_encode($response_array);
?>
Additional fix, you should check whether the query succeed or not.
if(mysql_query($query)){
$response_array['status'] = 'success';
}else {
$response_array['status'] = 'error';
}
On the client side:
success: function(data) {
if(data.status == 'success'){
alert("Thank you for subscribing!");
}else if(data.status == 'error'){
alert("Error on query!");
}
},
Hope it helps.
Just so you know, you can use this for debugging. It helped me a lot, and still does
error:function(x,e) {
if (x.status==0) {
alert('You are offline!!\n Please Check Your Network.');
} else if(x.status==404) {
alert('Requested URL not found.');
} else if(x.status==500) {
alert('Internel Server Error.');
} else if(e=='parsererror') {
alert('Error.\nParsing JSON Request failed.');
} else if(e=='timeout'){
alert('Request Time out.');
} else {
alert('Unknow Error.\n'+x.responseText);
}
}
Some people recommend using HTTP status codes, but I rather despise that practice. e.g. If you're doing a search engine and the provided keywords have no results, the suggestion would be to return a 404 error.
However, I consider that wrong. HTTP status codes apply to the actual browser<->server connection. Everything about the connect went perfectly. The browser made a request, the server invoked your handler script. The script returned 'no rows'. Nothing in that signifies "404 page not found" - the page WAS found.
Instead, I favor divorcing the HTTP layer from the status of your server-side operations. Instead of simply returning some text in a json string, I always return a JSON data structure which encapsulates request status and request results.
e.g. in PHP you'd have
$results = array(
'error' => false,
'error_msg' => 'Everything A-OK',
'data' => array(....results of request here ...)
);
echo json_encode($results);
Then in your client-side code you'd have
if (!data.error) {
... got data, do something with it ...
} else {
... invoke error handler ...
}
In order to build an AJAX webservice, you need TWO files :
A calling Javascript that sends data as POST (could be as GET) using JQuery AJAX
A PHP webservice that returns a JSON object (this is convenient to return arrays or large amount of data)
So, first you call your webservice using this JQuery syntax, in the JavaScript file :
$.ajax({
url : 'mywebservice.php',
type : 'POST',
data : 'records_to_export=' + selected_ids, // On fait passer nos variables, exactement comme en GET, au script more_com.php
dataType : 'json',
success: function (data) {
alert("The file is "+data.fichierZIP);
},
error: function(data) {
//console.log(data);
var responseText=JSON.parse(data.responseText);
alert("Error(s) while building the ZIP file:\n"+responseText.messages);
}
});
Your PHP file (mywebservice.php, as written in the AJAX call) should include something like this in its end, to return a correct Success or Error status:
<?php
//...
//I am processing the data that the calling Javascript just ordered (it is in the $_POST). In this example (details not shown), I built a ZIP file and have its filename in variable "$filename"
//$errors is a string that may contain an error message while preparing the ZIP file
//In the end, I check if there has been an error, and if so, I return an error object
//...
if ($errors==''){
//if there is no error, the header is normal, and you return your JSON object to the calling JavaScript
header('Content-Type: application/json; charset=UTF-8');
$result=array();
$result['ZIPFILENAME'] = basename($filename);
print json_encode($result);
} else {
//if there is an error, you should return a special header, followed by another JSON object
header('HTTP/1.1 500 Internal Server Booboo');
header('Content-Type: application/json; charset=UTF-8');
$result=array();
$result['messages'] = $errors;
//feel free to add other information like $result['errorcode']
die(json_encode($result));
}
?>
Server side:
if (mysql_query($query)) {
// ...
}
else {
ajaxError();
}
Client side:
error: function() {
alert("There was an error. Try again please!");
},
success: function(){
alert("Thank you for subscribing!");
}
adding to the top answer: here is some sample code from PHP and Jquery:
$("#button").click(function () {
$.ajax({
type: "POST",
url: "handler.php",
data: dataString,
success: function(data) {
if(data.status == "success"){
/* alert("Thank you for subscribing!");*/
$(".title").html("");
$(".message").html(data.message)
.hide().fadeIn(1000, function() {
$(".message").append("");
}).delay(1000).fadeOut("fast");
/* setTimeout(function() {
window.location.href = "myhome.php";
}, 2500);*/
}
else if(data.status == "error"){
alert("Error on query!");
}
}
});
return false;
}
});
PHP - send custom message / status:
$response_array['status'] = 'success'; /* match error string in jquery if/else */
$response_array['message'] = 'RFQ Sent!'; /* add custom message */
header('Content-type: application/json');
echo json_encode($response_array);
I had the same issue. My problem was that my header type wasn't set properly.
I just added this before my json echo
header('Content-type: application/json');
...you may also want to check for cross site scripting issues...if your html pages comes from a different domain/port combi then your rest service, your browser may block the call.
Typically, right mouse->inspect on your html page.
Then look in the error console for errors like
Access to XMLHttpRequest at '...:8080' from origin '...:8383' has been blocked by
CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested
resource.
i have a jquery ajax form.
i have validation at server side for repeated username and email ID.
which works fine without jquery/ajax.
in my php code i have used die() to return if any error occurs. my main problem is at ajax
here is the code
$(document).ready(function () {
$("form#regist").submit(function () {
var str = $("#regist").serialize();
$.ajax({
type: "POST",
url: "submit1.php",
data: $("#regist").serialize(),
success: function () {
$("#loading").append("<h2>you are here</h2>");
}
});
return false;
});
});
The success function works properly. if my data is valid then it is added in the db, if my data is repeated then it is not added in the db. Now what i want to know is how do i return the error from my php file and use it at success event. Thanks in advance..
edit : this is how my php script looks
$query = "SELECT username from userdetails WHERE username = '$username'";
$q = mysql_query($query) or die("error" . mysql_error());
$numrows = mysql_num_rows($q);
if($numrows > 0)
{
die("username already exixt");
//should i put something like this
//$error = "username already exists";
//return $error; --->> i am not sure about this..
}
thanks in advance
Php side:
if($numrows > 0)
{
echo "username already exist";
}
Javascript side:
success: function(msg)
{
if(msg == 'username already exist') alert(msg);
}
But this is so crude, If you plan to develop this further try to read some articles on JSON, so you can use json to communicate to server side. And also you should try to use some default error controlling, like return an array with php:
echo json_encode(array('error' => true, 'notice' => 'username exists'));
Then on the javascript side (jquery), use json ajax request and always check if error variable is true or not, if it is maybe you can use a default function for error controlling.
Hope this helped.
In the function definition which you have done like:
success: function(){
introduce a parameter like: success: function(retVal){
Now in the function you can check for the value of retVal.
Say, you return from your PHP script, "successful" for success case and "this email exists" for failure.
Now you can directly compare this here and do whatever you want to, like:
if(retVal == 'this email exists')
{
window.alert('please re-enter the email, this record exists!');
}
and so on...
Hope this helps.
$(document).ready(function () {
$("form#regist").submit(function () {
var str = $("#regist").serialize();
$.ajax({
type: "POST",
url: "submit1.php",
data: $("#regist").serialize(),
success: function (msg) {
alert(msg);
}
});
return false;
});
});
Here from server side send the message and show it, how i have shown it :)