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);
Related
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.
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..
I am creating a webpage having Excel like features to create a Plan.For this i need to fill an initial form and click on submit button , then submit the form using ajax to a server side PHP script which inserts these records to a Mysql table.
But the issue is i can only transfer 1-2 records of table using the POST Query as there is a limit to it.What should i do in this case?Is there any other way of doing it without expanding the POST query limit?
My Front end code(.js)
</script>
buttons.save.addEventListener('click', function() {
var r1 = hot.countRows() - hot.countEmptyRows() - 1;
var c1 = hot.countCols()- 1 ;
var data = String(hot.getData(0,0,r1,c1));
data = data.replace(/,/g,'');
document.getElementById('all_data').value= JSON.stringify(hot.getData(0,0,r1,c1));
document.getElementById('colheaders').value=JSON.stringify(hot.getColHeader());
console.log(hot.getInstance());
var testplan_name = document.getElementById('feature_name').value;
var product = document.getElementById('product').value;
var release = document.getElementById('release').value;
var pv_engg = document.getElementById('pv_engg').value;
var pe_engg = document.getElementById('pe_engg').value;
var rd_engg = document.getElementById('rd_engg').value;
var tp_completion = document.getElementById('tp_completion').value;
var at_completion = document.getElementById('at_completion').value;
var all_headers = document.getElementById('colheaders').value;
var all_data = document.getElementById('all_data').value;
var maker = document.getElementById('maker').innerHTML;
var datastring = 'testplan_name='+testplan_name+'&product='+product+'&release='+release+'&pv_engg='+pv_engg+'&pe_engg='+pe
_engg+'&rd_engg='+rd_engg+'&tp_completion='+tp_completion+'&at_completion='+at_completion+'&headers='+all_headers+'&all_data='
+all_data+'&maker='+maker;
if(testplan_name=="" || pv_engg =='' || pe_engg== '' || rd_engg== '' || product=='' || release=='') {
else if(data=="") {
alert("For creating a testplan , you need to fill this table.");
}
else {
alert(datastring);
$.ajax({
url :"save_create_pro.php",
type :"POST",
data : datastring,
cache : false,
success :function(result) {
console.log(result);
alert(result);
alert("Form Submitted successfully");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
return false;
});
});
</script>
My Backend php code:
<?php
$dbh=mysql_connect('noiwebfarmo','abc','xyz');
if(! $dbh ) {
die('Could not connect: ' . mysql_error());
}
$database=mysql_select_db('testmohit');
$testplan_name=$_POST['testplan_name'];
$product=$_POST['product'];
$release=$_POST['release'];
$pv_engg=$_POST['pe_engg'];
$pe_engg=$_POST['pe_engg'];
$rd_engg=$_POST['rd_engg'];
$tp_completion=$_POST['tp_completion'];
$at_completion=$_POST['at_completion'];
$maker=$_POST['maker'];
$headers=stripslashes($_POST['headers']);
$all_data = stripslashes($_POST['all_data']);# to remove \ before " that occur when parsed through ajax
$headers=preg_replace('/\["/','',$headers);
$headers=preg_replace('/"\]/','',$headers);
$headers=split('","',$headers);
for($j=0;$j<count($headers);$j++) {
$headers[$j]= str_replace(' ','_',strtolower("$headers[$j]"));
}
$date=date('Y-m-d');
$all_data=preg_replace('/\[\["/','',$all_data);
$all_data=preg_replace('/"\]]/','',$all_data);
$rows_data=split('"\],\["',$all_data);
or($i=0;$i<count($rows_data);$i++) {
$data[$i] = split('","',$rows_data[$i]);
}
$result = array();
foreach($data as $key => $val){
$temp = array();
foreach($val as $k => $v){
$temp[$headers[$k]] = $v;
}
$result[] = $temp;
}
#print $all_data;
print count($result);
print_r($result);
for($i=0;$i < count($result);$i++) {
$temp = $result[$i];
$query = "INSERT INTO testplans (testplan_name,product,pro_release,percent_tpcompletion,percent_atcompletion,pv_engineer,rnd_engg,pe_engg,tc_name,cell_name,customer_name,flops,title,status,mfix_ccr,test_scenerio,expected_results,ccr_no,ccr_status,remarks,create_date,maker) VALUES ('$testplan_name','$product','$release','$tp_completion','$at_completion','$pv_engg','$rd_engg','$pe_engg','$temp[testcase_name]','$temp[cell_name]','$temp[customer]','$temp[flops]','$temp[title]','$temp[status]','$temp[mfix_ccr]','$temp[scenerio_brief_description]','$temp[expected_results]','$temp[ccr_no]','$temp[ccr_status]','$temp[remarks]','$date','$maker')";
mysql_select_db('testmohit');
$enter=mysql_query($query,$dbh);
if(! $enter) {
die('Could not enter data: ' . mysql_error());
}
}
# echo "$query Entered data successfully";
mysql_close($dbh);
?>
Please provide a solution to insert large no. of rows of handson table without expanding the size of query string .What can be the solution of this problem.
Thanks in advance.
I have to get my smartphone-application to work until tomorrow and after hours of work I can't solve it on my own.
Important part of the PHP:
$sql = "SELECT `player_id`, `intro`, `level1`, `level2`, `level3`, `sectask1`, `sectask2`, `sectask3` FROM `matrix` WHERE `matrix`.`player_id` = '$id';";
$result = $conn->query($sql);
$results = array();
while ($row = mysqli_fetch_assoc($result)) {
$results[] = $row;
};
$json = json_encode( $results);
header("Content-type: application/json");
echo( $_GET['callback'] . ' (' . $json . ');' );
?>
My Javascript Function:
$(document).ready(function() {
$(".slogan").click( function(){
console.log("EnterMatrix");
$.ajax({type: "GET",
url: 'http://192.168.141.98/getmatrix.php',
dataType: "jsonp",
crossDomain: true,
success: function(data) {
console.log("intro");
var users=JSON.parse(data);
console.log(data);
var intro = users[0].intro;
var level1 = users[0].level1;
var level2 = users[0].level2;
var level3 = users[0].level3;
var sectask1 = users[0].sectask1;
var sectask2 = users[0].sectask2;
var sectask3 = users[0].sectask3;
if(intro==0){
console.log("clicked2");
$("#matrix_introduction").show(300);}
else{
$("#matrix_introduction2").show(300);}
},
error: function(jqXHR, textStatus, errorThrown) {
alert('error ' + textStatus + " " + errorThrown);
}
});
});
});
What is Wrong - I am thankful for every hint!
I already tried a hella lot of solutions! Maybe it is something obvious?
Thanks :)
$json = json_encode( $results);
header("Content-type: application/json");
echo( $_GET['callback'] . ' (' . $json . ');' );
replace this code with
$json = json_encode( $results);
echo $json;
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.