When using Select2 on localhost (XAMPP) server to get data from the database, it works perfectly. But after deploying it to server, it doesn't work, and console shows 500 Internal Server Error.
Following is the code I'm using:
$('#search-box').select2({
placeholder: 'Select an item',
ajax: {
url: 'php/search.php',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: data
};
},
cache: true
}
});
And the PHP code in search.php:
require_once("dbinfo.php");
// Opens a connection to a MySQL server
$connection=mysqli_connect ('localhost', $username, $password);
if (!$connection) { die('Not connected : ' . mysqli_error($connection));}
// Set the active MySQL database
$db_selected = mysqli_select_db($connection, $database);
if (!$db_selected) {
die ('Can\'t use db : ' . mysqli_error($connection));
}
$sql = "SELECT c_id, city_name FROM city
WHERE city_name LIKE '%".$_GET['q']."%'
LIMIT 10";
$result = $connection->query($sql);
$json = [];
while($row = $result->fetch_assoc()){
$json[] = ['id'=>$row['c_id'], 'text'=>$row['city_name']];
}
echo json_encode($json);
What is going wrong here?
In the ajax, set type to "GET"
ajax: {
url: 'php/search.php',
type: 'GET',
dataTy.......
This works for me.
Related
Jquery Mobile - Ajax call to fetch data from Json data from MySql database returning error.
Here's my code
Server code
<?php
try{
header('Content-type: application/json');
$server = "myurl";
$username = "username";
$password = "password";
$database = "mydb";
$con = mysqli_connect($server, $username, $password, $database) or die ("Could not connect: " . mysql_error());
/*mysql_select_db($database, $con);
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
*/
$sql = "SELECT id, l_name AS name, l_lat AS value1, l_long AS value2 FROM landmarks ORDER BY l_name";
$result= mysqli_query($con, $sql);
$records = array();
while($row = mysqli_fetch_assoc($result)) {
$records[] = $row;
}
mysqli_close($con);
echo json_encode($records);
}
catch(Throwable $e) {
$trace = $e->getTrace();
echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine().' called from '.$trace[0]['file'].' on line '.$trace[0]['line'];
}
?>
my ajax call
try {
$.ajax({
url: 'myurl',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var res = '<h1>'+item.name+'</h1>'
+ '<p>'+item.value1+'<br>'
+ item.value2+'</p>';
output.append(res);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
}
catch (e) {
logMyErrors(e);
}
Here ajax is returning the error function.
But while running the server code in the browser, json data is displayed correctly.
Nothing is being logged in the console. Please help to find out what has gone wrong.
I want delete a record from database and to do it I want use ajax..
So I have a table where I put into last td this:
<input type='image' src='./img/delete.png' onClick='deleteUser(".$utentiIscritti[$i][0].");' />
this is my deleteUser function:
function deleteUser(id){
$.ajax({
type:"post",
url: "deleteUserAjax.php",
data: {'id':id},
success: function(data){
console.log("OK");
location.reload();
},
error: function(xhr, status, error){
alert(xhr+"\n\n"+status+"\n\n"+error);
console.log("KO");
}
});
}
And this is my php page to connect to db and delelte the record:
<?php
$USERDB = "u";
$PASSWORDDB = "p";
$NAMEDB = "d";
$queryDeleteUser = 'delete from user where id = "'.$_POST['id'].'"';
$conn = mysql_connect("localhost", $USERDB, $PASSWORDDB)
or die("Errore nella connessione al database: " . mysql_error());
mysql_select_db($NAMEDB) or die("Errore nella selezione del database: " . mysql_error());
mysql_query($queryDeleteUser) or die("Errore nella query: " . $queryDeleteUser . "\n" . mysql_error());
dbDisconnect($conn);
But I obtain always (from every ajax request) error:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
iscritti.php:80
Why???
You can consider two solutions.
Your code is buggy. Try to execute it on it's own. Just call it in your browser and check the result!
You have specified a relational path for your script. url: "deleteUserAjax.php", try instead an absolute path and check the result (url: "http://yourdomain.com/deleteUserAjax.php")
Maybe make it more cleaner:
HTML part:
<input type='image' src='./img/delete.png' value='<?=$id?>'>
jQuery part:
$(document).ready(function(){
$("#delete").on("click", function(){
var data = $(this).val();
$.ajax({
method: "POST",
url: "page_you_handle_it.php?action=delete",
data: {'id':id}
}).done(function(data){
//here you get response of your delete function!
});
});
});
PHP part:
$host = "[HOST]"; //Like localhost
$user = "[USER]"; //Like root
$pass = "[PASS]"; //Like 123
$db = "[DB]"; //Like users
$con = mysqli_connect($host, $user, $pass, $db) or die ("Conntecting the Database gone wrong");
$id = $_POST['id'];
$query_str = "DELETE FROM user WHERE id = '$id'";
$query = mysqli_query($con, $query_str);
if (!$query) //Do not run the `$query` in the return parts because it already runs when you say `if (!$query)`
{
echo 'Delete gone wrong';
}
else
{
echo 'Delete succes!';
}
I try to DELETE a row in mysql. I got help to insert and it works well. I tried to use the same logic for delete one row with ID identification, but I can not delete the row.
What is wrong in this code?
...
Here is the full code:
Javascript:
function jsRecordDeleteWrite()
{
var jsObject = {
"ID": document.form_articles.ID.value
};
// ... the AJAX request is successful
var updatePage = function (response) {
alert("record successful deleted");
};
// ... the AJAX request fail
var printError = function (req, status, err) {
alert("deletingt record failed");
};
// Create an object to describe the AJAX request
$.ajax({
url : 'deletearticle.php',
dataType : 'json',
contentType: 'application/x-www-form-urlencoded',
data : jsObject,
type : 'POST',
success: updatePage,
error: printError
});
}
Here is deletearticle.php
<?php
$link = mysql_connect('localhost', 'admin0', 'star1star1star0');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('sob', $link);
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
//read the json file contents
$ID = $_POST['ID'];
//delete item from mysql table
$sql = mysql_query("DELETE FROM articles WHERE ID=$ID");
if(!mysql_query($sql))
{
die('Error : ' . mysql_error());
}
//database connection close
mysql_close($link);
//}
?>
Verify that the server receives in php
var_dump($ID);
If query is right, check the mysql user has rights to update table
Put single quotes around $ID:
//delete item from mysql table
$sql = mysql_query("DELETE FROM articles WHERE ID= '$ID'");
I'm using PhoneGap to create a Android QR code scanning app which act as a client, while the server is using PHP with MySQL (WAMP). Below is the section of QR scanning app to send the scanned result to the server, it manage to send and get reply from server, so I think the problem is at my server code in the next section
$.ajax({
url: "http://192.168.1.2/receiveQR.php",
type: 'POST',
data: {
QR: result.text
},
success: function(response) {
$('#result').html(''); //clean the field
alert("QR sent to server successfully");
$("#result").append(response + '<br/>');
},
error: function() {
alert('Not working!');
}
});
Server code: to receive the QR scanned result as input then use the input to retrieve record from MySQL database to display the result on PHP page immediately, although my code can successfully retrieve the record from db, but the ECHO is show on my Android APP and not my server PHP interface.
I want to achieve result like Library Barcode Scanning result, is my method wrong?
<?php
if(isset($_POST['QR'])){ //check is the QR result is empty or not
$qr = $_POST['QR']; //QR scanned result send from APP to server
$tablename = "book";
$db = mysql_connect("localhost", "root", "");
if(!mysql_select_db("testing", $db)){
print mysql_error();
}
if(!empty($qr)) {
$sql="SELECT bk_title FROM ".$tablename." WHERE bk_id = '".$qr."'";
$retval = mysql_query($sql, $db);
if(! $retval){
die("Cound not get data: ".mysql_error());
}
while($row = mysql_fetch_assoc($retval)){
echo "Book Title :{$row['bk_title']} <br> ";
}
mysql_close($db);
}
$reply = "Server Received";
print json_encode($reply);
}
?>
You did couple of mistakes over here.
Please replace your code with below code:
$.ajax({
url : "http://192.168.1.2/receiveQR.php",
dataType: "json"
type : 'POST',
data : { QR : result.text},
success : function(response){
$('#result').html(''); //clean the field
alert("QR sent to server successfully");
$("#result").append(response.data + '<br/>');
},
error : function() {
alert('Not working!');
}
});
<?php
if(isset($_POST['QR']))
{
//check is the QR result is empty or not
$qr = $_POST['QR']; //QR scanned result send from APP to server
$tablename = "book";
$db = mysql_connect("localhost", "root", "");
if(!mysql_select_db("testing", $db)){
print mysql_error();
}
if(!empty($qr)) {
$reply=array();
$sql="SELECT bk_title FROM ".$tablename." WHERE bk_id = '".$qr."'";
$retval = mysql_query($sql, $db);
if(! $retval){
die("Cound not get data: ".mysql_error());
}
while($row = mysql_fetch_assoc($retval)){
$reply['data'] = "Book Title :{$row['bk_title']} <br> ";
}
mysql_close($db);
}
$reply['message'] = "Server Received";
print json_encode($reply);
}
?>
use this one
javascript
formData = {
QR: result.text
}
$.ajax({
url: "http://192.168.1.2/receiveQR.php",
type: 'POST',
data: formData,
success: function(response) {
$('#result').html(''); //clean the field
alert("QR sent to server successfully");
$("#result").append(response + '<br/>');
},
error: function() {
alert('Not working!');
}
});
php
<?php
if(isset($_POST['QR'])){ //check is the QR result is empty or not
$qr = $_POST['QR']; //QR scanned result send from APP to server
$tablename = "book";
$db = mysql_connect("localhost", "root", "");
if(!mysql_select_db("testing", $db)){
print mysql_error();
}
if(!empty($qr)) {
$sql="SELECT bk_title FROM ".$tablename." WHERE bk_id = '".$qr."'";
$retval = mysql_query($sql, $db);
if(! $retval){
die("Cound not get data: ".mysql_error());
}
while($row = mysql_fetch_assoc($retval)){
echo "Book Title :{$row['bk_title']} <br> ";
}
mysql_close($db);
}
$reply = "Server Received";
print json_encode($reply);
}
?>
I have a MYSQL table that has a column defined as TEXT, when i reading the contents into PHP the result is that the data is not being pulled through.
my php code
SELECT establishments.name AS estName,
establishments.address AS estAddr,
establishments.telephone_num AS estTel,
establishments.description AS estDesc,
establishments.Logo AS estLogo,
establishments.title AS estTitle
FROM bucurestideals1.establishments
WHERE establishments.establishment_id ="'.$est_id.'"';
The table row has data so this is not an issue, i am reading the data using php as below:
$.ajax({
type: 'GET',
url: pass_url,
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function (data, status) {
// Assign the returned data to the page
$.each(data, function(i,item)
{
alert(item.estDesc);
});
},
Update: PHP Code
<?php
header('Content-type: application/json');
$est_id = $_GET['id'];
$server = "*";
$username = "*";
$password = "*";
$database = "";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result))
{
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
You can probably remove the quotes from your where statement. If that is not the issue, can you post the php code that you use to execute the sql?