I have created a .post() request
function validateLogin()
{
var username = $("#username").val();
var password= $("#password").val();
var details = {"name": username, "password": password};
console.log(details);
console.log(JSON.stringify(details));
$.post("getthedb.php", JSON.stringify(details), function(response)
{
if(response.code==0)
{
alert("Response: " + response.message);
$("#myDiv").innerHTML = response.message;
}
else
{
$("#myDiv").innerHTML = response.message;
}
}, "application/json");
}
getthedb.php
<?php
header('Content-type: application/json');
$jsonobj = file_get_contents("php://input");
$detail= json_decode($jsonobj);
if(($detail->{'name'}=="abc") && ($detail->{'password'}=="abc"))
{
$response1['code']=0;
$response1['message']="Success";
}
else
{
$response1['code']=1;
$response1['message']="No Success";
}
$response = json_encode($response1);
echo $response;
?>
This is not giving back any result,'console.log(details)' and
'console.log(JSON.stringify(details))' produces the JSON object. how to debug this???
where am i lagging here.??
If you code doesn't provide some error i assume that your if down there isn't called and $response1 is empty. So no response to read.
if(($detail->{'name'}=="abc") && ($detail->{'password'}=="abc")
{
$response1['code']=0;
$response1['message']="Success";
}
else ???
$response = json_encode($response1); // Response1 is empty
echo $response;
missing ) in if loop.
if(($detail->{'name'}=="abc") && ($detail->{'password'}=="abc")
should be
if(($detail->{'name'}=="abc") && ($detail->{'password'}=="abc"))
$response1 array not declared.
You haven't written else case
Related
I know this is a duplicate question but I still need help with my code.
When I make a post request with postman it succeeds but when I use the flutter code it fails.
Any idea why?
So this is the flutter code to make the post request:
Future createQuote() async {
final response = await http.post(
Uri.parse('http://<myserver.com>/quotes/post.php'),
body: json.encode(
{
'quot': _quoteController.text,
'teller': _tellerController.text,
},
),
);
if (response.statusCode == 200 && response.body == 'success') {
print('s: ' + response.body);
// Navigator.pop(context);
} else {
print(response.body);
var test = jsonEncode(
{
'quot': _quoteController.text,
'teller': _tellerController.text,
},
);
print(test);
// throw Exception('Failed to create quote');
}
}
And this is the php file:
require_once('db.php');
$stm = $db->prepare("INSERT INTO quots (quot, teller) VALUES (:quot, :teller)");
$stm->bindParam(':quot', $_POST['quot']);
$stm->bindParam(':teller', $_POST['teller']);
$quot = $_POST['quot'];
$teller = $_POST['teller'];
if ($stm->execute()) {
echo "success";
} else {
echo "failure: ". $_POST['quot'] . $teller;
};
There is no need to jsonEncode the post body, use it as a plain Map.
final response = await http.post(
Uri.parse('http://<myserver.com>/quotes/post.php'),
body:
{
'quot': _quoteController.text,
'teller': _tellerController.text,
},
);
I have an AJAX call from jQuery to PHP where the PHP responds with a json_encode array, but the values of the array are not accessible in jQuery.
The status is OK, but the responseText is undefined.
$(document).ready(function () {
$("#comments_form").on("submit", function(e) {
e.preventDefault();
e.stopPropagation();
$.ajax({
type: 'POST',
url: 'process_in.php',
data: {
first: $("#firstname").val(),
second: $("#lastname").val(),
third: $("#mail").val(),
fourth: $("#phone").val(),
fifth: $("#message").val()
},
success: function(result) {
var x = jQuery.parseJSON(result);
alert(x.f);
},
});
});
})
<?php
include ('connection.php');
if (isset($_REQUEST['first']) && isset($_REQUEST['second']) && isset($_REQUEST['third']) && isset($_REQUEST['fourth']) && isset($_REQUEST['fifth']))
{
$firstname = $_REQUEST['first'];
$lastname = $_REQUEST['second'];
$email = $_REQUEST['third'];
$contact = $_REQUEST['fourth'];
$message = $_REQUEST['fifth'];
$data = array();
$data["f"] = xssafe($firstname);
$data["l"] = xssafe($lastname);
$data["e"] = xssafe($email);
$data["c"] = xssafe($contact);
$data["m"] = xssafe($message);
echo json_encode($data);
}
function xssafe($d)
{
$x = filter_var($d, FILTER_SANITIZE_STRING);
return $x;
}
A good practice is to always catch the errors too. In your ajax request there is no error callback to handle the exception.
Use dataType: "JSON" instead of jQuery.parseJSON(); so that if json in unparsable you get the callback in the error block.
$.ajax({
type: 'POST',
url: 'process_in.php',
dataType: 'JSON',
data: {
first: $("#firstname").val(),
second: $("#lastname").val(),
third: $("#mail").val(),
fourth: $("#phone").val(),
fifth: $("#message").val()
},
success: function(result) {
console.log(result.f);
},
error: function (jqXHR, exception) {
var msg = '';
if (jqXHR.status === 0) {
msg = 'Not connect.\n Verify Network.';
} else if (jqXHR.status == 404) {
msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
msg = 'Time out error.';
} else if (exception === 'abort') {
msg = 'Ajax request aborted.';
} else {
msg = 'Uncaught Error.\n' + jqXHR.responseText;
}
console.log(msg);
}
});
You can learn how to debug the code and check your error logs
Now lets get to your code, there are many possible cases that you are not getting the value.
It could be your php code or it could be your jquery.
In php to check whether its returning a valid json hit the url in browser like this
http://.../process_in.php?first=foo&second=foo&third=foo&fourth=foo&fifth=foo
As in your php code you haven't return any value so add an else part for the
if (isset($_REQUEST['first']) && isset($_REQUEST['second']) && isset($_REQUEST['third']) && isset($_REQUEST['fourth']) && isset($_REQUEST['fifth']))
{
$firstname = $_REQUEST['first'];
$lastname = $_REQUEST['second'];
$email = $_REQUEST['third'];
$contact = $_REQUEST['fourth'];
$message = $_REQUEST['fifth'];
$data = array();
$data["f"] = xssafe($firstname);
$data["l"] = xssafe($lastname);
$data["e"] = xssafe($email);
$data["c"] = xssafe($contact);
$data["m"] = xssafe($message);
echo json_encode($data);
} else {
echo json_encode(['error'=>'Invalid request']);
}
I've created an Arduino project wich sends the coordinates to an URL. The URL does some ajax calls. In the browser it works fine, but when I'm trying it with the Arduino it doesn't work. So I tried to do the same thing with an iOS app, but I got the same problem. This is the code on the page that the Arduino and iOS app request.
var directionsService = new google.maps.DirectionsService();
var base_url = window.location;
var received_data = <?php echo json_encode($received_data); ?>;
$.ajax({
url: 'http://gps-tracker.domain.nl/_api/handler.php',
data: { action: 'post', device_id: received_data['device_id']},
type: 'GET',
dataType:"jsonp",
jsonp:"callback",
success: function (response){
var error = [];
var total = response.length;
for (var type in response) {
if(response[type].types == 'area'){
var x = checkInsideCircle(response[type].longitude, response[type].latitude, received_data['longitude'], received_data['latitude'], response[type].reach / 1000);
if(x == false){
// Outside
error.push(true);
}else{
// Inside
error.push(false);
}
}else if(response[type].types == 'route'){
// Check route
checkOnRoute(response[type].start_latitude, response[type].start_longitude, response[type].end_latitude, response[type].end_longitude, response[type].type, response[type]['reach'], type, function(result) {
error.push(result);
if(error.length == total){
if(error.indexOf(false) >= 0){
// Device is inside route or area
outside = false;
}else{
// Send data to database
$.ajax({
url: 'http://gps-tracker.domain.nl/_api/handler.php',
data: { action: 'post', device_id: received_data['device_id'], longitude: received_data['longitude'], latitude: received_data['latitude']},
type: 'GET',
dataType: 'json',
success: function (response){
console.log('good');
},error: function(jq,status,message) {
alert('A jQuery error has occurred. Status: ' + status + ' - Message: ' + message);
}
});
}
}
});
}
}
},error: function(jq,status,message) {
alert('A jQuery error has occurred. Status: ' + status + ' - Message: ' + message);
}
});
Here is the code from the handler.php file, that the ajax request requests.
$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : false;
// Switch actions
switch($action) {
case 'get':
$callback ='callback';
if(isset($_GET['callback'])){
$callback = $_GET['callback'];
}
$routes = ORM::for_table('gps_tracker_route')
->inner_join('gps_tracker_device', array('gps_tracker_device.device_id', '=', 'gps_tracker_route.device_id'))
->where('gps_tracker_route.device_id', $_GET['device_id'])
->where('gps_tracker_device.device_id', $_GET['device_id']);
if($routes = $routes->find_many()){
foreach($routes as $k=>$v){
$v = $v->as_array();
if($v['status'] == 'on' or strtotime(date('Y-m-d H:i:s')) > strtotime($v['start_time']) and strtotime(date('Y-m-d H:i:s')) < strtotime($v['end_time'])){
$response1[$k] = $v;
$response1[$k]['types'] = 'route';
}
}
}
$area = ORM::for_table('gps_tracker_area')
->inner_join('gps_tracker_device', array('gps_tracker_device.device_id', '=', 'gps_tracker_area.device_id'))
->where('gps_tracker_area.device_id', $_GET['device_id'])
->where('gps_tracker_device.device_id', $_GET['device_id']);
if($area = $area->find_many()){
foreach($area as $k=>$v){
$v = $v->as_array();
if($v['status'] == 'on' or strtotime(date('Y-m-d H:i:s')) > strtotime($v['start_time']) and strtotime(date('Y-m-d H:i:s')) < strtotime($v['end_time'])){
$response2[$k] = $v;
$response2[$k]['types'] = 'area';
}
}
}
if(isset($response1) and isset($response2)){
$response = array_merge($response1, $response2);
}elseif(isset($response1)){
$response = $response1;
}else{
$response = $response2;
}
if ( isset($response) ) {
if ( is_array($response) ) {
if (function_exists('json_encode')) {
header('Content-Type: application/json');
echo $callback.'(' . json_encode($response) . ')';
} else {
include( ABSOLUTE_PATH . '/classes/json.class.php');
$json = new Services_JSON();
echo $json->encode($response);
}
} else {
echo $response;
}
exit(0);
}else{
exit();
}
break;
case 'post':
$_GET['timestamp'] = date("Y-m-d H:i:s");
$record = ORM::for_table('gps_tracker_device_logging')->create($_GET);
$record->save();
$item = ORM::for_table('gps_tracker_device_logging')
->where('id', $record->id);
if($item = $item->find_one()){
$item = $item->as_array();
echo json_encode($item);
}
break;
default:
die('invalid call');
}
Can someone help me?
EDIT
I think it is something with Javascript. I don't know if it's possible to use javascript when a device, like Arduino, makes a http request to a server. Someone know?
I think that it's because you need a Web Browser that supports JavaScript.
I don't work with Arduino, but from what I know it does not have a "real" Web Browser - it can only pull/download data but can't execute the JS part.
For JS to work you need something to run it. That is why it works in a the browser.
I'm using an action from LoginController.php:
public function ajaxAction()
{
$form = $this->getServiceLocator()->get('LoginForm');
$post = $this->request->getPost();
$form->setData($post);
$response = $this->getResponse();
if (!$form->isValid()){
// something is invalid; print the reasons
$json= $form->getMessages();
$response->setContent(\Zend\Json\Json::encode($json));
return $response;
} else {
$this->getAuthService()->getAdapter()->setIdentity(
$this->request->getPost('email'))->setCredential(
$this->request->getPost('password'));
$result = $this->getAuthService()->authenticate();
switch ($result->getCode()) {
case Result::FAILURE_IDENTITY_NOT_FOUND:
$json = "Email or password is incorrect";
$response->setContent(\Zend\Json\Json::encode($json));
return $response;
case Result::FAILURE_CREDENTIAL_INVALID:
$json = "Email or password is incorrect";
$response->setContent(\Zend\Json\Json::encode($json));
return $response;
}
}
}
and I get these Encoded $json values in script.js:
$('#navLogin').removeAttr('style');
$('#labelLogin').css('display', 'none');
$("#Login input").blur(function()
{
$("#formLoginErrorMessage").children().remove();
var formElementId = $(this).parent().find('input').attr('id');
doValidation(formElementId);
});
function doValidation(id, url)
{
var url = 'ajax/';
var data = {};
$('input').each(function()
{
data[$(this).attr('name')] = $(this).val();
});
$.post(url,data,function(resp)
{
$('#'+id).parent().find('.alert-danger').remove();
if(resp === null)
{
console.log("Dang");
}else if (typeof resp === "object") {
$('#'+id).parent().find('.alert-danger').remove();
$('#'+id).parent().append(getErrorHtml(resp[id], id));
console.log(resp);
} else {
$("#formLoginErrorMessage").addClass("alert-danger");
$("#formLoginErrorMessage").append("<li>" + resp + "</li>");
console.log(resp);
}
},'json');
}
function getErrorHtml(formErrors, id)
{
var o = '<ul id="errors-'+id+'" class="alert-danger">';
for(errorKey in formErrors)
{
o += '<li>' + formErrors[errorKey] + '</li>';
}
o+= '</ul>';
return o;
}
Using ajaxAction i encode error messages from a login form that might appear and pass them in $.post(url,data,function(resp){..., where resp is encoded object from php.
Problem When there are nothing to encode in Google Developer Tools I get:
POST http://new.local/login/ajax/ 500 (Internal Server Error)
Fix By adding this to LoginController.php i don't get a 500 Error and can process JSON object.
if(!isset($json)){
$json = " ";
$response->setContent(\Zend\Json\Json::encode($json));
return $response;
}
}
I am trying to send some data using php and jquery ajax using json datatype method.
Here is my code:
$("#username").on("keyup change keypress", function () {
var username = $("#username").val();
$.ajax
({
type: "POST", // method send from ajax to server
url: window.location.protocol + '//' + window.location.host + '/' + "admin/admins/user_exists",
data: {
username: username
},// Specifies data to be sent to the server
cache: false, // A Boolean value indicating whether the browser should cache the requested pages. Default is true
contentType: "application/json",
dataType: 'json', // The data type expected of the server response.
success: function (response_data_from_server) {
for (var key in response_data_from_server)
var result = response_data_from_server[key] + ""; // JSON parser
if (result == 'true') {
console.log("---------------- in true");
$("#username_alert").text("ERROR");
$('#username_alert').removeClass("alert-success");
$("#username_alert").css("visibility", "visible");
}
else {
if (result == 'false') {
console.log("---------------- in false");
$("#username_alert").text("NO ERROR");
$("#username_alert").css("visibility", "visible");
$('#username_alert').addClass("alert-success");
}
else {
if (result == 'empty') {
console.log("---------------- in empty");
$("#username_alert").text("ERROR");
$("#username_alert").css("visibility", "visible");
$('#username_alert').removeClass("alert-success");
}
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
and it always goes to an error function. The error that I receive is the following:
parsererror SyntaxError: Unexpected token {}
My url location is correct and is indeed returning the correct json format. Here is my php code:
public function user_exists()
{
$username = $this->input->post("username");
$is_exists = "false";
$this->load->database();
if ($username != "")
{
$rows = $this->db->query("
SELECT * FROM `admins` WHERE `username` = '" . $username . "'
")->num_rows();
if ($rows > 0)
{
$is_exists = "true";
}
else
{
$is_exists = "false";
}
}
else
{
$is_exists = "empty";
}
$arr = array ('result' => $is_exists );
$response = json_encode($arr);
echo $response;
}
I've debugged it million times, the firebug sees the response as correct and expected json, however the client side seems to refuse to get it as a json respone, for what I believe.
Will appreciate any help!
...
header('Content-type: application/json');
echo $response;
Maybe you could use "header('Content-type: application/json');" before "echo"