JQuery not working after null ajax responce - javascript

I have Jquery code
$(document).ready(function(){
$('#login').click(
function () {
$.post('/profile/ajax/login', {
username: $('#username').val(),
password: $('#password').val(),
},
function (res) {
if (res != null) {
$.each(res, function (i, val) {
$('#login-error').html('<div class="alert alert-danger fade in"><a class="close" data-dismiss="alert" href="#">×</a>' + val + '!</div>');
return false;
});
} else {
location.reload();
}
},
'json'
);
}
);
}
And have PHP code
if($_POST)
{
$username = $_POST['username'];
$password = $_POST['password'];
$post = Validation::factory($_POST);
$post->rule('username', 'not_empty');
$post->rule('password', 'not_empty');
if($post->check())
{
if(!Auth::instance()->login($username, $password, true))
{
echo json_encode(array('Неверный Логин или Пароль'));
}
}
else
{
$errors = $post->errors('validation');
echo json_encode($errors);
}
}
If Ajax return some text with errors (res != null) - Jquery work normally.
If Ajax returned without any information nothing happens in "else" block.
How I can solve this problem?

The datatype you specified is json and so if the return value is null then it wont be processed. Try changing the datatype or echo an error in json format in your php file :)

The check res != null is the problem. An empty array can't be compared to null.
Change the condition to check the array length:
if (res.length > 0) {
Secondly if the submitted credentials are in valid format and are correct, the PHP returns nothing. This will cause the jQuery error handler to fire instead of success because a blank response can't be parsed as JSON. Add another else clause that returns an empty array:
if(!Auth::instance()->login($username, $password, true)){
echo json_encode(array('Неверный Логин или Пароль'));
} else {
echo json_encode(array());
}

Try changing your PHP code to :
$result = null;
if($_POST)
{
$username = $_POST['username'];
$password = $_POST['password'];
$post = Validation::factory($_POST);
$post->rule('username', 'not_empty');
$post->rule('password', 'not_empty');
if($post->check())
{
if(!Auth::instance()->login($username, $password, true))
{
$result = array('Неверный Логин или Пароль');
}
}
else
{
$result = $post->errors('validation');
}
}
echo json_encode($result);
This would result in your result being json encoded in all possible cases.

Related

Error (net::ERR_EMPTY_RESPONSE) on AJAX call

When the AJAX is called I always get these errors:
net::ERR_EMPTY_RESPONSE or net::ERR_CONNECTION_RESET
I also tryed different browsers (Chrome and Edge) but it is only working on localhost.
Thanks for all your help and support.
My PHP code (register.php):
require_once 'mysql_conn.php';
// username and password sent from form
$myUsername = mysqli_real_escape_string($db,$_POST['username']);
$myPassword = mysqli_real_escape_string($db,$_POST['password']);
$myRepPassword = mysqli_real_escape_string($db,$_POST['rep_password']);
if($myPassword == $myRepPassword && strlen($myUsername) >= 3 && strlen($myPassword) >= 8)
{
$userCheck = "SELECT id FROM users WHERE username = '$myUsername'";
$result = mysqli_query($db,$userCheck);
$count = mysqli_num_rows($result);
if($count > 0)
{
echo "This user already exists";
}
else
{
$sql = "INSERT INTO users (username, password) VALUES ('$myUsername', '$myPassword')";
if ($db->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
}
}
else
{
echo "Please check the values you inserted";
}
and the AJAX call:
$(function () {
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'register.php',
data: {username:username, password:password, rep_password:rep_password},
success: function (data) {
errorHandling(data);
}
});
});
});
I don't know how, but I solved it by deleting and re-creating the register.php file

AJAX request posts on second submit

