How to get a simple text in AJAX response [duplicate] - javascript

I'm struggling with an issue here: I'm trying to create a jQuery/AJAX/PHP live search bar. I am calling search.php fine, but whenever I output the response in the console, I get the contents of my master.php file (which is just site-wide layout) along with the JSON-encoded results. I can't figure out what is causing this to happen.
Here is my jQuery:
$(function() {
$("#search-text").keyup(function() {
var $res = $(".search-results");
$.ajax({
type: "POST",
url: "search.php",
data: { query: $(this).val() },
cache: false,
success: function(html) {
$res.show();
$res.append(html);
console.log(html);
},
error: function(xhr, status, error) {
console.log("XHR: " + xhr);
console.log("Status: " + status);
console.log("Error: " + error);
}
});
return false;
});
});
And search.php:
$key = $_POST["query"];
$db = new Database();
$db->query("SELECT * FROM users WHERE firstname LIKE :key OR lastname LIKE :key OR firstname AND lastname LIKE :key");
$db->bind(":key", '%' . $key . '%');
$rows = $db->resultset();
echo json_encode($rows);
Thanks!

Write an exit() after the echo in search.php.
Like this:
$key = $_POST["query"];
$db = new Database();
$db->query("SELECT * FROM users WHERE firstname LIKE :key OR lastname LIKE :key OR firstname AND lastname LIKE :key");
$db->bind(":key", '%' . $key . '%');
$rows = $db->resultset();
echo json_encode($rows);
exit();
It should prevent showing the entire page.

In search.php before sending $rows in json_encode() give one condition that will check $row is empty or not.like :
if(!empty($res))
echo json_encode(array('status'=>'success','result'=>$rows));
else
echo json_encode(array('status'=>'failed','result'=>[]));
In ajax check
success: function(html)
{
if(html.status=='success')
{
$res.show();
$res.append(result.html);
console.log(result.html);
}
}
may be it will work..

Related

Always receive Error: parsererror in pushJsonData: SyntaxError: Unexpected end of JSON input [object Object] in my Script

I always receive the Parser error in pushJsonData and I don't know why.
I tested it first with just the user value and it works fine, but when I try to thrwo back mor than the user I recieve the error below:
SyntaxError: Unexpected end of JSON input [object Object]
My JavaScript code:
$('#Login').click(function() {
var user = $("#user").val();
$.ajax({
url: "src/ajax.php",
type: "POST",
data: { ACTION : "checkUser", USER: user},
dataType: "json",
success: function(data) {
var user = data.user;
$('#testUser').text("Hallo " + user);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus + " in pushJsonData: " + errorThrown + " " + jqXHR);
}
});
});
My PHP code:
if($_POST['ACTION'] == "checkUser") {
$checkUser = $_POST['USER'];
$sql = $db->query("SELECT * FROM fm_user WHERE user = '".$checkUser."' LIMIT 1");
$getUser = $sql->fetch_assoc();
$resultArray = array(
"user" => $getUser['user'],
"isadmin" => $getUser['isadmin'],
"user_data" => $getUser['user_data']
);
$result = json_encode($resultArray);
}
You're not outputting anything. But, rather than close this as off-topic due to a typo I wanted to point out some issues with your code, which is unsafe and inefficient. Always always use prepared statements, and there's no need to waste code putting array elements into an array. Something like this should work better:
<?php
if($_POST['ACTION'] == "checkUser") {
$result = null;
$checkUser = $_POST['USER'];
$stmt = $db->prepare("SELECT user, isadmin, user_data FROM fm_user WHERE user = ? LIMIT 1");
$stmt->bind_param("s", $checkUser);
if ($stmt->execute()) {
$result = $stmt->get_result();
$getUser = $result->fetch_assoc();
$result = $getUser;
}
header("Content-Type: application/json");
echo json_encode($result);
die();
}
Untested, and it's been a long time since I've used mysqli but it should work.

AJAX response from PHP script not working

