How could I change the following php into ajax?
<?php
$selectMSGs = 'SELECT * FROM group_messages WHERE group_id="'.$_GET["id"].'" ORDER BY msg_id DESC';
$selectMSGs2 = $connect->query($selectMSGs);
while ($rowMSGs = $selectMSGs2->fetch_assoc()) {
echo "<div class='lead MessageOfPerson'>";
echo "<div class='NameOfPerson'>";
echo "<p>";
echo $rowMSGs['msg_sender'];
echo "</div>";
echo "<div class='MessageText'>";
echo nl2br($rowMSGs['group_msg']);
echo "</p>";
echo "</div>";
echo "</div>";
echo "<hr>";
}
?>
I already have some other ajax course (not my own) that is already being run on this page, could it be possible to combine this php together with my current ajax and php file? The files look like this:
ajax
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
function updateChat(){
$.ajax({
//TODO set localhost to the strato livechat file
url: "http://localhost:8080/LiveChat/LiveChat/code/php/groups/liveChat.php",
type: "get",
data: "msg_id="+$('#msg_id').val(),
dataType: "json",
success: function(response, status, http){
$.each(response, function(index, item){
$('#msg_id').val(item.msg_id);
//TODO update messages
});
},
error: function(http, status, error){
alert( 'Error updating chat, ' + error);
}
});
}
//auto update chat
setInterval( updateChat, 2000 );
</script>
php
<?php
// Lets fetch the value of msg_id
$data = $_REQUEST;
$msg_id = $data['msg_id'];
// Connect to MySQL Server TODO change to strato
$con = mysqli_connect( "localhost" , "root" , "" , "db2723249" );
// If msg_sender and group_msg is available then
// add it in table chats
if(
isset( $data['msg_sender'] ) &&
isset( $data['group_msg'] )
) {
$insert = "
INSERT INTO group_messages (group_id, group_msg, msg_sender)
VALUES( '".$data['msg_sender']."' , '".$data['group_msg']."' )
";
$insert_result = mysqli_query( $con , $insert );
}
$select = "SELECT *
FROM group_messages
WHERE msg_id > '".$msg_id."'
";
$result = mysqli_query( $con , $select );
$arr = array();
$row_count = mysqli_num_rows( $result );
if( $row_count > 0 ) {
while( $row = mysqli_fetch_array( $result ) ) {
array_push( $arr , $row );
}
}
// Close the MySQL Connection
mysqli_close( $con );
// Return the response as JSON
echo json_encode( $arr );
?>
Okay, after working on this for about 20 hours, I finally found out how to do it (without help:)! I was able to merge the old and new ajax and php.
The new ajax became
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
function updateChat(){
$.ajax({
//TODO set localhost to the strato livechat file
url: "http://localhost:8080/LiveChat/USB/code/php/groups/liveChat.php",
type: "get",
data: "msg_id="+$('#msg_id').val(),
dataType: "json",
success: function(response, status, http){
$.each(response, function(index, item){
$("#ChatBox").html("<div class='lead MessageOfPerson'> <div class='NameOfPerson'> <p>" + item.msg_sender + "</p> </div> </div> <div class='MessageText'> <p>" + item.group_msg + "</p> </div> <hr/>" + $('#ChatBox').html());
$('#msg_id').val(item.msg_id);
});
},
error: function(http, status, error){
alert( 'Error updating chat, ' + error);
}
});
}
//auto update chat
setInterval( updateChat, 2000 );
</script>
The php became:
<?php
// Lets fetch the value of msg_id
$data = $_REQUEST;
$msg_id = $data['msg_id'];
// Connect to MySQL Server TODO change to strato
$con = mysqli_connect( "localhost" , "root" , "" , "db2723249" );
// If msg_sender and group_msg is available then
// add it in table chats
if(
isset( $data['msg_sender'] ) &&
isset( $data['group_msg'] )
) {
$insert = "
INSERT INTO group_messages (group_id, group_msg, msg_sender)
VALUES( '".$data['msg_sender']."' , '".$data['group_msg']."' )
";
$insert_result = mysqli_query( $con , $insert );
}
$select = "SELECT * FROM group_messages WHERE msg_id > '".$msg_id."' ";
$result = mysqli_query( $con , $select );
$arr = array();
$row_count = mysqli_num_rows( $result );
if( $row_count > 0 ) {
while( $row = mysqli_fetch_array( $result ) ) {
array_push( $arr , $row );
}
}
// Close the MySQL Connection
mysqli_close( $con );
// Return the response as JSON
echo json_encode( $arr );
?>
Related
I am having an issue where i get a timeout if i run a certain php script with parameters sent from a Jquery Ajax reequest. However if i simply run this script with no parameters I.E just run it on its own its fine.
The php file the Ajax request is in is noteContent.php
noteContent.php:
<script type="text/javascript">
// Submit generalNote to the database
function submitNoteText()
{
var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
var notetext = $("#ta1").val();
var dataString = 'noteid1=' + noteid + '¬etext1=' + notetext;
if(noteid == ''||notetext == '')
{
alert("NoteID or Text is blank");
}
else
{
$.ajax({
type: "POST",
url: "submitNoteText.php",
dataType: 'json',
data: dataString,
cache: false,
success: function(result){
alert("Success");
}
});
}
return false;
};
</script>
The script its trying to run
submitNoteText.php:
<?php include 'connectionDetails.php'; ?>
<?php
if (isset($_POST['noteid1'], $_POST['notetext1']))
{
var_dump($_POST['notetext1']);
$noteid2 = $_POST['noteid1'];
$notetext2 = $_POST['notetext1'];
$stmt = "UPDATE Notes SET Note = '?' WHERE NoteID = ?";
$params = array($noteid2, $notetext2);
$stmt = sqlsrv_query($conn, $stmt, $params);
if ($stmt === false)
{
die( print_r(sqlsrv_errors(), true));
}
}
else
{
echo "No Data";
}
?>
they are all connected with an include to
connectionDetails.php(which has never returned an error before):
<?php
$myServer = "Test";
$connectionInfo = array('Database' => 'Test', 'UID' => 'Test', 'PWD' => 'test');
//connection to the database
$conn = sqlsrv_connect($myServer, $connectionInfo)
or die("Couldn't connect to SQL Server on $myServer");
//Test connection to server
// if ($conn)
// {
// echo "connection successful"; # code...
// }
?>
<?php
//Defining my queries
$getNotes = "SELECT NoteID, NoteName, Note FROM Notes ORDER BY NoteName ASC";
$getTemplateNotes = "SELECT TemplateNoteID, TemplateNoteName, TemplateNote FROM TemplateNotes ORDER BY TemplateNoteName ASC";
$getReplaceVariables = "SELECT ReplaceVariableID, ReplaceVariableName, ReplaceVariableNote FROM ReplaceVariables ORDER BY ReplaceVariableName ASC";
$resultNotes = sqlsrv_query($conn, $getNotes);
$resultTemplate = sqlsrv_query($conn, $getTemplateNotes);
$resultVariables = sqlsrv_query($conn, $getReplaceVariables);
if( $resultNotes === false)
{
die( print_r( sqlsrv_errors(), true) );
}
if( $resultTemplate === false)
{
die( print_r( sqlsrv_errors(), true) );
}
if( $resultVariables === false)
{
die( print_r( sqlsrv_errors(), true) );
}
?>
When i click the button to run the request i get this:
All the text to be submitted is in the params:
Ajax data parameter should be an array :
$.ajax({
type: 'POST',
url: "your urls",
data: {
id: youridval,
anothervar: anothervalvalue
},
beforeSend: function() {
},
complete: function() {
},
success: function(_result) {
}
});
I want to POST data from form. It works fine.
In the other functionality i want to get data from database.
I don't know where is mistake. I suspect that AJAX call is fine.
My PHP code:
<?php
$uuid = $_POST['uuid'];
$minor = $_POST['minor'];
$mayor = $_POST['mayor'];
$lokalizacja = $_POST['lokalizacja'];
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else{
echo "Polaczono";
}
$sql = "INSERT INTO beacons (uuid, major, minor, lokalizacja)
VALUES ('$uuid', '$minor', '$mayor', '$lokalizacja')";
if ($conn->query($sql) === TRUE) {
echo "Dane dodano prawidłowo";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sqlget = "SELECT uuid, major, minor, lokalizacja FROM beacons";
$result = $conn->query($sqlget);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo json_encode(array("value" => "UUID: " . $row["uuid"]));
}
} else {
echo "Brak rekordów w bazie";
}
$conn->close();
?>
AJAX call:
$('#admin').submit(function(e){
e.preventDefault();
if( ($("input[name=uuid]").val().length) > 40 || ($("input[name=minor]").val().length) > 5 || ($("input[name=mayor]").val().length) > 5 || ($("input[name=lokalizacja]").val().length) > 20){
$(".error-pola").show();
} else{
$.post('administrator-connect.php', $(this).serialize() )
.done(function(){
$(".success-wyslanie").show();
})
.fail(function(){
$(".error-wyslanie").show();
});
}
});
$(document).ready(function() {
$.ajax({
type: "GET",
url: 'administrator-connect.php',
dataType: 'json',
success: function(data)
{
alert("fsdfsd"+ data);
},
error: function(){
alert("not");
}
});
});
I am using:
echo json_encode(array("UUID" => $row["uuid"]));
and in ajax:
var jqxhr = $.get( "administrator-get.php", function(data) {
var jsonx = JSON.parse(JSON.stringify(data));
$( "#data-listing" ).html(jsonx);
});
But I get response:
{"UUID":"B9407F30-F5F8-466E-AFF9-25556B57FE6D"}
How to get only string ?
If you write this
dataType: 'json',
It expect for JSON value not string be sure to return only JSON.
You returns string value not JSON.
With like this code
echo "Polaczono";
Any echo would be the return value for ajax
At last you should return only one value like this.
echo json_encode($result);//an array result
You can check by string return. By removing dataType
I have a table with multiple fields and i want to update only one when same ID.The code that im using to update is next
<?php
require('db.php');
mysql_query("SET NAMES 'utf8'");
date_default_timezone_set('UTC');
include("auth.php"); //include auth.php file on all secure pages
$status = "";
if(isset($_POST['new']) && $_POST['new']==1){
$id=$_REQUEST['id'];
$query = "SELECT * from base where `id`='$id'";
$result = mysql_query($query) or die ( mysql_error());
$row = mysql_fetch_assoc($result);
$scantime = date("Y-m-d H:i:s");
$trn_date = date("Y-m-d H:i:s");
$id=$_REQUEST['id'];
$surname =$_REQUEST['surname'];
$name= $_REQUEST['name'];
$company_name=$_REQUEST['company_name'];
$firm= $_REQUEST['firm'];
$visitors= $_REQUEST['visitors'];
$barcode= $_REQUEST['barcode'];
$submittedby = $_SESSION["username"];
$update="update base set `scantime`='$scantime' where `id`='$id'";
mysql_query($update) or die(mysql_error());
}
?>
To search data i using ajax autocomplete function
require_once 'config.php';
mysql_query("SET NAMES 'utf8'");
if($_POST['type'] == 'country_table'){
$row_num = $_POST['row_num'];
$surname = $_POST['name_startsWith'];
$query = "SELECT custId,id,name, surname, company_name, firm,barcode,trn_date,scantime FROM base where UPPER(surname) LIKE '".strtoupper($surname)."%'";
$result = mysqli_query($con, $query);
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$name = $row['barcode'].'|'.$row['surname'].'|'.$row['name'].'|'.$row['company_name'].'|'.$row['firm'].'|'.$row['trn_date'].'|'.$row['scantime'].'|'.$row['id'].'|'.$row['custId'].'|'.$row_num;
array_push($data, $name);
}
echo json_encode($data);
}
And to fill data to input fields
$('#barcodescanr').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'ajax.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: 'barcodescanr',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function( event, ui ) {
var names = ui.item.data.split("|");
$('#name_1').val(names[2]);
$('#company_name_1').val(names[3]);
$('#surname_1').val(names[1]);
$('#firm_1').val(names[4]);
$('#info').val(names[5]);
$('#scanbartime').val(names[6]);
$('#Id').val(names[7]);
$('#custId').val(names[8]);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
The problem that i have is that when i press submit to form it doesnt update scantime .
Thank you
I wrote this call for user authentication:
$( '.sign-in' ).click( function(e) {
e.preventDefault();
var logincall = $.ajax({
type: "POST",
url: "../snippets/auth.php",
data: { username: $('#id_email').val(), password: $('#id_password').val() }
});
logincall.done(function( result ) {
alert( 'finished: ' + result );
if( result == 'valid' ) {
location.reload();
} else {
$( '.warning' ).toggleClass('hidden');
}
});
logincall.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
and here's the auth.php function
if( isset($_POST['username']) && isset($_POST['password']) ) {
$username = $_POST['username'];
$password = md5($_POST['password']);
$query = "SELECT COUNT(*) FROM member WHERE username='$username' AND password='$password';";
$result = $mysqli->query($query);
$result = $result->fetch_array(MYSQLI_ASSOC);
if( $result['COUNT(*)'] !== 0 ) {
$_SESSION['logged'] = true; //this sets
$query = "SELECT id, level FROM member WHERE username='$username' AND password='$password';";
$result = $mysqli->query($query);
$result = $result->fetch_array(MYSQLI_ASSOC);
$_SESSION['uid'] = $result['id']; //this DOES NOT set
$_SESSION['lvl'] = $result['level']; //this DOES NOT set
echo json_encode('valid');
} else {
echo json_encode('invalid');
}
}
The odd thing is, if I navigate directly to
myurl.com/snippets/auth.php?username=myusername&password=mypassword
it DOES set the other two session variables, but I can never get index.php to pick them up.
I even added that refresh line to it to ensure it could pick them up, and it gets $_SESSION['logged'] just fine, but not ['uid'] or ['level']
I am trying to pass some values to my PHP page and return JSON but for some reason I am getting the error "Unknown error parsererror". Below is my code. Note that if I alert the params I get the correct value.
function displaybookmarks()
{
var bookmarks = new String();
for(var i=0;i<window.localStorage.length;i++)
{
var keyName = window.localStorage.key(i);
var value = window.localStorage.getItem(keyName);
bookmarks = bookmarks+" "+value;
}
getbookmarks(bookmarks);
}
function getbookmarks(bookmarks){
//var surl = "http://www.webapp-testing.com/includes/getbookmarks.php";
var surl = "http://localhost/Outlish Online/includes/getbookmarks.php";
var id = 1;
$.ajax({
type: "GET",
url: surl,
data: "&Bookmarks="+bookmarks,
dataType: "jsonp",
cache : false,
jsonp : "onJSONPLoad",
jsonpCallback: "getbookmarkscallback",
crossDomain: "true",
success: function(response) {
alert("Success");
},
error: function (xhr, status) {
alert('Unknown error ' + status);
}
});
}
function getbookmarkscallback(rtndata)
{
$('#pagetitle').html("Favourites");
var data = "<ul class='table-view table-action'>";
for(j=0;j<window.localStorage.length;j++)
{
data = data + "<li>" + rtndata[j].title + "</li>";
}
data = data + "</ul>";
$('#listarticles').html(data);
}
Below is my PHP page:
<?php
$id = $_REQUEST['Bookmarks'];
$articles = explode(" ", $id);
$link = mysql_connect("localhost","root","") or die('Could not connect to mysql server' . mysql_error());
mysql_select_db('joomla15',$link) or die('Cannot select the DB');
/* grab the posts from the db */
$query = "SELECT * FROM jos_content where id='$articles[$i]'";
$result = mysql_query($query,$link) or die('Errant query: '.$query);
/* create one master array of the records */
$posts = array();
for($i = 0; $i < count($articles); $i++)
{
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = $post;
}
}
}
header('Content-type: application/json');
echo $_GET['onJSONPLoad']. '('. json_encode($posts) . ')';
#mysql_close($link);
?>
Any idea why I am getting this error?
This is not json
"&Bookmarks="+bookmarks,
You're not sending JSON to the server in your $.ajax(). You need to change your code to this:
$.ajax({
...
data: {
Bookmarks: bookmarks
},
...
});
Only then will $_REQUEST['Bookmarks'] have your id.
As a sidenote, you should not use alert() in your jQuery for debugging. Instead, use console.log(), which can take multiple, comma-separated values. Modern browsers like Chrome have a console that makes debugging far simpler.