Why can't I access the JSon data? - php

I'm trying to get the count of a variable using ajax but it keeps printing fail everytime
here is the php file that works perfectly when I test it
<?php
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($conn,"bdpfe") or die ("no database");
$rech=$_GET['q'];
$sql=mysqli_query($conn,"select count(id_com) as nbr from commentaire where id_pub like '".$rech."' ");
$response = array();
$nbrs = array();
$result=$sql;
while($row=mysqli_fetch_array($result))
{
$nbr=$row['nbr'];
$nbrs[] = array('nbr'=>$nbr);
}
$response['nbrs'] = $nbrs;
echo "mycallbackcom(".json_encode($response).")";
?>
and here is the ajax call using jsonp
(function getnbr() {
$.ajax({
type : 'GET',
url : 'http://127.0.0.1:800/test/count_com.php?callback=?&q='+$('#idpub').val() ,
jsonpCallback: 'mycallbackcom',
dataType: 'jsonp',
contentType: "application/json",
success: function (data) {
alert("succes");
},
error: function () {
alert("fail");
}
});
})(jQuery);
and the callback function is empty for now:
function mycallbackcom()
{}
it keeps printing fail every time.

Try only returning the JSON. You have specified this as your expected return dataType.
echo json_encode($response);
Then handle the response:
(function getnbr() {
$.ajax({
type : 'GET',
url : 'http://127.0.0.1:800/test/count_com.php?callback=?&q='+$('#idpub').val() ,
jsonpCallback: 'mycallbackcom',
dataType: 'jsonp',
contentType: "application/json",
success: function (data) {
mycallbackcom(data)
},
error: function () {
alert("fail");
}
});
});

You need to parse the $_GET variable..
$data = json_decode($_GET['q']);
function mycallback($data) {
//Do something
}
return mycallback($data);

Related

JSON responce populating undefine in dropdown

JSON response is not populating in dropdown perhap query gat the result perfectly.
alert the success function i.e
alert(result.data);--[object object]
here is my html code
Jquery
function fillTransferJobPositionAreaDropDown( job_type_id,province_id,region_id,district_id,tehsil_id,uc_id, area_id) {
var loadDDUrl = baseApiUrl + "Employee/all_new_job_positions_area/"+job_type_id+"/"+province_id+"/"+region_id+"/"+district_id+"/"+tehsil_id+"/"+uc_id+"/"+area_id;
console.log(loadDDUrl);
debugger;
newJobPositionIDFld.empty();
newJobPositionIDFld.append($("<option />").val("0").text("Select New Job Position"));
newJobPositionIDFld.select2('val', '0');
var url = loadDDUrl;
$.ajax({
url: url,
accepts: 'application/json',
cache: false,
type : 'GET',
dataType: 'jsonp',
success: function (result) {
alert(result.data);
console.log(result.data);
// Handle the complete event
if(result.data == null) return;
$.each(result.data, function () {
newJobPositionIDFld.append($("<option />").val(this.job_position_id).text(this.job_position_id+'-'+this.job_name));
});
}
});
}//End Ajax call
PHP
$this->db->select('jp.job_position_id,jp.jobposition_title as job_name');
$this->db->from('job_positions jp');
$this->db->where('jp.job_type_id', $job_type_id);
$this->db->where('jp.province_id', $province_id);
$this->db->where('jp.region_id', $region_id);
$this->db->where('jp.district_id', $district_id);
$this->db->where('jp.tehsil_id', $tehsil_id);
$this->db->where('jp.uc_id', $uc_id);
$this->db->where('jp.area_id', $area_id);
$this->db->get()->row_array();
Your query returns a object, not an array of objects, so remove the loop:
success: function (result) {
newJobPositionIDFld.append($("<option/>").val(result.data.job_position_id).text(result.data.job_position_id+'-'+result.data.job_name));
}

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

Issue with insert into sql query

$.ajax({
url: 'http://localhost/xampp/htdocs/ajax.php',
contentType: 'application/json',
type: 'post',
data: {
//score is a new variable and count2 is an integer variable which i want to send it to the database
"score":"count2"
},
success: function () {
alert("ok");
},
error: function () {
alert("error");
}
});
The above code alerts me "ok".
function connect(){
$connect = mysql_connect('localhost','root','') or die("ERROR");
$connect2Database = mysql_select_db('fypdb', $connect);
return $connect;
}
if(isset($_POST)){
if($connect = connect()){
$query = "INSERT INTO fypdbtable (score) VALUES ('".$_POST['score']."');";
$completeQuery = mysql_query($query, $connect);
}
}
I think the problem is on "insert into" query because in ajax.php prompts me Notice: Undefined index: score in C:\xampp\htdocs\xampp\htdocs\ajax.php on line 14 where it is the query line
Any help would be appreciate
Problem here is in your ajax code. You are using contentType: 'application/json' but you try to acces
param in your php script with $_POST, but post works with form encoded content types.
So you can remove contentType from your ajax call and it will use default which is
contentType:'application/x-www-form-urlencoded; charset=UTF-8'
EDIT
Make your ajax code like that:
$.ajax({
url: 'http://localhost/xampp/htdocs/ajax.php',
type: 'post',
data: {
"score":"count2"
},
success: function () {
alert("ok");
},
error: function () {
alert("error");
}
});
The "error" message tells you, that $_POST['score'] is not defined. But thats just a warning. If you want to know if your variable is set, use isset() function or turn off warnings in the configuration.

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

jQuery json from PHP result

I have this jQuery script
var dataString = "class_id="+class_id;
$.ajax({
type: "POST",
url: "page.php",
data: dataString,
success: function (msg) {
//stuck here
},
error: function () {
showNotification("error", "Could not process at this time, try again later."); //this is a function created by me (which works fine so I just left the code in here)
}
});
my PHP output is something like this
echo '{status:1,message:"Success"}';
or
echo '{status:0,message:"Failure"}';
what I am trying to do in jQuery success: function(...) part is check if status is 0 or 1 and then show the message.
I tried to do is
success: function(text) {
if(parseInt(text.status) == 1) {
alert(text.message); // this is the success, the status is 1
} else {
alert(text.message); // this is the failure since the status is not 1
}
}
which didn't work, it was only outputing the else statement, even though the status was 1
Your PHP is generating invalid JSON, and shows no sign of setting an appropriate content type header to tell the browser to treat it as JSON in the first place. So first, fix the PHP:
header('application/json');
echo json_encode(Array("status" => 1, "message" => "Success"));
Then:
success: function (msg) {
alert(msg.message)
},
You can also use
PHP
echo json_encode(Array("status" => 1, "message" => "Success"));
JS
Inside your call back function use
success: function (msg) {
$.parseJSON(msg);
alert(msg.message);
}
The parseJSON will convert the json string returned/echoed by PHP in to json object.
Try something like below,
$.ajax({
type: "POST",
url: "page.php",
data: dataString,
dataType: 'json',
success: function (msg) {
if (msg.status == 0) {
alert("Success " + msg.message);
} else if (msg.status == 1) {
alert("Error " + msg.message);
}
},
error: function () {
showNotification("error", "Could not process at this time, try again later."); //this is a function created by me (which works fine so I just left the code in here)
}
});
If you don't specify in $.ajax the type 'json' data passed to response handler is treated as string. While if you specify 'json' dataType parameter you can use:
msg.status
and
msg.message
As a hint i suggest in php to use the json_encode function to generate json output.

Categories