json object in php not being read - php

I want to pass username and password to a php script and check in the database. On the client side I use the following script to make a json object and post it to the php file.
var myobj = {};
myobj["usrname"]= $( "#customer option:selected" ).text();
myobj["usrpass"]= $("#psw").val();
var myjson = JSON.stringify(myobj);
$.ajax({
method: "POST",
url: "checkpass.php",
data: myjson
})
.done(function( msg ) {
alert( msg );
});
On the server side, when I see in firebug, the post is passed as
Parametersapplication/x-www-form-urlencodedDo not sort
{"usrname":"XXXXXXX...
JSON
usrname
"XX"
usrpass
"justdoit"
Source
{"usrname":"XXX","usrpass":"justdoit"}
however when i run the php script to check the query the it returns an error
$usrname = $_POST['usrname'];
$usrpass = $_POST['usrpass'];
$sql = "select count(*) from glusers where EmpName='$usrname' and EmpPass='$usrpass'";
$result = $conn->query($sql);
if($result >0){
$output = 'Success';
} else
{
$output = 'fail';
}
I have tried through all the posts but cannot get this to work.
Thanks in advance.
Regards,

Echo and die the statement in order for ajax to have a success event
Js File
var myobj = {};
myobj["usrname"] = 'myUsername';
myobj["usrpass"] = 'myPassword';
$.ajax({
type: "post",
url: "url",
dataType: "json",
data: {post_data: myobj},
contentType: "application/x-www-form-urlencoded",
success: function (responseData) {
console.log(responseData);
},
error: function (errorThrown) {
console.log(errorThrown);
}
});
PHP action File
/** if we print post we will get the following array * */
//print_r($_Post);
//die()
//Array
//(
// [post_data] => Array
// (
// [usrname] => myUsername
// [usrpass] => myPassword
// )
//
//)
if (isset($_Post['post_data'])) {
$myPost = $_Post['post_data'];
$usrname = $myPost['usrname'];
$usrpass = $myPost['usrpass'];
$sql = "select count(*) from glusers where EmpName='$usrname' and EmpPass='$usrpass'";
$result = $conn->query($sql);
$num_row = $result->num_rows;
if ($num_row > 0) {
$output = 'Success';
} else {
$output = 'fail';
}
echo json_encode($output);
die();
}

Try This :
in js file :
$(document).on("ready", function(){
// Create an object using an object literal.
var ourObj = {};
// Create a string member called "data" and give it a string.
// Also create an array of simple object literals for our object.
ourObj.data = "Some Data Points";
ourObj.arPoints = [{'x':1, 'y': 2},{'x': 2.3, 'y': 3.3},{'x': -1, 'y': -4}];
var savedata = JSON.stringify(ourObj)
$.ajax({
type:"POST",
url:"Users.php",
data: {"points" : JSON.stringify(ourObj)},
success: function(data) {
// Do something with data that came back.
alert(data);
}
})
});
In PHP File :
if (isset($_POST["points"])) {
$points = json_decode($_POST["points"]);
echo "Data is: " . $points->data . "<br>";
echo "Point 1: " . $points->arPoints[0]->x . ", " . $points->arPoints[0]->y;
}

Try this:
var myobj = '{
usrname:'+$( "#customer option:selected" ).text()+',
usrpass:'+$("#psw").val()+'
}';
or
var myobj = {};
myobj.usrname= $( "#customer option:selected" ).text();
myobj.usrpass= $("#psw").val();

Use Json2 library as follows,
var myobj = {};
myobj["usrname"]= $( "#customer option:selected" ).text();
myobj["usrpass"]= $("#psw").val();
var myjson = JSON2.stringify(myobj);
$.ajax({
method: "POST",
url: "checkpass.php",
data: myjson
})
.done(function( msg ) {
alert( msg );
});

Well actually you php code is invalid because you pass json day not name value pair so you cant get it from $_POST['username']. You need to get the whole post data and decode it like this.
$data = json_decode(file_get_contents('php://input'), true);
Now $data is dictionary array of username and password. Also sanitize your data before passing to query to avoid sql injection.

Related

Ajax success function not working with json answer

