Returning [Object object] from json_encode - javascript

I'm having trouble returning a status message from a php file to an ajax function in an html file. When go to submit I get [Object object] on the screen. From what I understand json_encode would be able to return the object $answer with its value. Am I missing something here?
php
<?php
require_once 'dbconfig.php';
require_once('FirePHPCore/fb.php');
ob_start();
$answer = new stdClass;
if(isset($_POST))
{
$uname;
$pword;
//email = ema
$ema;
$answer->result = "successful";
$answer->text = "";
foreach($_POST as $key => $value)
{
if($key == 'u')
{
$uname = $value;
}
else if($key == 'p')
{
$pword = $value;
}
else if($key == 'em')
{
$ema = $value;
}
}
}
else
{
$answer->result = "Error";
$answer->text = "Error Message";
}
$check = mysqli_query($con, "SELECT username FROM users WHERE username = '$uname'") or die(mysql_error());
$check2 = mysqli_num_rows($check);
if ($check2 != 0) {
$answer->text = "sorry username taken";
$ansr = json_encode($answer);
echo $ansr;
die('Sorry, the username is already in use.');
}
exit(0);
?>
ajax in my html file
$.ajax({
type: "POST",
url: "registration.php",
dataType: "json",
data : { u: un, p:p1, e:em },
cache: !1,
beforeSend: function(){
$("#submit").hide();
$('#status').text('please wait ...');
},
complete: function(){
$("#submit").show();
},
success: function(answer){
if(answer.result == "successful")
{
$("#status").html(answer.text);
}
else
{
$("#status").html(answer.result);
}
},
error: function(answer){
$("#status").text(answer);
}
});
any advice or hints would be appreciated.

Thanks #RamRaider !
Using die() right after using json_encode invalidated the data.

Related

Ajax doesn't do anything when php connected to database

I'm trying to establish a simple connection between Javascript and my database using ajax and PHP. Javascript is supposed to receive a name from an HTML form, modify it and post it to PHP to check whether the name is already in the database and return true/ false back to javascript for further use.
Everything works fine as long as I don't add the part of code that connects to the database. Calling only the PHP file in Chrome also works and it will correctly print true or false.
As soon as I connect both together, nothing works. Neither success nor error will execute any of the code inside their functions.
JS1 + PHP1: Nothing happens
JS1 + PHP2: Correctly shows result in Alert1 and Alert2
PHP1 alone: Correctly prints either true or false
JS1
var boo = false;
if(str.length > 1) boo = true;
if (boo)
$.ajax ({
url: 's5Check.php',
type: 'post',
data: { str : str },
success: function( result ) {
alert(result); //Alert1
if(result != false){
boo = false;
alert(str + " already exists!"); //Alert2
} else {
boo = true;
alert(str + " doesn't exist!"); //Alert3
}
},
error: function( e ) {
alert("Error: " + e); //Alert4
}
});
PHP1
<?php
if (isset($_POST['str'])) {
$con = mysqli_connect("localhost","root","","dbtest");
$temp = mysqli_real_escape_string($con, $_POST['str']);
$check = "SELECT id FROM handle WHERE name = '$temp'";
$result = $con -> query($check);
if($result->num_rows > 0) {
echo true;
} else{
echo false;
}
} else{
echo "error";
}
?>
PHP2
<?php
echo $_POST['str'];
?>
Thanks.
echo true will output 1. echo false will output nothing. You're not checking for either of these in your success function.
Using JSON is a simple solution to this, and allows for easy enhancement to more complex results.
JS:
$.ajax({
url: 's5Check.php',
type: 'post',
data: {
str: str
},
dataType: 'json',
success: function(result) {
alert(result); //Alert1
if (result === false) {
boo = false;
alert(str + " already exists!"); //Alert2
} else if (result === true) {
boo = true;
alert(str + " doesn't exist!"); //Alert3
} else if (result === "error") {
alert("Error");
} else {
alert("Unknown problem");
}
},
error: function(jqXHR, txtStatus, e) {
alert("Error: " + e); //Alert4
}
});
PHP:
<?php
if (isset($_POST['str'])) {
$con = mysqli_connect("localhost","root","","dbtest");
$check = "SELECT id FROM handle WHERE name = ?";
$stmt = $con->prepare($check);
$stmt->bind_param("s", $_POST['str']);
$result = $stmt->execute();
$response = $result->num_rows > 0;
} else{
$response = "error";
}
echo json_encode($response);
?>

How to add php form validation with ajax error handling

