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.
Related
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.
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 try to call a php function with Ajax. This is my JavaScript code in my html file:
<script type="text/javascript">
function ajax(){
$.ajax({
type:"POST",
url: "SQLCommunication.php",
dataType: "JSON",
success : function(json){
json = jQuery.parseJSON(json);
alert(json.value);
}
}
)
}
$("#btn_refresh").click(function(){
ajax();
});
</script>
I don't know if i have to specify which PHP function i actually want to call? I also don't know how i do that.
My PHP function:
header('Content-Type: application/json');
function readValue(){
$conn = establishConnection();
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT datetime, value FROM tempvalues";
$result = $conn->query($sql);
if($result->num_rows > 0){
$row = $result->fetch_assoc();
$arr["datetime"] = $row["datetime"]; //return datetime and value as array
$arr["value"] = $row["value"];
if(is_ajax()){
return json_encode($arr);
} else {
return $arr;
}
}
$conn->close();
}
So the problem is now, that nothing happens if i press the button.
I'll rewrite to my style
jQuery
<script type="text/javascript">
$("#btn_refresh").click(function(){
$.ajax({
type:"POST",
url: "SQLCommunication.php",
dataType: "JSON",
success : function(data){
console.log(data);
if(data.status === "success"){
alert("success");
}else{
alert("error");
}
}
error : function(XHR, status){
alert("fatal error");
}
})
});
</script>
PHP
header('Content-Type: application/json');
function readValue(){
$conn = establishConnection();
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT datetime, value FROM tempvalues";
$result = $conn->query($sql);
if($result->num_rows > 0){
$row = $result->fetch_assoc();
$arr["datetime"] = $row["datetime"]; //return datetime and value as array
$arr["value"] = $row["value"];
$arr["status"] = "success";
}else{
$arr["status"] = "error";
}
return json_encode($arr);
$conn->close();
}
echo readValue();
Untested
Updated
functions.php
function readValue(){
$conn = establishConnection();
if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT datetime, value FROM tempvalues";
$result = $conn->query($sql);
if($result->num_rows > 0){
$row = $result->fetch_assoc();
$arr["datetime"] = $row["datetime"]; //return datetime and value as array
$arr["value"] = $row["value"];
$arr["status"] = "success";
}else{
$arr["status"] = "error";
}
return json_encode($arr);
$conn->close();
}
function writeValue(){
...
}
SQLCommunication.php
header('Content-Type: application/json');
if(!isset($_GET['func']) && empty($_GET['func'])){
//make the file inaccessible without $_GET
$arr['status'] = "error";
echo json_encode($arr);
exit();
)
if($_GET['func'] === "readvalue"){
echo readValue();
}elseif($_GET['func'] === "writevalue"){
echo writeValue();
}elseif($_GET['func'] === "whatever"){
//whatever...
}
....
jQuery
$("#btn_refresh").click(function(){
$.ajax({
type:"POST",
url: "SQLCommunication.php?func=readvalue", //SQLCommunication.php?func=writevalue
dataType: "JSON",
success : function(data){
console.log(data);
if(data.status === "success"){
alert("success");
}else{
alert("error");
}
}
error : function(XHR, status){
alert("fatal error");
}
})
});
If you want to see the result in your ajax response, you have to use echo(), or any other printing method in your controller instead of return
Apologies if this is a repeat question, but any answer I have found on here hasn't worked me. I am trying to create a simple login feature for a website which uses an AJAX call to PHP which should return JSON. I have the following PHP:
<?php
include("dbconnect.php");
header('Content-type: application/json');
$numrows=0;
$password=$_POST['password'];
$username=$_POST['username'];
$query="select fname, lname, memcat from members where (password='$password' && username='$username')";
$link = mysql_query($query);
if (!$link) {
echo 3;
die();
}
$numrows=mysql_num_rows($link);
if ($numrows>0){ // authentication is successfull
$rows = array();
while($r = mysql_fetch_assoc($link)) {
$json[] = $r;
}
echo json_encode($json);
} else {
echo 3; // authentication was unsuccessfull
}
?>
AJAX call:
$( ".LogIn" ).live("click", function(){
console.log("LogIn button clicked.")
var username=$("#username").val();
var password=$("#password").val();
var dataString = 'username='+username+'&password='+password;
$.ajax({
type: "POST",
url: "scripts/sendLogDetails.php",
data: dataString,
dataType: "JSON",
success: function(data){
if (data == '3') {
alert("Invalid log in details - please try again.");
}
else {
sessionStorage['username']=$('#username').val();
sessionStorage['user'] = data.fname + " " + data.lname;
sessionStorage['memcat'] = data.memcat;
storage=sessionStorage.user;
alert(data.fname);
window.location="/awt-cw1/index.html";
}
}
});
}
As I say, whenever I run this the values from "data" are undefined. Any idea where I have gone wrong?
Many thanks.
This is my ajax call.
$(document).on('click','#Quote_create_value',function(){
$.ajax({
type : 'GET',
url : '../../../protected/config/ajax.php',
success : function(response){
$("#Quote_template_value").html(response);
}
});
});
I have many methods in ajax.php. Each and every method throws some response.
<?php
function respose()
{
$query = "select * from quote where template IS NOT NULL";
$result = mysql_query($query, $con);
while ($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['template'].'">' . $row['template'] . '</option>';
}
$query1 = "select * from template";
$data = mysql_query($query1,$con);
while ($row = mysql_fetch_assoc($data)) {
echo json_encode($row);
}
}
function result()
{
}
?>
But i want to get response from one method [ie. from response()].
How can this be done?
You could include a selector in the ajax request data. Like this for example:
$(document).on('click','#Quote_create_value',function(){
$.ajax({
type : 'GET',
url : '../../../protected/config/ajax.php',
data: "function=result",
success : function(response){
$("#Quote_template_value").html(response);
}
});
});
Then in your PHP code, a simple if-statement will check which one to output.
if(isset($_GET['function'])) {
if($_GET['result'] == 'result') {
// do result stuff
} elseif($_GET['function'] == 'response') {
// do response stuff
}
}