I have a simple jQuery AJAX request that submits user input from a text box to a PHP file. Here's the code for it:
$.ajax({
url: url,
type: type,
data: data,
dataType: 'json',
success: function(response){
console.log(response);
}
});
The PHP file basically logs the user in. Everything worked fine until I added "dataType: 'json'
" to my AJAX request. Now, whenever I click my submit button, nothing logs. Here is my PHP file:
<?php
include 'dbcon.php';
if ( isset( $_POST['text_login_username'], $_POST['text_login_password'] ) ) {
$loginResult = array();
$dbcon = getConnection();
$userName = mysqli_real_escape_string( $dbcon, $_POST['text_login_username'] );
$password = mysqli_real_escape_string( $dbcon, $_POST['text_login_password'] );
$loginQuery = "SELECT * FROM userData WHERE userName='$userName' AND userPassword='$password'";
$queryResult = mysqli_query( $dbcon, $loginQuery );
$legalRows = mysqli_num_rows( $result );
if ( $legalRows == 1 ) {
$loginResult['allClear']=0;
} else {
$loginResult['allClear']=1;
}
echo json_encode( $loginResult );
}
?>
AJAX file
$(document).ready(function(){
$('form.loginSubmit').on('submit',function(){
var that = $(this),
url=that.attr('action'),
type=that.attr('method'),
data={};
that.find('[name]').each(function(index,value){
var that=$(this),
name=that.attr('name');
value=that.val();
data[name]=value;
});
$.ajax({
url: url,
type: type,
data: data,
contenType:'application/json; charset=utf-8',
dataType:'json',
success: function(response){
console.log(response);
},
error: function(error)
{
console.log("test");
}
});
return false;
});
});
I can assure that the proper links to files, posts, etc. are set up properly, because this works until I try to send out the json_encode
variable. Any help would be much appreciated!
Thanks!
~Carpetfizz
UPDATE: I added an error:
setting to my AJAX call, and it runs whenever I submit.
UPDATE: Check out my answer. This was the solution for me.
Check this code
demo.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="initial-scale=1, maximum-scale=1" />
<title>jQuery AJAX Call to PHP Script with JSON Return</title>
<style type="text/css">
body {font-family: Helvetica, Arial, sans-serif; font-size: 13px}
.the-return {background: #f0f0f0; padding: 10px; margin-top: 15px}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script type="text/javascript">
$("document").ready(function(){
$(".js-ajax-php-json").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php",
data: data,
success: function(data) {
$(".the-return").html(
"Favorite beverage: " + data["favorite_beverage"] + "<br />Favorite restaurant: " + data["favorite_restaurant"] + "<br />Gender: " + data["gender"] + "<br />JSON: " + data["json"]
);
alert("Form submitted successfully.
Returned json: " + data["json"]);
}
});
return false;
});
});
</script>
</head>
<body>
<p><b>jQuery AJAX Call to PHP Script with JSON Return</b></p>
<form action="return.php" class="js-ajax-php-json" method="post" accept-charset="utf-8">
<input type="text" name="favorite_beverage" value="" placeholder="Favorite restaurant" />
<input type="text" name="favorite_restaurant" value="" placeholder="Favorite beverage" />
<select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<input type="submit" name="submit" value="Submit form" />
</form>
<div class="the-return">
[HTML is replaced when successful.]
</div>
</body>
</html>
return.php
<?php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test(){
$return = $_POST;
//Do what you need to do with the info. The following are some examples.
//if ($return["favorite_beverage"] == ""){
// $return["favorite_beverage"] = "Coke";
//}
//$return["favorite_restaurant"] = "McDonald's";
$return["json"] = json_encode($return);
echo json_encode($return);
}
?>
Try this. Make sure that your data variable in JS has the correct syntax of a JS object. More info about JSON objects here
$.ajax({
url: url,
type: type,
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(response){
console.log(response);
}
});
Can you try this? Add to your server script.
My json_encode returned nothing also until I added this when I upgraded my PHP version. Its got to do with json_encode only working on UTF-8
mysqli_query($dbcon, "SET NAMES utf8");
I also added this to the top of the script...
mb_internal_encoding("UTF-8");
1.- Use header content-type in your PHP code:
header('Content-type: application/json');
2.- Use content-type header in your jQuery ajax code:
contentType:'application/json; charset=utf-8'
3.- Check if your ajax jQuery code is POST or GET( default: get ):
type: "post"
4.- Print JSON in your PHP:
if( array_key_exists("text_login_username",$_POST) AND array_key_exists("text_login_password",$_POST) )
{
header('Content-type: application/json');
/**
* Create link
*/
$link = getConnection(); /* user function */
/**
* Default value for result
*/
$result = array(
"allClear" => 1
);
/**
* first arg is connection
* mysqli_real_escape_string ( mysqli $link , string $escapestr )
*/
$username = mysqli_real_escape_string( $link , $_POST["text_login_username"] );
$password = mysqli_real_escape_string( $link , $_POST["text_login_password"] );
/**
* Select "1" is best way with LIMIT; you dont need all fields... ¬¬ bad way...
**/
$source = mysqli_query( $link , "SELECT 1 FROM userData WHERE userData.userName='$username' AND userData.userPassword='$password' LIMIT 1" , MYSQLI_STORE_RESULT );
/**
* count
*/
if( mysqli_num_rows( $source ) == 1 )
{
$result["allClear"] = 0;
}
/**
* print json
*/
echo json_encode( $result );
/**
* prevent others prints
*/
exit;
}
5.- Use array_key_exists to verified if exists key in array
bool array_key_exists( mixed $key , array $search )
6.- Use this $.ajax code:
$.ajax({
url: "json.php",
type: "post",
data: {
text_login_username : "xxxx",
text_login_password : "xxx"
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(response)
{
console.log(response);
}
});
Good Luck!
The solution was weird. There was something wrong with mysqli_num_rows
. I just did this instead.
$legalRows=$queryResult->num_rows;
It works fine. Thanks for all the great answers. I definitely learned some new things that I will be implementing.