I am getting the internal server error 500 on my ajax call. I am using a LAMP stack as my server and I've checked the permissions so that can't be my error.
Here's my javascript code:
//$('#addAthleteForm').trigger("reset");
//$(document).ready(function() {
$(function () {
$("#dialog").dialog({
autoOpen: false,
maxWidth: 600,
maxHeight: 500,
width: 500,
height: 460,
close: function () {
$('#addAthleteForm').trigger("reset");
}
});
$("#addAthlete").on("click", function () {
$("#dialog").dialog("open");
});
$("#addAthleteForm").submit(function (e) {
e.preventDefault();
var postData = jQuery(this).serialize();
$("#dialog").dialog("close")
$.ajax({
type: "POST",
url: "AddAthletes.php",
dataType: 'json',
data: postData,
success: function (data) {
alert(data);
},
error: function (jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
$("#editAthlete").submit(function (e) {
e.preventDefault();
var editData = jQuery(this).serialize();
$.ajax({
type: "POST",
url: "GetAthlete.php",
dataType: 'json',
data: editData,
success: function (data) {
var form = document.forms['addAthleteForm'];
form.fname.value = data.fname;
form.lname.value = data.lname;
form.school.value = data.school;
form.agegrp.value = data.agegrp;
}
});
$("#dialog").dialog("open");
});
})
and here's my php code:
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$school = $_POST['school'];
$agegrp = $_POST['agegrp'];
$db = mysqli_connect("localhost", "root", "passwrd","site");
if(!$db){
exit("Error in database connection");
}
else{
$result = mysqli_query($db, "SELECT * FROM `School` WHERE `SchoolLong`='$school'");
$row = mysqli_fetch_array($result));
$SchoolID = $row['SchoolID'];
$result = mysqli_query($db,"SELECT * FROM `AgeGroup` WHERE `AgeGroupLong`='$agegrp'");
$row = mysqli_fetch_array($result));
$AgeGroupID = $row['AgeGroupID'];
mysqli_query($db, "INSERT INTO `Athlete` (`NameFirst`,`NameLast`, `SchoolID`, `AgeGroupID`) VALUES ('$fname', '$lname', $schoolID, $agegrpID)");
}
echo json_encode($fname);
?>
I'm not to sure where this error is coming from. The code used to work.
Syntax error in below line:-
$row = mysqli_fetch_array($result));
It should be :-
$row = mysqli_fetch_array($result);
same mistake for below mysqli_fetch_array()
Your corrected block of code are:-
$result = mysqli_query($db, "SELECT * FROM `School` WHERE `SchoolLong`='$school'");
$row = mysqli_fetch_array($result);
$SchoolID = $row['SchoolID'];
$result = mysqli_query($db,"SELECT * FROM `AgeGroup` WHERE `AgeGroupLong`='$agegrp'");
$row = mysqli_fetch_array($result);
$AgeGroupID = $row['AgeGroupID'];
Related
I keep receiving this JSON error,i think it has something to do with html tags or any other tags that conflicts with it.
Here is my PHP Code:
<?php
require_once("connection.php");
class AddAdminUPController extends Connection{
public function addAdminUP(){
include "function.php";
$username = cleanData($_POST['username']);
$password = cleanData($_POST['password']);
if (!empty($username)){
if(!empty($password)){
if(strlen($password) > 8){
$select_query = "select * from sample_user where user_name = ?";
$stmt = $this->db->prepare($select_query);
$stmt->bindParam(1,$username);
if($stmt->execute()){
if($stmt->rowCount() <= 0){
$password = password_hash($password,PASSWORD_BCRYPT,array('cost' => 12));
$create_query = "insert into sample_user(user_name,password)values(?,?)";
$stmt = $this->db->prepare($create_query);
$stmt->bindParam(1,$username);
$stmt->bindParam(2,$password);
if($stmt->execute()){
echo "<script>".
"Materialize.toast('Created SuccessFully!', 5000, 'green')"
."</script>";
echo "<script>".
"$('#add_admin_up_form').hide();".
"$('#add_admin_up').hide();";
?>
$(".enrollment_title").html("<i class='material-icons'>fingerprint</i> Enroll Fingerprint");
<?php
echo "</script>";
include 'flexcode_sdk/include/global.php';
include 'flexcode_sdk/include/function.php';
if(isset($_GET['action']) && $_GET['action'] == 'add'){
$lastID = $this->db->lastInsertId();
?>
<script type="text/javascript">
$('title').html('User');
function user_register(user_id, user_name) {
$('body').ajaxMask();
regStats = 0;
regCt = -1;
try
{
timer_register.stop();
}
catch(err)
{
console.log('Registration timer has been init');
}
var limit = 4;
var ct = 1;
var timeout = 5000;
timer_register = $.timer(timeout, function() {
console.log("'"+user_name+"' registration checking...");
user_checkregister(user_id,$("#user_finger_"+user_id).html());
if (ct>=limit || regStats==1)
{
timer_register.stop();
console.log("'"+user_name+"' registration checking end");
if (ct>=limit && regStats==0)
{
alert("'"+user_name+"' registration fail!");
$('body').ajaxMask({ stop: true });
}
if (regStats==1)
{
$("#user_finger_"+user_id).html(regCt);
alert("'"+user_name+"' registration success!");
$('body').ajaxMask({ stop: true });
load('view_admin.php?action=add');
}
}
ct++;
});
}
function user_checkregister(user_id, current) {
$.ajax({
url : "view_admin.php?action=checkreg&user_id="+user_id+"¤t="+current,
type : "GET",
success : function(data)
{
try
{
var res = jQuery.parseJSON(data);
if (res.result)
{
regStats = 1;
$.each(res, function(key, value){
if (key=='current')
{
regCt = value;
}
});
}
}
catch(err)
{
alert(err.message);
}
}
});
}
</script>
<?php
$last_id_query = "select * from sample_user where user_id = ?";
$stmt = $this->db->prepare($last_id_query);
$stmt->bindParam(1,$lastID);
if ($stmt->execute()){
while($row = $stmt->fetch(PDO::FETCH_OBJ)){
$url_register =
base64_encode($base_path."register.php?user_id=".$row->user_id);
echo "<br><a href='finspot:FingerspotReg;$url_register' onclick=\"user_register('".$row->user_id."','".$row->user_name."')\" class='fw_button general_button btn waves-effect waves-light'>Register Fingerprint</a>";
}
}
}
elseif (isset ($_GET['action']) && $_GET['action'] == 'checkreg') {
$sql1 = "SELECT count(finger_id) as ct FROM sample_finger WHERE user_id=".$_GET['user_id'];
$result1 = mysql_query($sql1);
$data1 = mysql_fetch_array($result1);
if (intval($data1['ct']) > intval($_GET['current'])) {
$res['result'] = true;
$res['current'] = intval($data1['ct']);
}
else
{
$res['result'] = false;
}
echo json_encode($res);
}
else { echo "Parameter invalid..";}
}
else{
echo "<script>".
"Materialize.toast('Query Failed!', 5000, 'red')"
."</script>";
}
}
else{
echo "<script>".
"Materialize.toast('Username already exists!', 5000, 'red')"
."</script>";
}
}
else{
echo "<script>".
"Materialize.toast('Query Failed!', 5000, 'red')"
."</script>";
}
}
else{
echo "<script>".
"Materialize.toast('Password is too short!', 5000, 'red')"
."</script>";
}
}
else{
echo "<script>".
"Materialize.toast('Password is empty!', 5000, 'red')"
."</script>";
}
}
else{
echo "<script>".
"Materialize.toast('Username is empty!', 5000, 'red')"
."</script>";
}
}
}
$add_admin_up_controller = new AddAdminUPController;
echo $add_admin_up_controller->addAdminUP();
?>
I need help in fixing this kind of error. It keeps displaying:
SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at Function.jQuery.parseJSON (jquery.js:8520) at Object.success (eval at (jquery.js:339), :55:90) at fire (jquery.js:3148) at Object.fireWith [as resolveWith] (jquery.js:3260) at done (jquery.js:9314) at XMLHttpRequest.callback (jquery.js:9718)
You are returning plain text instead of JSON. In your ajax call put the response dataType: 'json' and the part of PHP:
header("Content-Type: application/json");
echo json_encode($res);
exit;
This error due to your responce is not in json format and your ajax request is expecting json responce .
You can change responce header by use dataType : 'text/html' in your ajax request.
Here in action .
function user_checkregister(user_id, current) {
$.ajax({
url : "view_admin.php?action=checkreg&user_id="+user_id+"¤t="+current,
type : "GET",
dataType: 'text/html',
success : function(data)
{
try
{
var res = jQuery.parseJSON(data);
if (res.result)
{
regStats = 1;
$.each(res, function(key, value){
if (key=='current')
{
regCt = value;
}
});
}
}
catch(err)
{
alert(err.message);
}
}
});
}
I can read Qrcode and what i want is to check if the text in qrcode is in remote database. I have a php file where I do some process to check if database is in mysql. But it does not work. below my code
/*part of js file
scan: function() {
console.log('scanning');
var scanner = cordova.require("cordova/plugin/BarcodeScanner");
scanner.scan( function (result) {
var rs= result;
$.ajax({
type: 'POST',
data: rs,
url: 'http://url/page.php',
success: function(data){
console.log(data);
document.getElementById("info").innerHTML = data;
},
error: function(){
console.log(data);
alert('error');
}
});
return false;
}, function (error) {
console.log("Scanning failed: ", error);
} );
}
/* My php file
<?php
// Create connection
$conn = mysql_connect($servername, $username, $password);
mysql_select_db("database", $conn);
$result=$_POST['result'] ; //value from qrcode scanned by device
$sql="SELECT * FROM tabe WHERE code = '$result' ";
$rs = mysql_query($sql,$conn);
$count=mysql_num_rows($rs);
if($count == 1) {
echo "ok";
}
else
{
return "No Ok";
}
?>
I'm new using ajax and I have a code to display from wordpress some information from database columns.
I have this PHP code to connect with the database and create the JSON file:
<?php
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if (isset($username) && isset($password)) {
//CONEXION
$host="localhost";
$user="DB_Username";
$pass="DB_Password";
$dbname="DB_Name";
//Conexion
$conexion = mysqli_connect($host, $user, $pass,$dbname)
or die("unexpected error");
//gWe made the search
$sql = "SELECT * FROM Column WHERE A_Login='$username'";
mysqli_set_charset($conexion, "utf8");
if(!$result = mysqli_query($conexion, $sql)) die();
$clients = array();
$num_result = mysqli_num_rows($result);
if ($num_result == 0) {
$clients = array("error" => "true", "msg" => "We can't found this user", "data" => $username);
} else {
while($row = mysqli_fetch_array($result))
{
$id=$row['ID'];
$Name=$row['Name'];
if ($row['A_Login'] == $username && $row['A_Password'] == $password){
$clients[] = array('id'=> $id, 'Name'=> $Name);
} else {
$clients[] = array('error'=> "true", "msg" => "Incorrect data");
}
}
}
$close = mysqli_close($conexion)
or die("Unespected error with DB");
}
else {
$clients = array("error" => "true", "msg" => "You must fill all fields", "username" => $username);
}
//We build the JSON
$json_string = json_encode($clients);
echo $json_string;
?>
In a wordpress page I have this code, I build a form where if the user click the submit button call doLogin()
<script type="text/javascript"> function doLogin(){
data = {username: jQuery("#user").val(), password: jQuery("#pass").val()}
console.log(data);
jQuery.ajax({
type: "POST",
url: "Mywebsiteurl.php",
data: data,
beforeSend: function(){
},
success: function(data){
console.log(data);
//var arr = JSON.parse(data);
//$('#forma').html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
console.log(textStatus);
console.log(errorThrown);
}
});
} </script>
I need to show in <div id="forma"> a kind of list usign html, for example:
Id: VALUE ID
Name: VALUE NAME
and more information...
When i try to print in my website the required information using $('#forma').html(data); I obtain error or just an empty space.
How can I fix it? thanks.
In WordPress we need to hook the ajax hook to your check_user function here.
add_action('wp_ajax_your_action_from_js', 'your_function');
//Using ajax for non-logged users as well (PUBLIC)
add_action('wp_ajax_nopriv_your_action_from_js', 'your_function');
Check below code for how it is done regarding your context.
In functions.php
function check_user() {
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
if (isset($username) && isset($password)) {
//CONEXION
$host="localhost";
$user="DB_Username";
$pass="DB_Password";
$dbname="DB_Name";
//Conexion
$conexion = mysqli_connect($host, $user, $pass,$dbname)
or die("unexpected error");
//gWe made the search
$sql = "SELECT * FROM Column WHERE A_Login='$username'";
mysqli_set_charset($conexion, "utf8");
if(!$result = mysqli_query($conexion, $sql)) die();
$clients = array();
$num_result = mysqli_num_rows($result);
if ($num_result == 0) {
$clients = array("error" => "true", "msg" => "We can't found this user", "data" => $username);
} else {
while($row = mysqli_fetch_array($result))
{
$id=$row['ID'];
$Name=$row['Name'];
if ($row['A_Login'] == $username && $row['A_Password'] == $password){
$clients[] = array('id'=> $id, 'Name'=> $Name);
} else {
$clients[] = array('error'=> "true", "msg" => "Incorrect data");
}
}
}
$close = mysqli_close($conexion)
or die("Unespected error with DB");
}
else {
$clients = array("error" => "true", "msg" => "You must fill all fields", "username" => $username);
}
//We build the JSON
$json_string = json_encode($clients);
echo $json_string;
}
add_action('wp_ajax_check_user', 'check_user');
//Using ajax for non-logged users as well (PUBLIC)
add_action('wp_ajax_nopriv_check_user', 'check_user');
In your JS called file.
In the script the action is related to your _your_action_from_js. So action is needed for knowing where the ajax has to hit. In our case it executes our check_user and returns the appropriate values.
<script type="text/javascript">
function doLogin(){
data = {action: 'check_user', username: jQuery("#user").val(), password: jQuery("#pass").val()}
console.log(data);
jQuery.ajax({
type: "POST",
url: ajax_url,
data: data,
beforeSend: function(){
},
success: function(data){
console.log(data);
//var arr = JSON.parse(data);
//$('#forma').html(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
console.log(textStatus);
console.log(errorThrown);
}
});
}
</script>
Reference Simple AJAX Form: http://wptheming.com/2013/07/simple-ajax-example/
CODEX Reference: https://codex.wordpress.org/AJAX_in_Plugins
WordPress has specific methods to enable ajax requests.
// registering ajax request for Logged users
add_action( 'wp_ajax_my_action', 'my_action_callback' );
// registering ajax request also for public area
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
function my_action_callback()
{
// Your code here
wp_die(); // this is required to terminate immediately and return a proper response
}
To call it:
jQuery(document).ready(function($) {
var data = {action: "my_action", username: jQuery("#user").val(), password: jQuery("#pass").val()}
jQuery.ajax({
url: '/wp-admin/admin-ajax.php',
data: data,
method: 'POST',
success: function(response) {
console.log(response);
},
error: function(a,b,c) {
}
});
});
Source: https://codex.wordpress.org/AJAX_in_Plugins
hi i am working on an authentification page , so my code is the following
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
if(result == 'true')
{
alert(result);
}
}});
});
});
i get the form , the login and password and i pass them to my php script .
<?php
//data connection file
//require "config.php";
require "connexion.php";
extract($_REQUEST);
$pass=crypt($password);
$sql = "select * from Compte where email='$email'";
$rsd = mysql_query($sql);
$msg = mysql_num_rows($rsd); //returns 0 if not already exist
$row = mysql_fetch_row($rsd);
if($msg == 0)
{
echo"false1";
}
else if($row[1] == crypt($password,$row[1]))
{
echo"true";
}
else
{
echo"false2";
}
?>
everything is goood , when i give the good email and password i get true otherwise i get false, that's not the problem , the problem is i am trying to redirect the user to another page called espace.php if the result is true so i've tried this .
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
if(result == 'true')
{
form.submit(true);
}
else form.submit(false);
}});
});
});
now even if the login and password are not correct the form is submitted , how could i manage to do that i mean , if the informations are correct i go to another page , otherwise i stay in the same page.
use json to get result from authanication page
<?php
//data connection file
//require "config.php";
require "connexion.php";
extract($_REQUEST);
$pass=crypt($password);
$sql = "select * from Compte where email='$email'";
$rsd = mysql_query($sql);
$msg = mysql_num_rows($rsd); //returns 0 if not already exist
$row = mysql_fetch_row($rsd);
$result = array();
if($msg == 0)
{
$result['error'] = "Fail";
}
else if($row[1] == crypt($password,$row[1]))
{
$result['success'] = "success";
}
else
{
$result['error'] = "try again";
}
echo json_encode($result); die;
?>
And in the ajax,, check what is the response.
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
var response = JSON.parse(result);
if(response.error){
//here provide a error msg to user.
alert(response.error);
}
if(response.success){
form.submit();
}
}});
});
});
I am building a website that uses jQuery/AJAX to send data to a php page, and from there insert it into a database. For some reason, the code isn't inserted and I get no response at all.
my javascript:
function insert_data(){
var title = debate_title.value;
var subtitle = debate_sub.value;
var sides = debate_sides.value;
$(function() {
$.ajaxSetup({
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
window.location.replace('errors/noConnection.html');
} else if (jqXHR.status == 404) {
window.location.replace('errors/noConnection.html');
} else if (jqXHR.status == 500) {
window.location.replace('errors/noConnection.html');
} else if (exception === 'parsererror') {
window.location.replace('errors/noConnection.html');
} else if (exception === 'timeout') {
window.location.replace('errors/noConnection.html');
} else if (exception === 'abort') {
window.location.replace('errors/noConnection.html');
} else {
window.location.replace('errors/noConnection.html');
}
}
});
});
$.ajax({
type: "POST",
url: "post_debate.php",
data: { post_title: title, post_sub: subtitle, post_sides: sidesm, ajax: 1 },
dataType: "json",
timeout: 5000, // in milliseconds
success: function(data) {
if(data!==null){
window.location.replace('show_debate.php?id=' + data);
}else{
window.location.replace('errors/noConnection.html');
}
}
});
}
My PHP code (post_debate.php):
<?php
require('connect.php');
$title = $_POST['post_title'];
$subtitle = $_POST['post_sub'];
$sides = $_POST['post_sides'];
$ajax = $_POST['ajax'];
$date = new DateTime();
$timeStamp = $date->getTimeStamp();
if($ajax==1){
$query = mysql_query("INSERT INTO debates VALUES('','$title','$subtitle','$sides','0','0','$timeStamp')");
$get_data = mysql_query("SELECT id FROM debates WHERE title='$title', subtitle='$subtitle', sides='$sides', timestamp='$timeStamp'");
while($id=mysql_fetch_array($get_data)){
$final_id = $id['id'];
}
exit($final_id);
}else{
die("404 SERVER ERROR");
}
?>
Thanks!
EDIT - NOT SOLVED YET
My new PHP code:
<?php
header("content-type: application/json");
require('connect.php');
$title = $_POST['post_title'];
$subtitle = $_POST['post_sub'];
$sides = $_POST['post_sides'];
$ajax = $_POST['ajax'];
$date = new DateTime();
$timeStamp = $date->getTimeStamp();
if($ajax==1){
$query = mysql_query("INSERT INTO debates VALUES('','$title','$subtitle','$sides','0','0','$timeStamp')");
$get_data = mysql_query("SELECT id FROM debates WHERE title='$title', subtitle='$subtitle', sides='$sides', timestamp='$timeStamp'");
while($id=mysql_fetch_array($get_data)){
$final_id = $id['id'];
}
print (json_encode(array("Id"=>$final_id)));
}else{
die("404 SERVER ERROR");
}
?>
my new Javascript .ajax:
$.ajax({
type: "POST",
url: "post_debate.php",
data: { post_title: title, post_sub: subtitle, post_sides: sides, ajax: 1 },
dataType: "json",
timeout: 5000, // in milliseconds
success: function(data) {
if(data!==null){
window.location.replace('show_debate.php?id=' + data['Id']);
}else{
window.location.replace('errors/noConnection.html');
}
}
});
Your code is expecting JSON as a response...
dataType: "json",
(Documentation Here)
But you're returning a non-json value without an appropriate content-type header.
Try changing your PHP script from
exit($final_id);
to (untested)
header("content-type: application/json");
print (json_encode(array(
"Id"=>$final_id
)));
Also, put a breakpoint on your success callback in your Javascript code (using Firebug or a similar tool) and examine what data contains. It should now be an associative array so you can do
window.location.replace('show_debate.php?id=' + data['Id']);
Improvement:
Instead of doing a SELECT to get the recently inserted Id, use mysql_insert_id(). Something like this...
$query = mysql_query("INSERT INTO debates VALUES('','$title','$subtitle','$sides','0','0','$timeStamp')");
$final_id = mysql_insert_id();
print (json_encode(array("Id"=>$final_id)));
Also, an alternate way to test what your PHP is returning if you can't see the response in your development tool is to browse to the page directly (You'd have to change all your $_POST to $_REQUEST)