$(form id).serialize() returns empty string - php

I have a simple search form whose content I want to send to my php query as a POST request. I'm using AJAX to send it, and so far everything works fine, but for some reason instead of sending the actual value of the input field, it always sends an empty string.
Can someone please explain what I'm doing wrong here?
my html:
<form id="searchbox">
<input type="text" placeholder="author, title, keyword...">
<input type="submit" value="Search">
</form>
my js (the console.log line is there in order to see what's getting posted, ie for checking what's wrong with my code):
$("#searchbox").submit(function(e) {
e.preventDefault();
console.log($("#searchbox").serialize());
$.post(
"db_queries/all_articles.php",
$( "#searchword" ).serialize(),
function(data) {
console.log(JSON.parse(data));
} //end response function
); //end search article POST request
})
my php:
try {
$hostname = "localhost";
$username = "root";
$password = "";
$db = new PDO("mysql:host=$hostname;dbname=topdecka_PTC",$username, $password);
if (!empty($_POST)) {
$query = $db->prepare('SELECT * FROM articles WHERE title = :title');
$query->execute(array(':title' => 'test1'));
$result = $query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
die();
}
else {
$query = $db->prepare('SELECT * FROM articles');
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
die();
}
} catch (PDOException $e) {
echo "Error!: " . $e->getMessage() . "<br/>";
die();
}

Your input tags must have a name attribute in order to be serialized.

Related

Why does my AJAX request print out the pages entire HTML code?

I'm trying to make an AJAX request, send the data to a PHP file, check if the username and password are correct, return an answer, and then run the login.php file which determines runs the session.
Right now, my AJAX request does nothing except print out my entire HTML code for the login page.
If someone knows why, please let me know...
(I apologize in advance for posting all of my login.js and checkLogin.php, I fear that the question may be unanswerable without the context for both)
This is login.js
$(function() { //Once the document has fully loaded
$("#login_form").submit(function(event) {
//INITIALIZING VARIABLES
var userName = $("#userName").val();
var passWord = $("#passWord").val();
var error = 0;
event.preventDefault(); //Prevent normal submit action
$("#userError, #passError").text(""); //Clear the text each time the user clicks submit
if (userName == "") { //Checking if the username is blank
$("#userError").text("Please enter your username");
error = 1;
}
if (passWord == "") { //Checking if the password is blank
$("#passError").text("Please enter your password");
error = 1;
}
//BEGIN Ajax Request
var $form = $(this),
term = $form.find("userName, passWord"),
url = 'checkLogin.php';
var posting = $.post(url, {username: userName, password: passWord});
posting.done(function(data) {
$("#userError").text(posting.responseText);
});
//END Ajax Request
if (error == 0) {
$("passError").text("Success");
}
}); //END submit button click
$("#login_form").submit();
});
This is checkLogin.php
<?php
$link = mysqli_connect(DB info private); //Database Connection
if (!$link) {
die('Could not connect: ' . mysqli_connect_error());
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') { //Keeps the text inside the this.responseText
//Preparing and Binding SQL statement
$stmt = mysqli_prepare($link, "SELECT username, password FROM login WHERE username =? and password =?");
mysqli_stmt_bind_param($stmt, "ss", $username, $password);
//PRINTS UNIDENTIFIED INDEX
$username = $_POST['username']; //Retrieving the username
$password = $_POST['password']; //Retrieving the password
mysqli_stmt_execute($stmt); //Execute the parameterized prepared statement
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
}
?>
Form tag from client_login.php
<form action="login.php" method="post" name="login_form" id="login_form">
</form>
You are not returning anything on checkLogin.php. You should try:
$row = mysqli_fetch_assoc($result);
if($row) {
echo "User found!";
exit();
}
I would recommend you, returning a text in json format. This way you can return more complex reponses to use in your js script. For example, in your checkLogin.php:
$row = mysqli_fetch_assoc($result);
if($row) {
echo json_encode([
'code' => '1', // code that represent successful
'message' => 'User found!'
]);
exit();
}
And in your login.js:
posting.done(function(data) {
var response = JSON.parse(data);
if(response.code == '1') {
$("#userError").text(response.message);
}
});
There are few issues here
url = checkLogin.php; should be url = 'checkLogin.php';
Right now url will be undefined and ajax url will post everything to yoursite.com/undefined and obiviosly the server will return 404 with default 404 page. Thats why you see html in your response.
YourcheckLogin.php should return some data to client. Use echo() for that.