How can I add validation and php error handling with ajax. Now the success message come correctly but how can I implement error message on it? I might need to add some php validation please help.
Here is my JS.
$('#edit_user_form').bind('click', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function () {
$(".msg-ok").css("display", "block");
$(".msg-ok-text").html("Profile Updated Successfully!!");
},
error: function() {
//Error Message
}
});
});
PHP
<?php
require_once 'db_connect.php';
if($_POST) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$index_no = $_POST['index_no'];
$contact = $_POST['contact'];
$id = $_POST['id'];
$sql = "UPDATE members SET fname = '$fname', lname = '$lname', index_no = '$index_no', contact = '$contact' WHERE id = {$id}";
if($connect->query($sql) === TRUE) {
echo "<p>Succcessfully Updated</p>";
} else {
echo "Erorr while updating record : ". $connect->error;
}
$connect->close();
}
?>
ajax identifies errors based of status code, your php code will always return status code 200 which is success, even when you get error in php code unless its 500 or 404. So ajax will treat response as success.
if you want to handle php error, make following changes in your code
<?php
require_once 'db_connect.php';
if($_POST) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$index_no = $_POST['index_no'];
$contact = $_POST['contact'];
$id = $_POST['id'];
$sql = "UPDATE members SET fname = '$fname', lname = '$lname', index_no = '$index_no', contact = '$contact' WHERE id = {$id}";
if($connect->query($sql) === TRUE) {
echo "true";
} else {
echo "false";
}
$connect->close();
}
?>
$('#edit_user_form').bind('click', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function (res) {
if(res == 'true') {
//success code
} else if(res == 'false') {
//error code
}
},
error: function() {
//Error Message
}
});
});

how to echo one by one in loop on the same page