If I set dataType to 'json' and inside my PHP file I print whatever I want (event a letter), success function works, but if I don't print anything else besides the JSON I need, stops working. I can't handle my data with something else printed, because it turns the answer into HTML, instead of JSON. I'm able to see in Network -> Answer the JSON file (only when I don't print anything else beside the JSON), but I don't know why I can't even do an alert in success function when that is the case.
This is my ajax, which only works because I'm printing 'true' on the server:
$(document).on("click", "#btnEditarInstructor", function(event) {
event.preventDefault();
let rfc = $(this).attr("value");
$.ajax({
type: "POST",
url: "../utils/ajax/ajax_consulta_instructor.php",
data: {
rfc: rfc,
},
dataType: "json",
succes: function(response) {
if (response == true) {
// alert(response);
}
},
error: function(request, status, error) {
var val = request.responseText;
alert("error" + val);
alert(status);
alert(error);
},
});
})
This is my PHP code:
$rfc = $_POST['rfc'];
$sql = "SELECT * FROM instructores WHERE rfc = '$rfc'";
$sql_run = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($sql_run)) {
echo "true";
$datos['status'] = 'OK';
$datos['nombre'] = $row['nombre'];
$datos['apellidos'] = $row['apellidos'];
$datos['email'] = $row['email'];
$datos['tipo_promotor'] = $row['tipo_promotor'];
echo json_encode($datos);
}
By the way, with that code, I get this error on the alert:
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 5 of the JSON data
I'm using jQuery 3.6.0 (https://code.jquery.com/jquery-3.6.0.js)
If you're returning JSON, you can only echo the JSON once, not each time through the loop.
If there can only be one row, you don't need the while loop. Just fetch the row and create the JSON.
You also can't echo anything else, so the echo "true"; lines are breaking it.
And your code is wide open to SQL-injection. You should use a prepared statement with a parameter, which I've shown how to do.
$rfc = $_POST['rfc'];
$stmt = $con->prepare("SELECT * FROM instructores WHERE rfc = ?");
$stmt->bind_param("s", $rfc);
$stmt->execute();
$sql_run = $stmt->get_result();
$datos = [];
if($row = mysqli_fetch_array($sql_run)){
$datos['status'] = 'OK';
$datos['nombre'] = $row['nombre'];
$datos['apellidos'] = $row['apellidos'];
$datos['email'] = $row['email'];
$datos['tipo_promotor'] = $row['tipo_promotor'];
}
echo json_encode($datos);
$(document).on("click", "#btnEditarInstructor", function (event) {
event.preventDefault();
let rfc = $(this).attr("value");
$.ajax({
type: "POST",
url: "../utils/ajax/ajax_consulta_instructor.php",
data: {
rfc: rfc,
},
dataType: "json",
success: function (response) {
if (response == true) {
// alert(response);
}
},
error: function (request, status, error) {
var val = request.responseText;
alert("error" + val);
alert(status);
alert(error);
},
});

ajax data[0] is undefined

I use ajax to get the number of rows (COUNT(*)) from a sql query in php.
The JSON return in Firefox-Network tab is:
[{"number":2}],
(the 2 is without quotes).
But in "ajax success" , when i try to get the value (2) from data[0]["number"] or data.length,it returns "undefined".
It works only if i parse JSON as object.
$.ajax({
url: 'queries.php?q=count',
type: 'post',
//data: data,
datatype: 'json',
success: function(data) {
//var dataobject = jQuery.parseJSON(data);
//console.log(dataobject);
//var var2 = dataobject[0].number; ---->THIS WORKS!
//alert(JSON.parse(data).length); ---->THIS WORKS!
//console.log(data.length); ---->Undefined
console.log(typeof data); ---->string
console.log(data[0]["number"]);---->Undefined,i want this to work!!!
}
});
Thw SQL i use in php is :
switch ($_GET["q"]) {
case "count":
$sql = "SELECT count(*) as number from
(SELECT Employees.emp_username, .............
where Employees.emp_username = ? and Year(emp)=2016 and Month(emp)= MONTH(getdate()) ) as rows1 ";
$stmt = sqlsrv_prepare( $conn, $sql , array(&$_SESSION["username"] ));
break;
default: header("Location: index.php"); }
if( !$stmt ) { die( print_r( sqlsrv_errors(), true)); }
sqlsrv_execute($stmt);
$rows = array();
if(sqlsrv_execute($stmt)){
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)){
$rows[] = $row; }
} else{
die( print_r( sqlsrv_errors(), true));
}
print json_encode($rows);
You have to parse the data first, like you did with jQuery.parseJSON(data) or like in the alert JSON.parse(data).
data is a string object, so when you access the element [0] you are getting the first character of the string. In your example: [. This is the first element of the string [{"number":2}].
My suggestion is to apply [0]['number'] to dataobject, so your code should look like this:
$.ajax({
url: 'queries.php?q=count',
type: 'post',
//data: data,
datatype: 'json',
success: function(data) {
var dataobject = jQuery.parseJSON(data);
console.log(dataobject[0]["number"]);
}
Your variable type is string. You must parse it first.
$.ajax({
url: 'queries.php?q=count',
type: 'post',
//data: data,
datatype: 'json',
success: function(data) {
//var dataobject = jQuery.parseJSON(data);
//console.log(dataobject);
//var var2 = dataobject[0].number; ---->THIS WORKS!
//alert(JSON.parse(data).length); ---->THIS WORKS!
//console.log(data.length); ---->Undefined
console.log(typeof data); ---->string
data = JSON.parse(data);
console.log(data[0]["number"]);---->Undefined,i want this to work!!!
}
});

PHP doesn't get JQuery serialize() POST parameters

I want to send a form with JQuery $.ajax, but I have a problem. It's seems that PHP cannot get serialized $_POST. It's weird because the variable elementiPost is not empty, indeed if I do console.log(parametriPost) the console show me the right content.
The weirdest thing is that PHP get parameters that I append manually to parametriPost ($_POST['data_r']) but not those of $(this).serialize()!
If I put manually a number in $ore it works fine, so the problem is not the query.
Thank you.
Here's the code:
JQuery
$('form').submit(function(e) {
e.preventDefault();
var formId = $(this).attr('id');
var data = area_get_row_date(formId);
var parametriPost = $(this).serialize() + '&data_r=' + data;
$.ajax({
url: 'insert_db.php',
method: 'POST',
async: false,
data: parametriPost,
success: function() {
// Success code
},
error: function(xhr, status, error) {
alert("Errore!");
}
});
});
PHP (insert_db.php)
$data = str_replace('_', '.', $_POST['data_r']);
$ore = $_POST['orelavorateore_2_07_2015'];
$sql = "INSERT INTO ore_lav
VALUES (NULL, 134, 4,STR_TO_DATE('" . $data . "', '%d.%m.%Y'), " . $ore . ", 1, 1)";
$results = api_store_result(api_mysql_query($sql));
This is what parametriPost contains:
lavorati_prenotati=L&periodointegrazione_3_07_2015=on&orelavoratechf_3_07_2015=&orelavorateore_3_07_2015=a&extra_field1_orelavoratechf_3_07_2015=&extra_field1_orelavorateore_3_07_2015=&extra_field2_orelavoratechf_3_07_2015=&extra_field2_orelavorateore_3_07_2015=&orenonlavoratechf_3_07_2015=&orenonlavorateore_3_07_2015=&orenonlavoratetipologia_3_07_2015=L&extra_field1_orenonlavoratechf_3_07_2015=&extra_field1_orenonlavorateore_3_07_2015=&extra_field1_orenonlavoratetipologia_3_07_2015=L&extra_field2_orenonlavoratechf_3_07_2015=&extra_field2_orenonlavorateore_3_07_2015=&extra_field2_orenonlavoratetipologia_3_07_2015=L&orenonpagateore_3_07_2015=&orenonpagatetipologia_3_07_2015=L&extra_field1_orenonpagateore_3_07_2015=&extra_field1_orenonpagatetipologia_3_07_2015=L&extra_field2_orenonpagateore_3_07_2015=&extra_field2_orenonpagatetipologia_3_07_2015=L&orelavoratechf_3_07_2015=&orelavorateore_3_07_2015=&data_r=3_07_2015
You can use this snippet to convert your form data into JSON format :
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$("form").submit(function( event ) {
event.preventDefault();
//convert form data to JSON
var params = $(this).serializeObject();
//add a 'data_r' field with some data to our JSON
params.data_r = 'sample data';
$.ajax({
url: 'app.php',
type: 'POST',
data: JSON.stringify(params),
})
.done(function(data) {
console.log(data);
});
});
and on the PHP side :
<?php
$data = json_decode(file_get_contents('php://input'), false);
print_r($data->data_r);
?>
Now $data is an object and you can access to a specific field :
$data->data_r

how to return an array in AJAX call in php

I have a form that has a select option , So I am trying to update the form/table with some content from database when I select a type in the select option ,
SO for that I did an ajax call something like this.
$("#selectPlantilla").on("change",function(){
var descripcion = $(this).val();
//alert(descripcion);
var url="http://index.php";
var posting = $.post(url, {
im_descripcion: descripcion,
}).done(function (data) {
alert(data);
});
});
And then I validated the call in php on the same inde.php page like this
if(isset($_POST['im_descripcion']))
{
$db = new dataBase();
$result = $db->execute("SELECT * FROM `tableNmae` WHERE `descripcion` = '".trim($_POST['im_descripcion'])."'");
$result = mysql_fetch_array($result);
print_r($result);
}
The problem I am facing is in the alert window it return the whole page instead of just the $result that I have printed , So can any one help me out how I can channelize it properly , I have use the values from the array $result to update in the form using JQuery .
Thanks in Advance
For returning PHP array data in Ajax, JSON will make your life the simplest.
$result = mysql_fetch_array($result);
echo(json_encode($result));
This will return the array in a format that is easily usable by JavaScript. Try this to see its content:
alert(JSON.stringify(data));
With JSON, you should be able to fetch data or iterate through it in JavaScript
Try this
In Javascript
<script type="text/javascript">
var $ =jQuery.noConflict();
$(document).ready(function(){
$('.dropdown_class').on('change', function() {
var m_val = this.value;
var datastring = "im_descripcion="+m_val;
$.ajax({
type: "POST",
url: "lunchbox_planner.php",
data: datastring,
cache: false,
success: function(result) {
var v = $.parseJSON(result);
var l = v.length;
for(var i=0;i<l;i++){
var sh_d = "<div class='coco3'>"+v[i]+"</div>";
$('.mon_tea').append(sh_d);
}
}
});
});
});
</script>
<div class="mon_tea">
In PHP
<?php
if(isset($_POST['im_descripcion'])) {
$db = new dataBase();
$result = $db->execute("SELECT * FROM `tableNmae` WHERE `descripcion` = '".trim($_POST['im_descripcion'])."'");
while($row_sh = mysql_fetch_array($result)){
$all_incr[] = $row_sh['col_name'];
}
echo json_encode($all_incr);
}
?>

Submit and load with ajax json

index.html:
Function drawChart() {
var jsonData = $.ajax({
url: "server.php",
dataType: "json",
async: false
}).responseText;
var obj = jQuery.parseJSON(jsonData);
var data = google.visualization.arrayToDataTable(obj);
var options = {
title: 'Number of visitors / <?php echo $unit; ?>'
};
var chart = new google.visualization.BarChart(
document.getElementById('chart_div'));
chart.draw(data, options);
}
}
server.php:
$SQLString = "SELECT (...)'".$_POST['value']."' (...)
$result = mysql_query($SQLString);
(...)
$data[$i] = array(...)
echo json_encode($data);
So, index.html get data from server.php right?
Can I send some values to server.php which are important to do the query before index.html do the jsonData...etc? How?
Thanks :)
Example of a query parameter:
var jsonData = $.ajax({
url: "server.php?someQuery=" + query,
dataType: "json",
async: false
}).responseText;
You can send using post method via ajax. Here is a JQuery example:
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
http://api.jquery.com/jQuery.ajax/
you can use a library that will do it automatically for you, using phery http://phery-php-ajax.net, in your case it would be:
the event phery:json will deal with the JSON sent from the server
var remote = phery.remote('data', {'argument': 'you want to send'}, {'target':'server.php'}, false);
remote.bind('phery:json', function(event, obj){
var data = google.visualization.arrayToDataTable(obj);
var options = {
title: 'Number of visitors / <?php echo $unit; ?>'
};
var chart = new google.visualization.BarChart(
document.getElementById('chart_div'));
chart.draw(data, options);
});
remote.phery('remote'); // call the remote AJAX function
in your server.php
function data($data){
$r = new PheryResponse;
// $data['argument'] will have 'you want to send'
$SQLString = "SELECT (...)'".$_POST['value']."' (...)"
$result = mysql_query($SQLString);
(...);
$data[$i] = array(...);
return $r->json($data);
}
Phery::instance()->set(array(
'data' => 'data'
))->process();

Categories