I am searching this and other sites for hours now, so I'm getting pretty desperate. No code from many questions with the same topic here works.
I need to insert data into the database and display a message after it is done. Also, I am using AJAX with jQuery so it would be asynchronous. It works just fine, the data gets inserted, but no response message shows.
I am a beginner at PHP and can't understend why this won't work. Relevant code below.
PHP function call:
if(isset($_POST["function"]) && !empty($_POST["function"]) && $_POST["function"] == "cl-add") {
$dbb->addMember("MyUsername", $_POST["name"]);
//$dbb is a DataBaseBroker instance
}
PHP function from the Broker:
function addMember($username, $ime) {
$query = "INSERT INTO clan";
$query.=" (username, ime) ";
$query.="VALUES ('".$username."','".$ime."');";
$result = $this->mysqli->query($query);
if ($result) {
echo("You added a member: ".$ime);
} else {
$response = "An error occured. Please try again.";
$response .= "<br>";
$response .= "Error: ".mysqli_error($connection);
echo $response;
}
}
JQuery function declarations:
var addMember = function(name, responseFn) {
if (name === "") {
alert("Please enter a name");
return;
}
$.ajax({
type : 'POST',
url: '../includes/layout/cl.php',
dataType : 'json',
data : {
'name' : name,
'function' : 'cl-add'
},
success : function(data) {
responseFn(data); //not working, should alert
}
});
}
var responseCallback = function(data) {
alert(data);
}
And inside $(document).ready():
$(document).on('click', '#cl-add', function(evt) {
var name = $("#cl_frm input").val();
addMember(name, responseCallback);
});
On your code:
dataType : 'json',
The Ajax request is waiting for a JSON response but you are giving a text response.
You should change the dataType: to text or html depending on your needs.
dataType : 'html',
or
dataType : 'text',
PHP changes:
<?php
function addMember($username, $ime)
{
$query = "INSERT INTO clan";
$query .= " (username, ime) ";
$query .= "VALUES ('" . $username . "','" . $ime . "');";
$result = $this->mysqli->query($query);
$response = null;
if ($result) {
$response = "You added a member: " . $ime;
} else {
$response = "An error occured. Please try again.";
$response .= "<br>";
$response .= "Error: " . mysqli_error($connection);
}
echo $response;
exit;
}
Change dataType parameter to 'text'. Also you can alert an object in JavaScript, actually you are not trying to alert an object but i just wanted to mention it.

parse return data from html to ajax

