Why is PHP adding a line break to my simple AJAX result? This couldn't be much easier. Am I missing something?
Here is my JS:
$(document).ready(function() {
$('#inputEmail').change(function(){
// Check to see if email exists
var email = $('#inputEmail').val();
//alert(email);
$.ajax({
url : "php/checkUserEmail.php",
type: "POST",
dataType: "text",
data: {email: email},
success: function(data){
alert(data);
if(data === "exists"){
alert(data);
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert("ajax error");
}
});
});
});
Here is my php:
<?php
include_once("db_connect.php");
// Catch results sent via $.post and assigns them to php variables.
$email = $_POST['email'];
// Check to see if email exists
$sql = "SELECT * FROM users WHERE email = '$email'";
$conn->prepare($sql);
$result = $conn->query($sql);
$rowCnt = $result->num_rows;
if($rowCnt == 0){
echo trim('new');
}else{
echo trim('exists');
}
For whatever reason, my result data string is returned as /r/nexists, rather than just exists, and thus never gets into my if block, even if I only use == to evaluate the condition. I tried adding the trim() function as you can see without result. Your help is much appreciated as this has taken me hours of time for a stupid if condition.
Check if there is an "empty" space after or before the php question marks, those line-breaks are also represented as part of the response.
I mean here
<?php?>
And here
I found a solution but I still do not like or understand what is happening. You should be able to return a simple string for a result. Anyway, what I did was to just echo the number of rows returned from the DB to my ajax success function. I then checked if the result was > 0 on the client and am finally in my IF block. Here is what I did:
JS:
$(document).ready(function() {
$('#inputEmail').change(function(){
// Check to see if email exists
var email = $('#inputEmail').val();
//alert(email);
$.ajax({
url : "php/checkUserEmail.php",
type: "POST",
dataType: "text",
data: {email: email},
success: function(data){
console.log(data);
if(data > 0){
console.log("HURRAY! I'm in my IF");
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert("ajax error");
}
});
});
});
Here is the PHP:
// Catch results sent via $.post and assigns them to php variables.
$email = $_POST['email'];
// Check to see if email exists
$sql = "SELECT * FROM users WHERE email = '$email'";
$conn->prepare($sql);
$result = $conn->query($sql);
$rowCnt = $result->num_rows;
echo $rowCnt;
?>
This works, and is actually maybe alittle more elegant, but you should be able to return a string without issue.
John
Related
I am a bloody beginner, I apologize if my mistake was too stupid.
So far I cannot get my 'taskone' entry updated. After the click on the button it should be '1' in the row for the current user.
my function
function loadDoc( user) {
console.log('aaa');
$.ajax({
url: "upper.php",
type: "POST",
data: {
'wp_users': user, 'taskeins': '1'
},
success: function(data){
alert(data);
}
});
}
my upper.php
$con=mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$current_user = get_current_user_id();
$Username = $_POST['wp_users'];
$taskeins = $_POST['taskeins'];
$sql = "UPDATE 'wp_users' SET 'taskeins' = 1 WHERE 'id' = '$current_user'";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
Basically the function should detect if the user has select the task. If so, 'taskeins' should get the indicator one so that it will be presented in the profile of the user.
The function gets called but that:
(function(event){loadDoc()
})
is my console output.
And I get a POST 500 error...
What I said - I am a total beginner. But maybe someone can help me.
As #MagnusEriksson pointed out, In MySQL, with regards to column names only, you use backticks and not quotes to escape sql reserved keywords otherwise you can leave them out.
Change your query to this:
$sql = "UPDATE `wp_users` SET `taskeins` = 1 WHERE `id` = '$current_user'";
Also you need to start using prepared statements as you are using an api (mysqli) that supports it
I used this, answered.
enter code herefunction loadDoc( user) {
console.log('aaa');
$.ajax({
url: "upper.php",
method: "POST",
data: {
'wp_users': user, 'taskeins': '1'
},
success: function(data){
alert(data);
}
});
}
Hello im using a login script with ajax and i want to callback and display my data
email and usernam to stock it in local storage.
i can get the data in json but i want to display this data in console.log
this is my codes
send_ajax.js
$(document).ready(function(e) {
$("#contactSubmitButton").click(function(){
var email = $("#contactEmailField").val();
var password = $("#contactNameField").val();
$.ajax({
type: "POST",
url: "http://hubafrica.co/webservices/get_user.php",
data: "email="+email+"&password="+password,
dataType: "json",
cache: false,
beforeSend: function(){ $("#contactSubmitButton").val('Chargement...');},
success: function(data) {
alert(data);
if(data)
{
iterateJson(data);
var url="http://hubafrica.co/webservices/get_user.php";
$.get(url,function(data){
// loop through the members here
$.each(json.data,function(i,dat){
console.log(dat.email);
window.localStorage.setItem("id", dat.id);
});
});
//window.location.href = "user_dashboard.html";
}else{
$("#formSuccessMessageWrap").fadeIn('slow');
$("#contactSubmitButton").val('se connecter');
}
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
});
});
script.php
<?php
header("Content-Type:application/json");
header('Access-Control-Allow-Origin: *');
include("../config/config.php");
$account=array();
if (isset($_POST["email"])){
$email = htmlspecialchars($_POST["email"]);
$pass = htmlspecialchars($_POST["password"]);
$sql = mysql_query('SELECT * FROM `b2b_user` where email="'.$email.'" and password="'.$pass.'"');
$num = mysql_num_rows($sql);
if($num > 0){
$row = mysql_fetch_assoc($sql);
$account['id'] = $row['id'];
$account['email'] = $row['email'];
echo '{"members":'.json_encode($account).'}';
}
}
?>
be for send response from backend you need to formate your data in json. Once you get in response you need to parseJSON()and the you can menuplate.
change here:use data.members to access data:
in your php construct like this:do not append string.
$account1= array('members'=>$account);
echo json_encode($account1);
script:
$.each(data.members,function(i,dat){
console.log(dat.email);
window.localStorage.setItem("id", dat.id);
});
You can either use
alert(JSON.stringify(data));
or
Console.log(JSON.stringify(data));
Following line of code turns an object/array in to a JSON text and stores that JSON text in a string.
JSON.stringify('/array variable here/')
Hope it helps.
I am trying to set a div tag to display a message if user isn't found in the database.
This is the line I can't get to work:
$("message").html(msg);
If you could help me understand what I'm doing wrong it would help. Thanks
$(document).ready(function(){
$("#submit").click(function(){
var username = $("#username").val();
var code = $("#code").val();
var msg = "Who are you?!";
var dataString = 'username='+ username + '&code='+ code;
localStorage.setItem("number",code);
if(username==''||code=='')
{
alert("Um..you are missing something...");
}
else
{
$.ajax({
type: "POST",
url: "verify.php",
data: dataString,
cache: false,
success: function(result){
if(result != 0)
alert(result);
},
error: function(){
$("message").html(msg);
}
});
}
return false;
});
});
My PHP code
<?php
$username = trim($_POST["username"]);
$code = trim($_POST["code"]);
include_once './inc/config.php';
$con = new mysqli(HOST, USER, PASSWORD, DATABASE);
$sql="SELECT * FROM info WHERE First_Name='".$username."' AND Line_Number='".$code."'" ;
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,$sql);
$num_rows = mysqli_num_rows($result);
if($num_rows != 0){
echo true;
}
else{
//echo "Who are you?!";
return false;
}
mysqli_free_result($result);
mysqli_close($con);
If your message element has the ID message, select it like this:
$("#message").html(msg);
If it has the class message, select it like this:
$(".message").html(msg);
The JQuery documentation contains an overview and in-depth description of all selector types.
In addition, to trigger the error method in your Javascript, your server-side code needs to send a HTTP error code, for example like this:
header("HTTP/1.1 404 Not Found");
Or like this:
http_response_code(404);
Is message a class or an ID? Make sure that you use the proper selector on which your output is to be displayed.
Use, # for id and . For class
error: function(){
$("#message").html(msg);
To target a div with id message use
$("#message")
You have missed the #
Try this:
$.ajax({...
success: function(data){
if(data)
$("#message").html (msg);
else
alert(data);
}
});
Apart from the obvious error in the message selector, another problem I can see is in your code is in your PHP.
Your php code does not return an error condition, it returns a true or false, so always your success callback will be called.
So
if($num_rows != 0){
echo true;
}
else{
//echo "Who are you?!";
echo false;
}
then
$.ajax({
type: "POST",
url: "verify.php",
data: dataString,
cache: false,
success: function (result) {
if (result) {
alert(result);
} else {
alert(msg);
//make sure you use a proper selector here
$("message").html(msg);
}
},
error: function () {
$("message").html(msg);
}
});
error: function(){
$("message").html(msg);
}
Do you respond with 404 or anything else, except of 2xx, when user is not found? And, yes, selector is incorrect. Your function will be called only in case of HTTP error during request to the server.
This
else{
//echo "Who are you?!";
return false;
}
will not run your function.
This
else{
//echo "Who are you?!";
header("HTTP/1.0 404 Not Found");
exit;
}
can do it, but not a very nice solution. The best one is to return something like this
$response = array('status' => 'failed', 'text' => 'Whatever');
header('Content-type: application/json');
echo json_encode($response);
exit;
and in your success function work with data, check the 'status' and so on.
I have this javascript to update a php session variable :
$(document).ready(function(){
$('#facebook_img').live('click',function(){
login_condetion = 1;
$.ajax({
type: "POST",
url: 'facebook_login_condition_variable.php',
data:{login_condetion:login_condetion},
dataType: "json",
success: function(data)
{
alert(123);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
/*alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
alert(XMLHttpRequest.responseText);*/
}
});
});
});
I print the session value before and after this code but it never change and when I alert responsText I get nothing and XMLHttpRequest gives me object object error .
This is my php code :
<?php
$temp = $_POST['login_condetion'];
if(!empty($temp) && $temp != 0)
{
$_SESSION['do_not_allow_auto_facebook_login'] = 1;
}
else
{
$_SESSION['do_not_allow_auto_facebook_login'] = 0;
}
$go = $_SESSION;
echo json_encode($go);
?>
Is there any problem with dataType of ajax function ? or it is a php session problem ? Please help me because I have been stuck here for long time.
Some suggestions..
Do you start the session at top of the page where you use it.
session_start();
in php code replace
$go = $_SESSION;
with
$go = $_SESSION['do_not_allow_auto_facebook_login'];
3.Do you need the datatype json, if not remove this line
echo json_encode($go);
and use
echo $go;
Use session_start() at the top of your script:
<?php
session_start();
...
I have a javascript fucntion below
function loginsubmit() {
var url = "../php/loginsubmit.php";
var data = "";
ajaxRequest(url, "POST",data , true, insertNewBody);
}
Which then creates my ajax request to post to my php code which is
<?php
session_start();
require_once ("db.php");
$username = $_POST['username'];
$password = $_POST['password' ];
echo $username;
$query = "select * from logindetails where username='$username' and password='$password'";
$result = mysql_query($query);
if(mysql_num_rows($result) == 1) {
$row = mysql_fetch_assoc($result);
$_SESSION['logged_in'] = TRUE;
} else {
$_SESSION['logged_in'] = FALSE;
}
mysql_close();
?>
These two pieces of code below are returning a null value and i can't see why?
$username = $_POST['username'];
$password = $_POST['password'];
It's because you're actually never setting the post values username and password in your javascript.
Put data in your data variable:
function loginsubmit() {
var url = "../php/loginsubmit.php";
var data = {username: 'yourusername', password: 'yourpassword'};
ajaxRequest(url, "POST",data , true, insertNewBody);
}
As clarified by others already, you are not sending data.. here is how you should:
function loginsubmit() {
var url = "../php/loginsubmit.php";
var username = document.myLoginForm.username.value;
var password = document.myLoginForm.password.value;
ajaxRequest(url, "POST", {username: username, password: password}, true, insertNewBody);
}
replace "myLoginForm" with the actual name of your form. Also there are other ways too to retrive values from input fields such as using element IDs of those feilds.
An ajax suggestion based on what Ruben is saying, you need to pass the username and password up to PHP in your login call.
$.ajax({
url : "../php/loginsubmit.php",
type: "POST",
data : {username:"theUsernameString",password:"thePasswordString"},
success: function(data, textStatus, jqXHR)
{
//data - contains the response from server
},
error: function (jqXHR, textStatus, errorThrown)
{
//handle the error
}
});