I was making a form to post data, combined with Ajax. Below is all code associated with it. The problem is that when filling the form in and submitting, on the first click it does the XHR request, and get's a success call back so changes the button to Done!.
But the results don't appear in the database. When clicking the submit button again, it does another XHR request that DOES get through. Any ideas what could cause this? Thanks!
// Method for updating the post in User.php
public function updatePost($id, $title, $content){
$query1 = $this->conn->prepare("UPDATE posts SET post_title=:post_title, post_content=:post_content WHERE post_id=:post_id");
$query1->bindparam(":post_title", $title);
$query1->bindparam(":post_content", $content);
$query1->bindparam(":post_id", $id);
try {
$query1->execute();
} catch (Exception $e) {
echo $e->getMessage();
}
} ?>
// Backend for the authenication and validation (where the form posts to)
<?php
session_start();
require_once("../User.php");
$login = new User();
$errors = [];
$post_title = $_POST['post-title'];
$post_content = $_POST['post-content'];
$post_id = $_POST['post-id'];
if( isset($post_title) && isset($post_content) && isset($post_id) ){
if( empty($post_title) ){
$errors[] = "The entered title is invalid in some way.";
}
elseif (empty($post_content)) {
$errors[] = "The entered content is invalid in some way.";
}
elseif(empty($post_id)){
$errors[] = "An internal error has occured, please contact the system administrator.";
}
else{
try {
if( !$login->updatePost($post_id, $post_title, $post_content) ){
echo "allrighty";
}
else{
echo "charliewegotaproblem";
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
?>
// JS for the Ajax request itself
$("form").submit(function(evt){
evt .preventDefault();
var url = $(this).attr("action");
var formData = $(this).serialize();
$.ajax(url, {
data: formData,
type: "POST",
success: function(response){
if(response == "allrighty"){
$(".update-submit").prop("value", "Done!")
}
else if (response == "charliewegotaproblem") {
$(".update-submit").prop("value", "Something went wrong...")
}
}
}); // Ajax OBJECT END;
});// Submit END
<?php
==> First return success message, if post update query has executed successfully in updatePost function
// Method for updating the post in User.php
public function updatePost($id, $title, $content){
$success = false; // Here I changed the code
$query1 = $this->conn->prepare("UPDATE posts SET post_title=:post_title, post_content=:post_content WHERE post_id=:post_id");
$query1->bindparam(":post_title", $title);
$query1->bindparam(":post_content", $content);
$query1->bindparam(":post_id", $id);
try {
$query1->execute();
if($query1){ $success = true; } // Here I changed the code
} catch (Exception $e) {
echo $e->getMessage();
}
return $success;
}
==> Now here if $login has return true than an only than "allrighty" will return
// Backend for the authenication and validation (where the form posts to)
session_start();
require_once("../User.php");
$login = new User();
$errors = [];
$post_title = $_POST['post-title'];
$post_content = $_POST['post-content'];
$post_id = $_POST['post-id'];
if( isset($post_title) && isset($post_content) && isset($post_id) ){
if( empty($post_title) ){
$errors[] = "The entered title is invalid in some way.";
}
elseif (empty($post_content)) {
$errors[] = "The entered content is invalid in some way.";
}
elseif(empty($post_id)){
$errors[] = "An internal error has occured, please contact the system administrator.";
}
else{
try {
if($login->updatePost($post_id, $post_title, $post_content)){ // Here I changed the code
echo "allrighty";
}
else{
echo "charliewegotaproblem";
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
}
?>

How to return with jquery an php json array object?

Hello i have an ajax form submit and i want to return json data. For some reason it doesnt work as it should. When data.error is return it should give me the message Email is incorect. Same for the other responses. What did i do wrong? My php has json header and also datatype is json.
$(function() {
$("form#login").on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "log.php",
data: $('form#login').serialize(),
dataType:"json",
success: function(data){
if(data.error == "yes")
{
$("#msg").html('Email is incorect.')
}
else if (data.mandatory == "yes")
{
$("#msg").html('please complete email and pass')
}
else if (data.tip =='user')
{
alert('it works'+ data.id);
}
},
error: function(){
alert("failure");
}
});
});
});
my php
<?php
header('Content-Type: application/json');
session_start();
include ('core/dbconfig.php');
$password=$_POST['password'];
$usernume=$_POST['email'];
$hash = hash('sha512', $password);
if ($password=='' or $usernume=='')
{
$arr[] = array('mandatory' => 'yes');
echo json_encode($arr);
}
else
{
$stmt = $dbh->prepare("SELECT * FROM Users where Email=:username and Password= :hashed");
$stmt->bindParam(':username', $usernume);
$stmt->bindParam(':hashed', $hash);
$stmt->execute();
if ($row = $stmt->fetch())
{
$_SESSION['id_user']=$row['ID_User'];
$arr[] = array(
'tip' => 'user',
'id' => '3'
);
echo json_encode($arr);
}
else
{
$arr[] = array('error' => 'yes',);
echo json_encode($arr);
}
}
?>
turn all your php instances of $arr[] = to $arr =
if(data.error != undefined) ///i think this is the right way
{
$("#msg").html('Email is incorect.')
}else if(data.length == 0){
alert("No users available");
}else {
/*
you will have to do an iteration here of your
"data" parent object through your child objects
*/
for(var x in data){
if (data[x].mandatory == "yes")
{
$("#msg").html('please complete email and pass')
}
else if (data[x].tip =='user')
{
alert('it works'+ data[x].id);
}
} //close for
} //close else

EOF / Failed to load error when calling PHP file with AJAX

Apparently my POST requests are being cancelled?
http://puu.sh/d73LC/c6062c8c07.png
and also, mysqli_result object has all null values when i query the database with a select query:
object(mysqli_result)[2]
public 'current_field' => null
public 'field_count' => null
public 'lengths' => null
public 'num_rows' => null
public 'type' => null
here is my php file:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "uoitlol";
$name = "test1"; //this should be $_POST['name']; test1 is just to test if it works.
$err = false;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_errno > 0) {
echo 'connerr';
die();
}
$sql = "INSERT INTO summoners (name) VALUES (?)";
$getname = "SELECT name FROM summoners";
$result = $conn->query($getname);
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $name);
if ($err === false) {
if (!$stmt->execute()) {
echo 'sqlerr';
} else {
echo 'success';
}
}
$stmt->close();
mysqli_close($conn);
here is my javascript file, which calls the php file with ajax whenever i click submit on my form (in a different html file)
$(document).ready(function () {
$("#modalClose").click(function () {
document.getElementById("signupInfo").className = "";
document.getElementById("signupInfo").innerHTML = "";
});
$("#formSubmit").click(function () {
var name = $("#name").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = {'name' :name};
if (name === '')
{
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>Please enter a summoner name!</b>";
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "submitName.php",
data: dataString,
cache: false,
success: function (msg) {
if (msg === 'error'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>That summoner name is already in the database!</b>";
} else if (msg === 'sqlerror'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>SQL error, contact the administrator.</b>";
} else if (msg === 'success'){
document.getElementById("signupInfo").className = "alert alert-success";
document.getElementById("signupInfo").innerHTML = "<b>Summoner successfully added!</b>";
}
}
});
}
return false;
});
});
I'm getting these errors everytime I click my button that submits my form:
Failed to load resource: Unexpected end of file from server (19:41:35:538 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:35:723 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:36:062 | error, network)
at public_html/submitName.php
I'm using Netbeans IDE, if that matters.
puu.sh/d6YXP/05b5f3dc06.png - screenshot of the IDE, with the output log errors.
Remove this from your submitName.php, unless there really is HTML in it.
<!DOCTYPE html>
If there is HTML in it, do this instead.
<?php
//your PHP code//
?>
<!DOCTYPE html>
//your HTML here//
</html>
Also, if submitName.php contains no HTML, make sure there is no blank line after ?> at the bottom.
EDIT: In regards to your query failing, try this code.
if (!empty($name) { //verify the form value was received before running query//
$getname = "SELECT name FROM summoners WHERE name = $name";
$result = $conn->query($getname);
$count = $getname->num_rows; //verify a record was selected//
if ($count != 0) {
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
} else {
echo "no record found for name";
exit;
}
}
Drop the ?> at the end of the php file and instead of using var dataString = 'name=' + name; use this instead:
var data = { "name" : name};
jQuery will automagically do the dirty stuff for you so that you don't have to special text-escape it and stuff.
That's as far as I can help without any log files and just a quick skim of your code.

JavaScript Prompt Box Cancel Button?

I have a JavaScript function as follows:
function popup(username) {
var req = createAjaxObject();
var message = prompt("Message:","");
if(message != ""){
req.onreadystatechange = function() {
if (req.readyState == 4) {
alert(req.responseText);
}
}
req.open('POST','getmessage.php',true);
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
req.send("username=" + username +"&message="+message);
} else {
alert("Please enter a message");
}
}
When the Cancel button is hit, the form is still processed through getmessage.php. Any way to have the Cancel button do nothing?
EDIT:
Here is the way this function is called:
<?php
mysqlLogin();
$username = $_COOKIE['sqlusername'];
$sql = mysql_query("SELECT username FROM `users` WHERE username!='$username'");
if(mysql_num_rows($sql) != 0) {
echo "<table class='usertable' align='center'>";
while($row = mysql_fetch_array($sql)){
$username = $row['username'];
echo "<tr><td><center>" . $row['username'] . "</center></td><td> Send Message</td></tr>";
}
echo "</table>";
} else {
echo "<center>No users found!</center>";
}
?>
The PHP script its linked to:
<?php
$id = rand(1,1500);
$poster = $_POST['username'];
$message = $_POST['message'];
$to = $_COOKIE['sqlusername'];
require('functions.php');
mysqlLogin();
$sql = mysql_query("INSERT INTO `messages` VALUES ('$id','$message','$to','$poster','')");
if($sql){
echo "Message sent!";
} else {
echo "Woops! Something went wrong.";
}
?>
In the case of Cancel, the prompt result is null, and null != '' (as per ECMA-262 Section 11.9.3).
So, add an extra explicit check for null inequality:
if(message != "" && message !== null) {
However, since the message is either some string or null and you only want to pass when it's a string with length > 0, you can also do:
if(message) {
This means: if message is truthy (i.e. not null or an empty string, amongst other falsy values), then enter the if clause.
Are you using Safari by any chance? I have found that Safari seems to be returning empty string instead of null when the user clicks Cancel.
See here: Safari 5.1 prompt() function and cancel.
Yeah, my suggested comment does work
var message = prompt("Message:","");
if(message){
alert("Not working!");
} else {
alert("Working!");
}
JSFiddle
var message = prompt("Message:","");
if(message){
alert("Message accepted, now i can process my php or script and blablabla!");
} else {
alert("Cancel Press or Empty Message, do nothing!");
}
var message = prompt('type any...', '');
if(message+'.' == 'null.')
{
alert("you've canceled");
}
else
{
alert("type ok");
}
$.messager.prompt('Save To File', 'FileName:', function(e){
if (e.response!='undefined'){
if (r!="")
{
alert('Your FileName is:' + r);
}
else
{
$.messager.alert('Err...','FileName cannot empty!!!');
}
}
});

Categories