Interaction between jquery,MySQL and PHP to retrieve the result

I have two file, test.html & test.php. I would like to display the result of an SQL query via jQuery AJAX.
test.php outputs proper JSON, but I'm not able fetch the same on clicking upon the button "Fetch Data". Is it wrong way of using AJAX?
Once fetching the data in test.html, how do I access the contents?
test.html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$ajax({
url:'test.php',
type:'get',
dataType:'json',
success:function(data){
alert(data);
console.log(data['success']);
console.log(data.success);
}
});
});
});
</script>
</head>
<body>
<button>Fetch Data</button>
</body>
</html>
test.php
<?php
$dbuser="root";
$dbname="test";
$dbpass="root";
$dbserver="localhost";
// Make a MySQL Connection
$con = mysql_connect($dbserver, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
// Create a Query
$sql_query = "SELECT ID, UserName, Status FROM user_details1";
// Execute query
$result = mysql_query($sql_query) or die(mysql_error());
$jsonArray = array();
while ($row = mysql_fetch_array($result)){
$jsonArrayItem = array();
$jsonArrayItem["ID"] = $row["ID"];
$jsonArrayItem["UserName"] = $row["UserName"];
$jsonArrayItem["Status"] = $row["Status"];
array_push($jsonArray, $jsonArrayItem);
//echo '<option value='. $row['id'] . '>'. $row['login'] . '</option>';
}
mysql_close($con);
$tableData = array(
"data" => $jsonArray
);
header('Content-Type: application/json');
echo json_encode($tableData,JSON_UNESCAPED_SLASHES);
die();
?>
How do I display/access/print the fetched result contents (AJAX section)?
Make a function like this
var dataToSend = "My Data";
$(button).on("click",function(event){
$.ajax({
method: "POST",
url: "test.php",
data: { pDataToSend: dataToSend }
}).done(function( data ) {
$('.results').empty();
$('.results').append(data);
});
});
And make a div like this
<div class="results></div>
In your PHP file you can read the POST using this code.
$foo = $_POST['pDataToSend'];
Also, your test.php file is all over the place. Use a PDO like this
//connect and setup database example
try {
$db = new PDO("mysql:host=localhost;dbname=second;port=8889","root","root");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch (Exception $e){
echo 'Could not connect to the database.105';
exit();
}
//select,insert,delete, update from database example
try{
$results = $db->prepare("SELECT * FROM articles WHERE article_id = ? AND user_id = ?");
$results->bindParam(1,$var);
$results->bindParam(2,$var2);
$results->execute();
$hold = $results->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit();
}

jQuery GET overwiting POST

I've got a simple jQuery script that isn't behaving correctly. What am I doing wrong? The idea is that the user enters a value into a textbox and then clicks a button. The jQuery then uses POST to send the value to a PHP file. The PHP file then runs a simple SQL query and gives a response. jQuery .load is then used to refresh the div containing the original php.
Using Chrome's tools, I've noticed that the response for POST is perfect. However, it then gets overwritten by a GET with no data.
jQuery:
$("#GOtest").click(function() {
var customer = $("#customer").val();
if (customer == '') {
$('#alert_formula_save_failed').show();
}
else {
$.post("../assets/forms/formulations/set_session.php", {
customer: customer,
}, function(data) {
$('#alert_formula_save_success').show();
$('#dynamic').load('../assets/forms/formulations/set_session.php');
$('#alert_formula_save_failed').hide();
setTimeout(function() { $('#alert_formula_save_success').fadeOut('fast'); }, 3000);
});
}
});
PHP:
<?php
$customer = null;
$customer = 'Test' ;
$customer2 = $_POST['customer'] ;
.. db connection bits ;
try
{
$PDO = new PDO( "mysql:host=".$host.";"."dbname=".$dbname, $user, $pass);
}
catch(PDOException $e)
{
die($e->getMessage());
}
$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM db_customers where customer = '$customer' ";
$stmt = $PDO->prepare($sql);
$stmt->execute(array($id));
$data = $stmt->fetch(PDO::FETCH_ASSOC);
$PDO = null;
$iscurrent = $data['iscurrent'];
echo '<br>' ;
echo 'Response 1-' ;
echo $iscurrent;
echo '<br>' ;
echo 'Response 2-' ;
echo $customer2 ;
?>
HTML:
<form id="testform" name="testform" method="POST">
<button type="button" name="GOtest" id="GOtest" class="btn btn-info">
<i class="fa fa-frown-o"></i>
SET SESSION
</button>
The idea being that 'response 1' just echoes a predefined value. Response 2 should just echo out whatever is typed into the text input box.. but the GET overwrites everything.
The "issue" is this line:
$('#dynamic').load('../assets/forms/formulations/set_session.php');
It uses GET by default.
Try using this in its place:
$('#dynamic').html(data);

calling PDO with AJAX, returns an empty string

I have a simple database query written in PHP using PDO. When I var_dump my $results, I get an associative array. So I figured I'd just use return $ result, call the script using AJAX and then work from there. But now when I console.log the data I get, I just get an empty string.
Can somebody explain what I'm doing wrong and how to fix it? Thanks
Here's my php (I've emptied host, username and password for "safety"):
<?php
try {
$hostname = "";
$username = "";
$password = "";
$db = new PDO("mysql:host=$hostname;dbname=topdecka_PTC",$username, $password);
$raw_result = $db->query('SELECT * FROM articles');
$result = $raw_result->fetchAll(PDO::FETCH_ASSOC);
return $result;
} catch (PDOException $e) {
echo "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
and my AJAX function:
$(document).ready(function() {
$.get( "db_queries/all_articles.php", function( data ) {
console.log( data );
});
});
You need to echo JSON encoded data:
Change this line:
return $result;
To:
echo json_encode($result);

How to display the result of my php in ajax

I want to do is display the result of my count.php in my index page. My plan is to auto count the number of rows of user_code and display the result in the index page everytime the page is visited or viewed.
My problem is that the ajax script doesnt recieve the result of count.php to display it in count inputbox on index page.
index page:
<input type="text" value="1" name="countValue" id="countValue" style="width: 12px;" /><br />
Count: <input type="text" name="count" id="count" readonly="readonly" /><br /><br /><br />
<script>
$(document).ready(function(){
var countTimer = setInterval(
function ()
{
codeValue();
}, 500);
var $count = $('#count');
function codeValue(){
$.ajax({
url:"count.php",
type:"GET",
data: { term : $('#countValue').val() },
dataType:"JSON",
success: function(result) {
$("#count").val(result.user_code);
}
});
};
});
</script>
count.php
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo $_GET['term'];
if (isset($_GET['term'])) {
$q = $_GET['term'];
$sql = "SELECT user_code FROM students";
$query = $dbc->prepare($sql);
$query->execute();
$num_rows = $query->rowCount();
echo json_encode(array('user_code'=>$num_rows));
}
?>
Your problem
echo $_GET['term'];
This breaks the expected JSON format that your script is meant to produce. Also, you aren't even using any request parameters so I don't know why you'd even bother.
Here's your PHP, all cleaned up
<?php
try {
$dbc = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', '',
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$stmt = $dbc->query('SELECT COUNT(1) FROM students');
header('Content-type: application/json');
echo json_encode(['user_code' => $stmt->fetchColumn()];
} catch (Exception $e) {
http_response_code(500);
echo $e->getMessage();
}
I'd also suggest adding an error callback to your $.ajax options to handle HTTP errors.
i try your code and it works for my table i have (4) records! check your query if there is data
make sure you have jquery file in your header. I did not change anything your html file. I just create my own query on my table. then okay.
You need to create a div in indexfile and id of that div is provided in ajax file,so as to populate data form count.php in that div.
Here i will give you a similar type of example, Try it by making your related changes
index.php
<div id="content">
</div>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: 'count.php',
success: function(data) {
$('#content').html(data);
}
});
<script>
count.php
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$con=mysqli_connect($host,$user,$pass,$db);
$result = mysqli_query($con,"SELECT user_code FROM students");
?>
<table>//this table will be loaded in div
<?php
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row['user_code']; ?></td>
</tr>
<?php
}
?>
</table>
You can also add autorefresh ajax script which will only reload only particular div after specific time interval(1 sec in below code) without reloading whole page
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#content').load('count.php').fadeIn("slow");
}, 1000); // refresh every 10000 milliseconds
</script>

Categories