The problem is in jQuery, jsondata.uname is not displaying any result. If I echo $myarray in PHP and use data in jQuery it will display the result in array form.
$(document).ready(function() {
$('button#myloginbtn').on('click', function(e) {
e.preventDefault();
var username = $('input#myusername').val();
var password = $('input#mypassword').val();
$.post('home.php', {
domylogin: 'domylogin',
username: username,
password: password
}, function(data) {
jsondata = JSON.parse(data);
$('p#auser').text(jsondata.uname); // This is not working
});
});
});
home.php:
<?php
if (isset($_POST['domylogin'])){
$myuname = $_POST['username'];
$mypword = $_POST['password'];
// temporary testing, later i will return some data from database related to these values
$myarray = array();
$myarray['uname'] = $myuname;
$myarray['pword'] = $mypword;
echo json_encode($myarray);
}
?>
Thanks everyone for support, I had got the problem. I had some html code in my php file, on removing html code in 'home.php' everything works as supposed!
In your PHP file:-
$myarray = array();
if (isset($_POST['domylogin'])){
$myuname = $_POST['username'];
$mypword = $_POST['password'];
$myarray['uname'] = $myuname;
$myarray['pword'] = $mypword;
}
echo json_encode($myarray);
Write your AJAX call as below:-
$.post('home.php', {
domylogin: 'domylogin',
username: username,
password: password
})
.done(function( data ) { // Use done function
jsondata = JSON.parse(data);
if(jQuery.isEmptyObject(jsondata) == false) // check jsondata is empty or not
console.log(data);
$('p#auser').text(jsondata.uname);
});
Hope it will help you:-
Related
the success function is working but the data is not going in the database
$(document).ready(function() {
$("#ChatText").keyup(function(e){
if(e.keyCode == 13) {
var ChatText = $("#ChatText").val();
$.ajax({
type:'POST',
url:'InsertMessage.php',
data:{ChatText:ChatText},
success:function(){
$("#ChatText").val("");
}
});
}
});
setInterval(function(){
$("#ChatMessages").load("DisplayMessages.php");
},15000000);
$("#ChatMessages").load("DisplayMessages.php");
});
PHP
<?php
session_start();
include "connectToDB.php";
if(isset($_POST['ChatText'])){
$uid = $_SESSION['userid'];
$gid = $_SESSION['GameId'];
$ct = $_POST['ChatText'];
$sql = "INSERT INTO `chats`( `ChatUserId`, `chatGameId`, `ChatText`) VALUES ('$uid','$gid',$ct);";
$result = mysqli_query($_db , $sql);
}
?>
one thing u could do to debug is that echo your sql query and see if you get the correct query that works. You can event try out that query in phpMyAdmin and see whats going on. Hard to tell anything without debug.
I have read all the related questions that reference to this topic, but still cannot find answer here. So, php and ajax works great. The problem starts when i try to include json, between php and ajax, to passing data.
here is my ajax:
function likeButton(commentId, userId, sessionUserId) {
// check if the comment belong to the session userId
if(sessionUserId == userId) {
alert("You cannot like your own comment.");
}
else if(sessionUserId != userId) {
var like_upgrade = false;
$.ajax({
url: "requests.php",
type: "POST",
dataType: "json",
data: {
keyLike: "like",
commentId: commentId,
userId: userId,
sessionUserId: sessionUserId,
like_upgrade: like_upgrade
},
success: function(data) {
var data = $.parseJSON(data);
$("#comment_body td").find("#updRow #updComLike[data-id='" +commentId+ "']").html(data.gaming_comment_like);
if(data.like_upgrade == true) {
upgradeReputation(userId);
}
}
});
}
}
Note, that i try not to include this:
var data = $.parseJSON(data);
Also i tried with diferent variable like so:
var response = $.parseJSON(data);
and also tried this format:
var data = jQuery.parseJSON(data);
None of these worked.
here is requests.php file:
if(isset($_POST['keyLike'])) {
if($_POST['keyLike'] == "like") {
$commentId = $_POST['commentId'];
$userId = $_POST['userId'];
$sessionUserId = $_POST['sessionUserId'];
$sql_upgrade_like = "SELECT * FROM gaming_comments WHERE gaming_comment_id='$commentId'";
$result_upgrade_like = mysqli_query($conn, $sql_upgrade_like);
if($row_upgrade_like = mysqli_fetch_assoc($result_upgrade_like)) {
$gaming_comment_like = $row_upgrade_like['gaming_comment_like'];
}
$gaming_comment_like = $gaming_comment_like + 1;
$sql_update_like = "UPDATE gaming_comments SET gaming_comment_like='$gaming_comment_like' WHERE gaming_comment_id='$commentId'";
$result_update_like = mysqli_query($conn, $sql_update_like);
$sql_insert_like = "INSERT INTO gaming_comment_likes (gaming_comment_id, user_id, user_id_like) VALUES ('$commentId', '$userId', '$sessionUserId')";
$result_insert_like = mysqli_query($conn, $sql_insert_like);
$like_upgrade = true;
//json format
$data = array("gaming_comment_like" => $gaming_comment_like,
"like_upgrade" => $like_upgrade);
echo json_encode($data);
exit();
}
}
Note: i also try to include this to the top of my php file:
header('Content-type: json/application');
but still not worked.
What am i missing here?
Don't call $.parseJSON. jQuery does that automatically when you specify dataType: 'json', so data contains the object already.
You should also learn to use parametrized queries instead of substituting variables into the SQL. Your code is vulnerable to SQL injection.
I want to test passing data from $.post to php file in query
this is my $.post
$( "#get_route").on('click', function() {
var imei = $('#hisdeviceimei').val();
$.post( "vehicle_route_qry.php",{ imei:imei.replace(/,\s*$/, "") },function(data) {
alert(data);
});
});
this is php file
<?
include 'connect_old.php';
session_start();
$appuser = $_SESSION['LOGIN_user'];
$username = $_SESSION['LOGIN_STATUS'] ;
$imei = $_REQUEST["imei"];
echo $imei;
$conn->close();
?>
I am not able to get return values(imei) in response . How can i get / test values ?
I have to retrieve many rows from MySQL and send by encoding with ajax and I done this. but the problem is I am not able to handle the output array data in ajax. can anyone help me please?
1>one.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "elearning";
$tableName = "users";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
if(isset($_POST)){
$exam_id=$_POST['exam_id'];
$sql="select * from exam_to_question where exam_id=$exam_id";
$result = mysql_query($sql);
$dataArray = array();
while($array = mysql_fetch_assoc($result)){
$dataArray[] = $array;
}
echo json_encode($dataArray);
}
?>
2> and ajax code is:
$.ajax({
type: 'POST',
url: '../functions/one.php',
data: "exam_id="+exam_id,
dataType: 'json',
success: function(data){
//alert(data[0]['question_id']);
// i have to handle data here
},
error:function(){
alert("AJAX failure");
}
});
If that is an array then you have to use .each() method of jQuery:
$.each(data, function(i, resp){
console.log(resp);
});
You will get jquery object with ajax response. So, you can process it with any of these functions:
http://api.jquery.com/each/
http://api.jquery.com/jQuery.each/
if you have used dataType: json then you can dirctly use
//if it is not a multidimensional array then you can dirctly
data.keyName
//if it is multidimensional array
$(data).each(function(index,element){
console.log(element);
})
I know I had already this question asked, but I'm doing something wrong in my code. I know that I need to use JSON, and after going through few pages I understand the theory, but somehow can't make it work here is my code once again (btw I know about my security issues and I'll work on them as soon as I solve my technical issues with JSON):
$(document).on('pageinit',function(){
$("#login").click(function(){
username=$("#usr").val();
password=$("#psw").val();
$.ajax({
type: "POST",
url: "http://imes.**********.com/php/login_check.php",
data: "name="+username+"&pwd="+password,
success: function(html){
//in case of success
if(html=='true')
{
var usr = console.log(data.usr);
var psw = console.log(data.psw);
$.cookie('usr', usr);
$.cookie('psw', psw);
$("#login_message").html("Logged in, congratulation.");
$.mobile.changePage("http://imes.**********.com/userpanel.php");
}
//in case of error
else
{
$("#login_message").html("Wrong username or password");
}
},
beforeSend: function() { $.mobile.showPageLoadingMsg(); }, //Show spinner
complete: function() { $.mobile.hidePageLoadingMsg() }, //Hide spinner
});
return false;
});
And my php:
<?php
session_start();
$username = $_POST['name'];
$password = $_POST['pwd'];
include('mysql_connection.php');
mysql_select_db("jzperson_imesUsers", $con);
$res1 = mysql_query("SELECT * FROM temp_login WHERE username='$username' AND password='$password'");
$num_row = mysql_num_rows($res1);
$res2 = mysql_fetch_array($res1);
if( $num_row == 1 ) {
$arr = array('usr' => $username, 'psw' => $password);
echo json_encode($arr);
echo 'true';
}
else{
echo 'false';
}
?>
Your out put is not valid json, echoing a true or false after the json will cause it to be invalid. You have to insert the success message into the json data.
if( $num_row == 1 ) {
$arr = array('usr' => $username, 'psw' => $password);
echo json_encode(array('data'=>$arr, 'success'=>true);
//echo 'true';
}
else{
echo json_encode(array('success'=>false);
}
then check in your ajax success callback
success: function(json){
//in case of success
if(json.success){
var usr = json.data.usr;
...
}
else{
...
}
Also you should pass your parameters to data as an object so it will be properly encoded.
data: {"name":username,"pwd":password},
Here's what I would do (PHP). First setup your response array, default to success FALSE.
$arr = array('success' => FALSE);
Then your condition overwrites if successful:
if( $num_row == 1 )
{
$arr = array('success' => TRUE, 'usr' => $username, 'psw' => $password);
}
Finally at the end of the script return the result as JSON encoded data.
echo json_encode($arr);
exit();
I would make the following change to your jQuery also:
$.ajax({
type: "POST",
url: "http://imes.**********.com/php/login_check.php",
data: "name="+username+"&pwd="+password,
dataType: 'json', // let's it know the response will be JSON formatted
success: function(json){
if (json.success === true){
// do whatever you want here
}
});
A bit of advice though: you should never pass a user's password to the front-end.There is no need for it, ever.
If it helps, JSON is basically the right-hande-side of a variable definition in JS:
var myvar = ....;
^^^^---- basically JSON
Since you're doing
echo json_encode($var);
echo 'true';
in your PHP code, consider how it'll look from the client side:
var myvar = 'somestring'true;
^^^^---syntax error
if you're outputting JSON for consumption by an AJAX call in your JS code, then the JSON text is the ONLY thing that can be output by the server as its response. Anything else will simply mangle the json string somehow, and make it invalid.