I have the following php and ajax code when I check in google chrome with ctrl+shift+I in network tab it shows the response as <{"response" : "2"} but this response can't be assigned to <h3> having id as respo
my php is
<<?php
$id = $_POST['reccount'];
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "testsite");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt update query execution
$sql = "SELECT * FROM paper WHERE ID=$id";
if(mysqli_query($link, $sql)){
$result = mysqli_query($link, $sql);
while($row = mysqli_fetch_array($result)) {
$data['response']= $row['response'];
$data['ansnum'] = $row['q_no'];
}
echo json_encode($data);
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
and ajax is
$.ajax({
type:"POST",
url:"<?php echo base_url();?>/shortfiles/loadans.php",
data: {reccount: reccount},
dataType:"JSON",
success: function(data){
alert (data.response);
$('#respond').text(data.response);
}
}) ;
and html is
<h3 ID="respond"style="margin-left:30px;">response</h3>
If the response from your PHP is:
<{"response" : "2"}
This would be an incorrectly formatted JSON string. This would be created by the extra < you have at the beginning of the document. I would advise you have the following PHP Opener:
<?php
This should correct the issue so the JSON Response would be:
{"response" : "2"}
It will be properly parse at that point.
Example
<?php
$id = (int)$_POST['reccount'];
$link = mysqli_connect("localhost", "root", "", "testsite");
header('Content-Type: application/json');
if($link === false){
die("{\"error\": \"Could not connect. " . mysqli_connect_error() . "\"}");
}
$sql = "SELECT * FROM paper WHERE ID=$id";
if(mysqli_query($link, $sql)){
$result = mysqli_query($link, $sql);
while($row = mysqli_fetch_array($result)) {
$data['response']= $row['response'];
$data['ansnum'] = $row['q_no'];
}
echo json_encode($data);
} else {
echo "{\"error\": \"Unable to execute $sql. " . mysqli_error($link) . "\"}";
}
mysqli_close($link);
?>
In my example, I cast the POST data to Integer to help ensure a malicious user does not get to send anything other than a digit. I also only send JSON data, even when sending an error. Using the header() helps define the data for the browser.
$.ajax({
type:"POST",
url:"<?php echo base_url();?>/shortfiles/loadans.php",
data: {reccount: reccount},
dataType:"JSON",
success: function(data){
console.log(data);
if(data.error !== undefined){
alert(data.error);
} else {
$('#respond').text(data.response);
}
}
});
Hope that helps.
Related
i have a ajax and php as follows but it is not changing the value of html attribute with id #respo
is there any modification require?
$.ajax({
type:"POST",
url:"<?php echo base_url();?>/shortfiles/loadans.php",
dataType: "json",
data: {reccount: reccount},
success: function(response) {
var response = ($response);
$("#respo").text(response);
},
})
and php as
<?php
$id = $_POST['reccount'];
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "testsite");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt update query execution
$sql = "SELECT response from paper WHERE ID=$id";
$result=mysqli_query($link, $sql);
while ($row = mysql_fetch_row($result)) {
$response => $row['response'];
}
echo json_encode($response);
// Close connection
mysqli_close($link);
?>
i want to assign a value of response to html element with id respo
Your code must look like
$.ajax({
type:"POST",
url:"<?php echo base_url();?>/shortfiles/loadans.php",
success:function(data){
var obj = jQuery.parseJSON(data);
document.getElementById('elementName').value = obj.varaibleName;
}
});
I'm creating a search form on a navbar to search for users on a mysql table.
I used a script i found online and, when i used it on localhost it all went fine. As soon as i typed the first letter of a name, i would instantly get the results.
But now, i placed the website on a webserver and what happens is the following:
I write 1 to 3 letters and nothing happens;
I write 4/5 letter and a error appears (Fatal error
: Call to undefined function mysqli_stmt_get_result() in
/home/pg22933/public_html/jade/backend-search.php
on line
68);
I write almost the full name of a user, and the result finally appears.
This is the file where i have all the code to do this:
<?php include('headers.php'); ?>
<script type="text/javascript">
function updateentrada(value, id)
{
console.log(value, id);
if(value == 1)
{
$.ajax({
type: 'post',
url: 'loaddata.php',
data: {
idconvidado:id,
entrada: 0
},
success: function () {
location.reload();
}
});
}
else if (value == 0)
{
$.ajax({
type: 'post',
url: 'loaddata.php',
data: {
idconvidado:id,
entrada: 1
},
success: function () {
location.reload();
}
});
}
}
</script>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "jade");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
if(isset($_REQUEST['term'])){
// Prepare a select statement
$sql = "SELECT * FROM convidados WHERE nome_convidado LIKE ?";
if($stmt = mysqli_prepare($link, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_term);
// Set parameters
$param_term = $_REQUEST['term'] . '%';
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
$result = mysqli_stmt_get_result($stmt);
// Check number of rows in the result set
if(mysqli_num_rows($result) > 0){
// Fetch result rows as an associative array
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$idconvidado = $row["id_convidado"];
$nome = $row["nome_convidado"];
$entrada = $row["entrada_convidado"];
if ($entrada == 1){
echo "<button value='". $entrada ."' name='". $idconvidado . "' onclick='updateentrada(this.value, this.name)' class='btnsearch'>" . $nome . " <i class='fa fa-check-circle-o check aria-hidden='true'></i></button>";
}
else if ($entrada == 0){
echo "<button value='". $entrada ."' name='". $idconvidado . "' onclick='updateentrada(this.value, this.name)' class='btnsearch '>" . $nome . " <i class='fa fa-circle-o check aria-hidden='true'></i></button>";
}
}
} else{
echo "<p>No matches found</p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// close connection
mysqli_close($link);
?>
What am i doing wrong?
http://php.net/manual/en/mysqli-stmt.get-result.php
It requires the mysqlnd driver, you need to install it on your web server
i want to insert data to mysql database using php service and json but when i click nothing happens it shows no error no message and the data is not added to the data base help please
here is the save function
function save(){
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {email: eml, mdp: mp}
$.ajax({
url:"http://localhost:800/test/insert.php",
type: 'POST',
data: data,
dataType: 'json',
success: function()
{alert("success");}
error: function()
{alert("fail");}
});
}
and this my php file insert.php
<?php
$json = $_POST['data'];
$new=json_decode($json, true);
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($conn,"bd") or die ("no database");
$sql = "INSERT INTO user (email,mdp) VALUES ($new['email'],$new['mdp'])";
if (mysqli_query($conn, $sql)) {
echo "created ";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>
You don't have "data" key in your $_POST array, you have "email" and "mdp", which you can access directly:
$email = mysqli_real_escape_string($_POST['email']);
$mdp = mysqli_real_escape_string($_POST['mdp']);
There is no json passed in this way, similarly when you have get string, you also don't need to parse it. Turn on error reporting, then you will see that $_POST['data'] is undefined.
BTW, use mysqli_real_escape_string to sanitize the input to prevent from injection.
"Insert.php" - > Not use for get data $json = $_POST['data'];
Only use this and try
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($conn,"bd") or die ("no database");
$email = $_POST['email'];
$mdp = $_POST['mdp'];
$new1 = json_encode($email);
$new2 = json_encode($mdp);
$sql = "INSERT INTO user ('email','mdp') VALUES ('".$new1."','".$new2."')";
$insert = mysqli_query($sql);
if ($insert) {
echo "created ";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Your PHP code seems to be correct, but please try the jQuery AJAX code as follows:
function save(){
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {email: eml, mdp: mp}
$.ajax({
url: "http://localhost:800/test/insert.php",
type: 'POST',
dataType: 'json',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
error: function () {
alert('fail');
},
success: function (data) {
alert('success');
}
});
}
In your data section has to be passed as JSON String, secondly you missed to in include the data contentType. Here content type is set as application/json, therefore pass the data as JSON string.
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);
}
?>
Trying to pass data to the server but it keeps returning a "Parameter Missing"
So either the data is not being passed to the PHP script or I am doing something wrong.
Here is the jQuery:
function quickJob(obj) {
var quickJobNumber = $(obj).text();
//alert(quickJobNumber)
$.ajax({
type: "GET",
url: "quickJobCB.php",
data: quickJobNumber,
success: function(server_response)
{
$("#message").removeClass().html(server_response);
}
});
}
Ok....when tracing the issue I created an alert as seen below. The alert is producing the expected results.
Here is the PHP script:
<?php
require_once("models/config.php");
// Make the connection:
$dbc = #mysqli_connect($db_host, $db_user, $db_pass, $db_name);
if (!$dbc) {
trigger_error('Could not connect to MySQL: ' . mysqli_connect_error());
}
if (isset($_GET['quickJobNumber'])) {
$quickJobNumber = trim($_GET['quickJobNumber']);
$quickJobNumber = mysqli_real_escape_string($dbc, $quickJobNumber);
$query = "SELECT * FROM projects WHERE projectNumber = '" . $quickJobNumber . "'";
$result = mysqli_query($dbc, $query);
if ($result) {
if (mysqli_affected_rows($dbc) != 0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo $row['projectName'];
}
} else {
echo 'No Results for :"' . $_GET['quickJobNumber'] . '"';
}
}
} else {
echo 'Parameter Missing';
}
?>
<?php include("models/clean_up.php"); ?>
data: quickJobNumber,
should be
data: { 'quickJobNumber': quickJobNumber },
You'll need to pass the data either as a query string like so
data: "quickJobNumber="+quickJobNumber,
or a map like so
data: data { quickJobNumber: quickJobNumber },
If you want to use the GET request, use $.get
$.get("/get_request.php", { quickJobNumber: "myAjaxTestMessage"},
function(data){
console.log("WOW! Server was answer: " + data);
});
In php
<?php
if(isset($_GET['quickJobNumber'])){
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('answer'=>'Hello user!'));
}
?>
If you want to use the POST request, use $.post
$.post("/post_request.php", { quickJobNumber: "myAjaxTestMessage"},
function(data){
console.log("WOW! Server was answer: " + data);
});
In php
<?php
if(isset($_POST['quickJobNumber'])){
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('answer'=>'Hello user!'));
}
?>
P.S. or you can use $_REQUEST in php.