I have some problem with the returned value of ajax.
this is the ajax code:
$(document).ready(function() {
var request;
$("#flog").submit(function(event) {
if(request)
request.abort();
event.preventDefault();
var form = $(this);
var serializedData = form.serialize();
var btnname = $('#log').attr('name');
var btnval = $('#log').val();
var btn = '&'+btnname+'='+btnval;
serializedData += btn;
request = $.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: serializedData,
});
request.done(function(data, status, jdXHR) {
alert(data);
});
request.fail(function(jdXHR, status, error) {
});
});
});
it takes data from a form and send it to another page.
this is the second page:
<?php include 'head.php'; ?>
<?php
if($_POST['login']) {
session_regenerate_id(true);
$con = mysqli_connect("localhost", "Alessandro", "ciao", "freetime")
or die('Could not connect: ' . mysqli_error($con));
$query = 'SELECT * FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
if(mysqli_num_rows($result) == 0) {
mysqli_close($con);
session_unset();
session_destroy();
$res = false;
return $res;
}
$query = 'SELECT password FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
$line = mysqli_fetch_array($result, MYSQL_ASSOC);
if(md5($_POST['password']) != $line['password']) {
mysqli_close($con);
session_unset();
session_destroy();
return false;
}
?>
<?php include 'foot.php'; ?>
and in .done the returned data is all the html page.
How can I retrieve only a data, like $res? I tried with json_encode() but with no results.
If in the second page I delete the lines include 'head.php' and include 'foot.php' it works. But I need that the secon page is html, too.
Somenone can help me?
Dont use the Data attribute from AJAX.
Replace
request.done(function(data, status, jdXHR) {
alert(data);
});
with
request.done(function(data, status, jdXHR) {
alert(jdXHR.responseText);
});
You could do it in a much simpler way.
In PHP store the result of the attempted login into a variable, for instance $result =0; to start with
If the login is valid change it to 1 and return it to ajax by doing an echo at the end of your PHP file. If you need other value returned such as the name you could add it to the variable with a separator such as || for instance.
in javascript collect your return and go data = data.split('||');
if (data[0] == 0){alert("Welcome back " + data[1]);}else{alert("wrong login...")}
Previous use is correct, you need to escape the user collected in your PHP script.
Hope this helps.

Uncaught SyntaxError: Unexpected end of input Chrome

I've to write an long poll query from my database - currently using mysqli. I'm successfully calling the data and return in my javascript code, but, now is the trick part, after 2 minutes, I receive this error: "Uncaught SyntaxError: Unexpected end of input".
I googled and read a couple pages (more then 30 I guess), but I wasn't able to solve this one...
everyone says is most likely that I forgot to close some brackets... but I guess not..
In other hand I prefer use json.parse() than eval().. and neither of them is working...
Thank for the attention.
Ps.: I'm not english native speacker, sorry any misspelling;)
That is my current js file
var old_msg_id = "<?php echo $old_msg_id; ?>";
function waitForMsg() {
$.ajax({
type: "GET",
url: "poll.php?old_msg_id=" + old_msg_id,
async: true,
cache: false,
//dataType : 'json',
success: function (dataRespond) {
//var jsonAnswer = eval("(" + dataRespond + ")");
var jsonAnswer = JSON.parse(dataRespond);
if (jsonAnswer.msg !== "") {
alert("New msg added to base!");
console.log(jsonAnswer.msg);
};
old_msg_id = jsonAnswer.old_msg_id;
setTimeout('waitForMsg()', 1000);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Deu merda!: Error: " + textStatus + " (" + errorThrown + ")");
setTimeout('waitForMsg()', 15000);
}
});
}
$(document).ready(function () {
waitForMsg();
});
That is my poll.php
error_reporting(0);
$conn = mysql_connect("localhost", "root", "");
mysql_select_db('padova', $conn) or die('Could not select database.');
$result = mysql_query("SELECT id FROM test ORDER BY id DESC LIMIT 1");
if($result === FALSE) {
die(mysql_error());
}
$old_msg_id = $_GET['old_msg_id'];
$result = mysql_query("SELECT id, text FROM test ORDER BY id DESC LIMIT 1");
while($row = mysql_fetch_array($result))
{
$last_msg_id = $row['id'];
$msg = $row['text'];
}
while($last_msg_id <= $old_msg_id)
{
usleep(1000);
clearstatcache();
$result = mysql_query("SELECT id, text FROM test ORDER BY id DESC LIMIT 1");
while($row = mysql_fetch_array($result))
{
$last_msg_id = $row['id'];
$msg = $row['text'];
}
}
$response = array();
$response['msg'] = $msg;
$response['old_msg_id'] = $last_msg_id;
$response = array_map('htmlentities',$response);
echo json_encode($response);

Textbox and AJAX data from mySQL

Hello I have a textbox and when I type something in it should update the page with the mySQL data via AJAX.
So Im trying to get live updated database results whenever you type something in the textbox. The goal is to get a textbox that is getting data from the mySQL database.
I have written the code so far, hopefully someone can advise me in this mather, thank you.
$select = 'SELECT *';
$from = ' FROM overboekingen';
$where2 = ' WHERE naam_klant LIKE % . $val . % ';
$opts = (isset($_POST['filterOpts']) ? $_POST['filterOpts'] : FALSE);
$val = (isset($_POST['txt']) ? $_POST['txt'] : FALSE);
if (is_array($opts) || $val) {
$where = ' WHERE FALSE';
if (in_array("naam_klant", $val)){
$where2.val;
}
}
else {
$where = false;
}
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>
AJAX
function updateEmployeesText(val){
$.ajax({
type: "POST",
url: "submit.php",
dataType : 'json',
cache: false,
data: {text: val},
success: function(records){
$('#employees tbody').html(makeTable(records));
}
});
}
You must define the PHP $val variable before.
The correct sytax:
$where2 = " WHERE naam_klant LIKE %$val% ";

Categories