meekro db, json and ajax - php

I am using meekro db to fetch data from database and when I return object as json format then ajax call goes to error
$(".cat").click(function() {
var value = $(this).attr('id');
$.ajax({
url:"/psl/ajax/get_words.php",
method:"post",
dataType: "json",
data:{ id: value },
success:function(response) // success part does not execute
{
var data = JSON.parse(response);
alert( data );
},
error:function (msg) { // error part executes every time
alert('error');
}
});
});
And the code which is being used to fetch data from database get_words.php
<?php
require_once '../inc/initDb.php';
$id = $_POST['id'];
$words = DB::query("select * from words where category_id = '$id'");
if (DB::count() > 0)
{
echo json_encode($words);
}

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);
},
});

Return php array to ajax not working

I am running a query to database which fetch a row and i want to return it as array which can accessed as array['min'], array['max'] etc. if i echo it with specific index, it shows the value correctly in ajax but i am unable to pass complete row through it to the ajax file.
PHP file:
<?php
// Database logic here
$calid = reset($_POST);
require '../incs/connect.php';
$sql=mysqli_query($con, "SELECT * FROM calcus_sets WHERE sets_id=$calid ");
WHILE($row=mysqli_fetch_array($sql))
{
echo $row['min']; break;
}
mysqli_close($con);
?>
JS file:
function DB_Fetecher(ops){
$.ajax({
type: "POST",
data: {ops},
url: "calcus_es1-fetcher.php",
success: function(res)
{
// alert( res );
alert(res);
}
});
}
This code get right value from mysql but i want to pass full row to ajax and then use each index in ajax itself to put into textboxes.
You can pass array by:
<?php
// Database logic here
$calid = reset($_POST);
require '../incs/connect.php';
$sql=mysqli_query($con, "SELECT * FROM calcus_sets WHERE sets_id=$calid ");
$result = array();
WHILE($row=mysqli_fetch_array($sql))
{
$result[] = array( "min" => $row['min'], "max" => $row['max'] );
}
mysqli_close($con);
echo json_encode( $result );
?>
On your js, make sure to specify dataType:"json",
function DB_Fetecher(ops){
$.ajax({
type: "POST",
data: {ops},
url: "calcus_es1-fetcher.php",
dataType:"json",
success: function(res)
{
// alert( res );
console.log(res);
}
});
}
Note: It is advisable to use console.log(res); instead of alert() on debugging.

codeigniter ajax getting the value of json from model

I am having trouble how to get the returned json from my controller to my view. The passing of the data is already okay, but i dont know how to decode or get the specific values of the json encoded.
All i want is to store my specific values of json to a variable for further use. Something like this :
$project_name = val.($json['project_name');
Here is my code from my view :
function showprojectdetails(projectSelected) {
var studentId = null;
$.ajax({
url : "<?php echo site_url('manager/projects/ProjDetails/')?>/" + projectSelected,
type: "GET",
dataType: "JSON",
success: function(data) {
$json = json_decode(data, true);
alert($json['project_code'];);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});
}
my Controller :
function ProjDetails($project_title) {
$data = $this->project->getProjDetails($project_title);
echo json_encode($data);
}
My model :
function getProjDetails($project_title) {
$this->db->from('project');
$query = $this->db->query('SELECT * from project where project_code = "'.$project_title.'" ');
return $query->row();
}
You dont need to decode the value in js. json_encode would convert array into json string. So what you get in view is already json. You simply needs to use it.
This will show you the json string in console.
console.log(data)
use
data['project_code']
You should combine PHP function
json_encode($your_json_string);
with JS
JSON.parse(response);
As in:
function showprojectdetails(projectSelected) {
var studentId = null;
$.ajax({
url : "<?php echo site_url('manager/projects/ProjDetails/')?>/" + projectSelected,
type: "GET",
dataType: "JSON",
success: function(data) {
var json = JSON.parse(data);
//do the magic you wanted to do like alert(json);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});
}

How to handle json response from php?

I'm sending a ajax request to update database records, it test it using html form, its working fine, but when i tried to send ajax request its working, but the response I received is always null. where as on html form its show correct response. I'm using xampp on Windows OS. Kindly guide me in right direction.
<?php
header('Content-type: application/json');
$prov= $_POST['prov'];
$dsn = 'mysql:dbname=db;host=localhost';
$myPDO = new PDO($dsn, 'admin', '1234');
$selectSql = "SELECT abcd FROM xyz WHERE prov='".mysql_real_escape_string($prov)."'";
$selectResult = $myPDO->query($selectSql);
$row = $selectResult->fetch();
$incr=intval($row['votecount'])+1;
$updateSql = "UPDATE vote SET lmno='".$incr."' WHERE prov='".mysql_real_escape_string($prov)."'";
$updateResult = $myPDO->query($updateSql);
if($updateResult !== False)
{
echo json_encode("Done!");
}
else
{
echo json_encode("Try Again!");
}
?>
function increase(id)
{
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
success: function (response) {
},
complete: function (response) {
var obj = jQuery.parseJSON(response);
alert(obj);
}
});
};
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
dataType: 'json',
success: function (response) {
// you should recieve your responce data here
var obj = jQuery.parseJSON(response);
alert(obj);
},
complete: function (response) {
//complete() is called always when the request is complete, no matter the outcome so you should avoid to recieve data in this function
var obj = jQuery.parseJSON(response.responseText);
alert(obj);
}
});
complete and the success function get different data passed in. success gets only the data, complete the whole XMLHttpRequest
First off, in your ajax request, you'll want to set dataType to json to ensure jQuery understands it is receiving json.
Secondly, complete is not passed the data from the ajax request, only success is.
Here is a full working example I put together, which I know works:
test.php (call this page in your web browser)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Define the javascript function
function increase(id) {
var post_data = {
'prov': id
}
$.ajax({
'type': 'POST',
'url': 'ajax.php',
'data': post_data,
'dataType': 'json',
'success': function (response, status, jQueryXmlHttpRequest) {
alert('success called for ID ' + id + ', here is the response:');
alert(response);
},
'complete': function(jQueryXmlHttpRequest, status) {
alert('complete called');
}
});
}
// Call the function
increase(1); // Simulate an id which exists
increase(2); // Simulate an id which doesn't exist
</script>
ajax.php
<?php
$id = $_REQUEST['prov'];
if($id == '1') {
$response = 'Done!';
} else {
$response = 'Try again!';
}
print json_encode($response);

post data by ajax jquery

i want to save data in database by a button click.here is my code,in Firefox it do not work it show empty alert and data do not saved in table.
$("#Save").click(function () {
var price = $("#price").val();
var agent_1_id= $("#agent_1_id").val();
var type = $("#type").val();
$.post("ajax_files/myDeals.php",
{
price: price,
agent_1_id: agent_1_id,type:type
},
function(data) {
alert(data);
});
});
click event fires and this function calls. Here is code on myDeals.php to save in table..
$price = $_REQUEST['price'];
$agent_1_id = $_REQUEST['agent_1_id'];
$type = $_REQUEST['type'];
mysql_query('insert query here');
echo "Saved Successfully ";//this is not alerted?
Try the sample sending the data as an object:
function end_incident() {
$.ajax({
type: "POST",
url: "http://www.example.co.uk/erc/end_incident.php",
data: { name: "Daniel", phone: "01234123456" },
success: function(msg){
alert('Success!');
}
});
};

Categories