I am writing a program that send bulk email to our registered users via ajax.
I want echo every loop response when it is completed and it goes to next condition.
For Example:-
I have list of 100 Emails in database. When i submitted the request to program it will start sending emails.
Prog. works something like :
<?php
foreach($emails as $email){
$status = $this->sendMail($email);
if($status == true)
{
echo "Mail Sent";
}else{
echo "Not Sent";
}
}
?>
Now i want to print "Mail Sent"/"Not Sent" again and again for every loop.
Output:-
Mail Sent
Mail Sent
Mail Sent
Not Sent
Mail Sent
Sending..
EDIT
My PHP Code is:-
<?php
public function send_message() {
$sendTo = $this->input->post('send_to');
$template = $this->input->post('template');
$subject = $this->input->post('subject');
switch ($sendTo) {
case 1:
$users = $this->getAllEmails();
break;
case 2:
$users = $this->getRegisteredUsersEmails();
break;
case 3:
$users = $this->getTemproryUsersEmails();
break;
case 4:
$users = $this->getSubscribersEmails();
break;
}
$status = $this->sendMail($users, $template, $subject);
echo "Mail Sent";
}
private function sendMail($users, $template, $subject) {
$this->load->library('parser');
$status = array();
$i = 0;
foreach ($users as $user) {
$message = $this->parser->parse('email_templates/' . $template, array('email' => $user->email, 'name' => ($user->name != '') ? "Hi " . $user->name : "Hello"), TRUE);
$response = $this->mail->send(config_item('sender_mail'), config_item('sender_name'), $user->email, $subject, $message);
$status[$i]['email'] = $user->email;
$status[$i]['status'] = ($response == 1) ? 1 : 0;
$i++;
}
return $status;
}
?>
My Ajax Code :-
<script type="text/javascript">
$("#send_mail").submit(function(){
$.ajax{
url:"<?php echo base_url('promotion/send_message'); ?>",
type:"post",
data:$(this).serialize(),
success:function(data){
$("#status").html(data);
}
}
});
</script>
You have to do your loop with javascript/jquery rather than PHP. To have no overflow on server-side you should probably only call the function on success by using recursion. This way it will be synchronous.
jQuery
var emails = [
'lorem#stackoverflow.com',
'ipsum#stackoverflow.com',
'foo#stackoverflow.com'
];
index = 0;
var sendMail = function(email){
$.ajax({
url:"sendMail.php",
type: "POST"
data: { emailId: email}
success:function(response) {
index++;
document.write(response);
if(emails[index] != undefined){
sendMail(emails[index]);
}
}
});
}
sendMail(emails[index]);
PHP
$status = $this->sendMail($$_POST['email']);
$msg = $status ? "Mail Sent" : "Not Sent";
echo $msg;
I want to print the response when each time "$this->mail->send" function is called in "sendMail()"
As your code above, $status should be return in ajax function like a json object array.so I try this one ...
private function sendMail($users, $template, $subject) {
$this->load->library('parser');
$status = array();
$i = 0;
foreach ($users as $user) {
$message = $this->parser->parse('email_templates/' . $template, array('email' => $user->email, 'name' => ($user->name != '') ? "Hi " . $user->name : "Hello"), TRUE);
$response = $this->mail->send(config_item('sender_mail'), config_item('sender_name'), $user->email, $subject, $message);
$status[$i]['email'] = $user->email;
$status[$i]['status'] = ($response == 1) ? 1 : 0;
$i++;
}
echo json_encode($status);
}
Ajax Code
<script type="text/javascript">
$("#send_mail").submit(function(){
$.ajax{
url:"<?php echo base_url('promotion/send_message'); ?>",
type:"post",
dataType : "json",
data:$(this).serialize(),
success:function(data){
$.each(data,function(i,v){
$("#status").append(v.status);
}
}
}
});
</script>

Why ajax code to connect with php is not working?

I wrote the ajax in the JavaScript function. That code is
function getValidate(checkID)
{
alert(checkID);
$.ajax({
type: 'post',
url: 'checkval.php',
datatype: 'json',
data: {checkID : checkID},
success: function (response) {
if (response === "OK"){
alert("Validation Successed.");
}else if(response === "NG"){
alert("Check Already Exists.");
}
},
error : function(err, req) {
alert("Error Occurred");
}
});
}
this code is outputs only "Error Occurred".
the connected php script is
<?php
echo("welcome");
$check = $_POST['checkID'];
$host = 'localhost';
$database = 'database';
$username = 'root';
$password = 'root';
$dbc = mysqli_connect($host,$username,$password,$database);
$checkno = $check;
$sql = "select claimno from check_details where checkno = $checkno";
$result = mysqli_query($dbc,$sql);
$rows = mysqli_num_rows($result);
if($rows != 0)
{
echo "NG";
}
else
{
echo "OK";
}
?>
at a time of calling the JavaScript function php file not executed......
please give me the idea to success it...........
Try this :
if($rows != 0)
{
$return = "NG";
}
else
{
$return = "OK";
}
echo json_encode($return);
Also you set datatype to json so response data must be json type
$.ajax({ dataType:"json"});
In php, store result in one variable and return json_encode
<?php
echo("welcome");
$check = $_POST['checkID'];
$host = 'localhost';
$database = 'database';
$username = 'root';
$password = 'root';
$dbc = mysqli_connect($host,$username,$password,$database);
$checkno = $check;
$sql = "select claimno from check_details where checkno = '$checkno'"; //use single quote
$result = mysqli_query($dbc,$sql);
$rows = mysqli_num_rows($result);
if($rows != 0)
{
$res = "NG";
}
else
{
$res = "OK";
}
echo json_encode($res);
?>
You are getting error occurred, because of below code. Try logging something meaningful to triag this.
error : function(err, req) {
alert("Error Occurred");
}
Please try below code to get a clue of the error
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
Reference: Take a look at this query
It seems that the php script is not working well.
Debug it with try and catch and see what output is comming.

Ajax login issues

I'm having issues with an Ajax login function. There was another question similar to mine that I was able to find but it proved no use.
I have no idea what is the issue, this works on another program as well with no issues, hopefully someone can see my mistake
From testing I think the issue is in the "checkLogIn" function because when I run the application the alert within the function shows
Ajax:
$("#checkLogIn").click(function()
{
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: checkLogIn(),
})
.done(function(data)
{
if(data == false)
{
alert("failure");
}
else
{
alert("Success");
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
function checkLogIn()
{
alert();
return JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
}
I'll also include the PHP but the PHP works 100% after testing it.
PHP:
$app->post('/logIn/', 'logIn');
function logIn()
{
//global $hashedPassword;
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
//$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName AND password=:password";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("userName", $q->userName);
$stmt->bindParam("password", $q->password);
$stmt->execute();
//$row=$stmt->fetch(PDO::FETCH_ASSOC);
//$verify = password_verify($q->password, $row['password']);
$db = null;
//if($verify == true)
//{
// echo "Password is correct";
//}
//else
// echo "Password is incorrect";
echo "Success";
} catch (PDOException $e) {
echo $e->getMessage();
}
}
I have commented out any and all hashing until I can get this working properly
There is no problem with the ajax script. From my assumption you always get Error alert. That is because you added dataType: "json", which means you are requesting the response from the rootURL + '/logIn/' as json Object. But in the php you simply echoing Success as a plain text. That makes the ajax to get into fail function. So, You need to send the response as json. For more details about contentType and datatype in ajax refer this link.
So you need to change echo "Success"; to echo json_encode(array('success'=>true)); in the php file. Now you'll get Success alert. Below I added a good way to handle the json_encoded response in the php file.
$app->post ( '/logIn/', 'logIn' );
function logIn() {
global $hashedPassword;
$request = \Slim\Slim::getInstance ()->request ();
$q = json_decode ( $request->getBody () );
$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName";
try {
$db = getConnection ();
$stmt = $db->prepare ( $sql );
$stmt->bindParam ( "userName", $q->userName );
$stmt->execute ();
$row=$stmt->fetch(PDO::FETCH_ASSOC);
$verify = false;
if(isset($row['password']) && !empty($row['password']))
$verify = password_verify($hashedPassword, $row['password']);
$db = null;
$response = array();
$success = false;
if($verify == true)
{
$success = true;
$response[] = "Password is correct";
}
else
{
$success = false;
$response[] = "Password is incorect";
}
echo json_encode(array("success"=>$success,"response"=>$response));
} catch ( PDOException $e ) {
echo $e->getMessage ();
}
}
And I modified the ajax code. There I showed you how to get the response from the json_encoded Object.
$("document").ready(function(){
$("#checkLogIn").click(function()
{
var post_data = JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: post_data,
})
.done(function(data)
{
// data will contain the echoed json_encoded Object. To access that you need to use data.success.
// So it will contain true or false. Based on that you'll write your rest of the code.
if(data.success == false)
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Success:"+response);
}
else
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Failed:"+response);
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
});
Hope it helps.

Categories

Resources