Ajax post not passing data to php? - php

So I'm having trouble with passing data using ajax post to php
Here is my jquery :
$('#kodeobat').on('change',function(){
var kodeobat = $(this).val();
if (kodeobat = ""){
$("#hargaobat").val("");
} else {
$.ajax({
type: "POST",
data: { 'kodeobat': kodeobat },
dataType: "json",
url: "getdata.php",
success: function(json) {
$("#hargaobat").val(json["hargaobat"]);
}
});
}
});
and here is the php file:
$kodeobat = $_POST['kodeobat'];
$stmt = $db_con->prepare("SELECT kodeobat, hargaobat FROM Obat WHERE kodeobat='".$kodeobat."'");
$stmt->execute();
while($row=$stmt->fetchAll(PDO::FETCH_ASSOC))
{
if($kodeobat == $row['kodeobat']){
echo json_encode($row);
}
}
and it results : Notice: Undefined index: kodeobat in .../getdata.php on line 4 which is this line $kodeobat = $_POST['kodeobat'];
Is there something wrong with the code? Thank youuu :)

$('#kodeobat').on('change',function(){
var kodeobat = $(this).val();
if (kodeobat == ""){
$("#hargaobat").val("");
} else {
$.ajax({
type: "POST",
data: { 'kodeobat': kodeobat },
dataType: "json",
url: "getdata.php",
success: function(json) {
$("#hargaobat").val(json["hargaobat"]);
}
});
}
});
Notice if (kodeobat == "")

Try sending your JSON as JSON by using PHP's header() function:
header("Content-Type: application/json", true);
look at this

If you are unaware of what type of value you would get in response here is a try..
$kodeobat = $_POST['kodeobat'];
if(empty($kodeobat)) {
echo("Value is empty");
} else if(is_array($kodeobat)) {
$i = count($kodeobat); //If the value is array iterate it
for($j = 0; $j < $i; $j++) {
echo($kodeobat[$i] . " ");
}
} else if(is_object($kodeobat)){
$json = json_decode($_POST,true); //if it is a json value decode it
$kodeobat_new = $json['kodeobat'];
}

Related

Data missing when sent via AJAX

I want to send two values to my PHP script that is being called from an AJAX request. Somehow my data is not being passed to the PHP script.
Maybe I am doing something wrong somewhere. Can I have some insight?
$(function() {
$(".delbutton").click(function() {
var viewed_comments = $("#viewed_comments").val();
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
var comments = 'comm=' + viewed_comments;
var tr = $(this).closest('tr');
if (confirm("Are you sure to mark this as viewed?")) {
$.ajax({
type : "POST",
url : "update_entry.php",
dataType: "json",
data: {info:info, comments:comments },
success : function(response) {
if(response=="updation success"){
console.log('inside');
}
}
});
}
return false;
});
});
And my PHP where the AJAX request is going,
$id = $_POST['id'];
$viewed_comments = $_POST['comm'];
$level_code = $_SESSION['level_code'];
$action = 'view';
$viewed_date = date("Y-m-d");
$viewed_by = $_SESSION['session_admin_id'] ;
if($action == 'view')
{
$viewed_date = date('Y-m-d h:i:s');
$nots = $db->idToField("tbl_table","notes",$id);
if ($nots == "")
{
$date_string = "last viewed on|".$viewed_date."|" ;
}
else {
$date_string = $nots."last viewed on|".$viewed_date."|" ;
}
$fnc->update_is_viewed_for("tbl_table",$id, "$viewed_date", $viewed_by);
$notes_data = array("notes"=>$date_string,"viewed_comments"=>$viewed_comments);
$db->query_update("tbl_table", $notes_data, "id=$id");
}
if($db->query_update("tbl_table", $notes_data, "id=$id")){
http_response_code();
echo json_encode('updation success');
}else{
http_response_code(204);
}
Isn't it a name thing? You send two POST variables:
data: {
info: info,
comments: comments
},
but you retrieve them with different names:
$id = $_POST['id'];
$viewed_comments = $_POST['comm'];
What do you get if you var_dump($_POST);?
Use seriliaze form values it will solve your data missing problem, change #frm to your form id
$(document).ready(function(){
$('#frm').submit(function(event){
event.preventDefault();
var formValues = $(this).serialize();
$.ajax({
url:"update_entry.php",
method:"POST",
data:formValues,
dataType:"JSON",
success:function(data){
if (data == 'updation success') {
console.log('success');
}
}
});
});
});

echo query on ajax response

I'm trying to send a php form data via AJAX (without the refresh) and display data in new form. I echo query but it didnt work. On AJAX response it shows me getReportAj form on call.The code goes like this:
Javascript
function getReport()
{
var dataString = "grNo=" +$(".grNo").val();
$.ajax({
type: "GET",
url: "getReportAj.php",
data: dataString,
success:function(data)
{
$('#result').html(data);
}
});
}
getReportAj.php
<?php
include "include/config.inc.php";
if(!isset($_SESSION['s_activName']) && !isset($_SESSION['s_userType']) || isset($_SESSION['s_userType']) && $_SESSION['s_userType'] == 'Student') {
$_SESSION['s_urlRedirectDir'] = $_SERVER['REQUEST_URI'];
header("Location:checkLogin.php");
}
else {
if(isset($_REQUEST['submit'])) {
$selectReport = "SELECT * from gradeterm1
WHERE studentId = ".$_POST['studentId']."
AND termValue = 1
LEFT JOIN studentmaster ON studentmaster.studentId = gradeterm1.studentId";
$selectReportRes = mysql_query($selectReport);
if($reportRow = mysql_fetch_array($selectReportRes)); {
$eReadingPro = $reportRow['eReadingPro'];
$eReadingFlu = $reportRow['eReadingFlu'];
$eReadingCom = $reportRow['eReadingCom'];
$eWritingCre = $reportRow['eWritingCre'];
$eWritingHan = $reportRow['eWritingHan'];
$eWritingGra = $reportRow['eWritingGra'];
$eWritingSpe = $reportRow['eWritingSpe'];
$eWritingVoc = $reportRow['eWritingVoc'];
$ewSpeakinCon = $reportRow['ewSpeakinCon'];
$ewSpeakinRec = $reportRow['ewSpeakinRec'];
$ewSpeakinCla = $reportRow['ewSpeakinCla'];
$eListingComp = $reportRow['eListingComp'];
$eListingCon = $reportRow['eListingCon'];
$extraReading = $reportRow['extraReading'];
$activityPro = $reportRow['activityPro'];
$hiReadingPro = $reportRow['hiReadingPro'];
$hiReadingFlu = $reportRow['hiReadingFlu'];
$hiReadingCom = $reportRow['hiReadingCom'];
$hiWritingCre = $reportRow['hiWritingCre'];
$hiWritingHan = $reportRow['hiWritingHan'];
$hiWritingGra = $reportRow['hiWritingGra'];
$hiWritingSpe = $reportRow['hiWritingSpe'];
$hiWritingVoc = $reportRow['hiWritingVoc'];
$hiwSpeakinCon = $reportRow['hiwSpeakinCon'];
}
}
}
include("./bottom.php");
$smarty->display('getReportAj.tpl');
?>
<script>
function getReport()
{
var dataString = "grNo=" +$(".grNo").val();
$.ajax({
type: "GET",
url: "getReportAj.php",
data: dataString,
success:function(data)
{
$('#result').html(data);
console.log(data);
}
});
}
</script>
in success event.. put the console.log(data) then run the script and check in console.

jquery.ajax json wrong?

hey i have a problem submitting my data via jquery and back:
$.ajax({
url: "checkAvailability.php",
type: 'POST',
data : {data:JSON.stringify(data)},
success: function(data) {
if (data.result == 0) {
alert("0")
}
if(data.result == 1) {
alert("1")
}
}
});
so,
ONE of those if-conditions must be true, because of:
checkAvailability.php:
if(isset($_POST['data'])) {
define('SECURE', true);
include "storescripts/connect_to_mysql.php";
require 'AvailabilityChecker.php';
$config = array(etc..);
$availabilityChecker = new AvailabilityChecker($config);
$data = $_POST['data'];
$data = json_decode($data,true);
preg_match( '/(\d+(\.\d+)?)/', $data['x'] , $m);
$x = $m[0];
if($availabilityChecker->check_availability($x)) {
echo json_encode(array("error" => "is ok", "result"=>1));
} else {
echo json_encode(array("error" => "not ok", "result"=>0));
}
}
data.result have to be 1 OR 0.
anybody can tell me why there is no alert-message? greetings!
UPDATE:
$.ajax({
url: "checkAvailability.php",
type: 'POST',
data : {data:JSON.stringify(data)},
success: function(data) {
if (data.result == 0) {
alert("0")
} else { alert("fail-1") }
if(data.result == 1) {
alert("1")
} else { alert("fail-2") }
}
});
now i get first the fail-1 alert and than the fail-2 alert, so both if-conditions are false, why?
You need to specify the dataType, otherwise jquery will instead try to guess what you are trying to do. In this case it is incorrectly guessing text/html rather than application/json.
$.ajax({
url: "checkAvailability.php",
type: 'POST',
dataType: 'json',
data : {data:JSON.stringify(data)},
success: function(data) {
if (data.result == 0) {
alert("0")
} else { alert("fail-1") }
if(data.result == 1) {
alert("1")
} else { alert("fail-2") }
}
});
You should also properly set the content-type header in php, before you echo the json.
header('Content-type: application/json');
You can get away with doing either-or, but i'd suggest doing both.
a solution can be
success: function(d) {
data = jQuery.parseJSON(d);
if (data.result == 0) {
alert("0")
}
if(data.result == 1) {
alert("1")
}
}
this becouse $.ajax will no decode the result text from the page for you.
what the php code is doin in fact is to print a json string to the stream.
Note that the the output passed to success can be any sort of text (also xml code on simply text)
You need to set the correct content type header in your php file:
header('Content-Type: application/json');
//snip
echo json_encode(array("error" => "is ok", "result"=>1));

How get AJAX to Post JSON data into div

I'm new Jquery and AJAX and I've really been struggling with the syntax I've been trying to use other tutorials as reference but nothing seems to work. I feel I have the right idea but syntax is wrong somewhere please help.
Here is the Ajax side
var var_numdatacheck = <?php echo $datacheck; ?>;
var var_numcheck = parseInt(var_numdatacheck);
function activitycheck(){
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck},
dataType: "json",
success: function(data) {
var json = eval('(' + data + ')');
$('#datacheck').html(json['0']);
var var_numcheck = parseInt(msg);
//setTimeout('activitycheck()',1000)},
error:function(msg) {
console.log(msg);
}
});
}
$(document).ready(function() {
activitycheck();
});
Here is the php the AJAX calls
<?php
require "dbc.php";
$function = $_POST['function'];
$datacheck = $_POST['datacheck'];
$search="SELECT * FROM Feedtest ORDER BY id DESC";
$request = mysql_query($search);
$update= mysql_fetch_array($request);
$updateid = $update['id'];
$updatecheck = mysql_num_rows($request);
$data = array();
if ($function == $datacheck){
echo $updatecheck;
echo $datacheck;
}
if ($function == "3test" && $updatecheck > $datacheck ) {
$updatesearch="SELECT * FROM Feedtest WHERE id = '$updateid' ORDER BY id DESC";
$updatequery = mysql_query($updatesearch);
$data['id'] = $updateid;
while ($row = mysql_fetch_array($updatequery))
{
?>
<?php $data[]= $row['First Name']; ?>
<?php
}
echo json_encode($data);
}
?>
</div>
</ul>
first of all ,always use JSON.parse(data) instead of eval.It is considereda a good practice.
second thing is always try to debug your code by checking it in console or alerting.In your context,this is what is happening-:
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck},
dataType: "json",
success: function(data) {
var data = eval('(' + data + ')');
console.log("myData"+data)//debugging.check the pattern so that you can acces it the way you want!!!
for(var i=0;i< data.length;i++)
{
alldata += "<li>"+data[i][0]+"<li><hr>";
}
$('#datacheck').html(alldata);
});
}
For JSON.parse:
success: function(data) {
var data = JSON.parse(data);
console.log("myData"+data)//debugging.check the pattern so that you can acces it the way you want!!!
for(var i in data)
{
alldata += "<li>"+data[i].First Name+"<li><hr>";
}
$('#datacheck').html(alldata);
});

DataType JSON doesn't work with php

Here is my HTML
<input x-webkit-speech id="mike" name="string" style="position: relative;" disabled lang="ru" />
Then when the field is changes,
This function executes
$(document).ready(function(){
$('#mike').bind('webkitspeechchange',function()
{
a= $(this).val();
recognizeAjax(a);
}) ;
});
function recognizeAjax(string) {
var postData ="string="+string;
$.ajax({
type: "POST",
dataType: "json",
data: postData,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
url: 'restURL.php',
success: function(data) {
// 'data' is a JSON object which we can access directly.
// Evaluate the data.success member and do something appropriate...
if (data.success == true){
alert(data.message);
}
else{
alert(data.message+'hy');
}
}
});
And here is my PHP (please don't say anything about the way i connect to DB it doesn't metter right now)
<?php header('Content-type: application/json; charset=utf-8');
error_reporting(E_ALL);
ini_set('display_errors', true);
// Here's the argument from the client.
$string = $_POST['www'];
$quest=1;
$con=mysql_connect("localhost", "******", "*********") or die(mysql_error());
mysql_select_db("vocabulary", $con) or die(mysql_error());
mysql_set_charset('utf8', $con);
$sql="SELECT * FROM `text` WHERE event_name = 'taxi' AND quest_id = '".$quest."'";
$result = mysql_query($sql);
mysql_close($con);
while($row = mysql_fetch_array($result))
{
if ($string == htmlspecialchars($row['phrase']))
{
$data = array('success'=> true,'message'=>$row['phrase']);
// JSON encode and send back to the server
header("Content-Type: application/json", true);
echo json_encode($data);
exit;
break;
} else {
// Set up associative array
$data = array('success'=> false,'message'=>'aint no sunshine');
header("Content-Type: application/json", true);
echo json_encode($data);
exit;
break;
}
}
When i change the dataType to "text" in the javasript function - i receive an alert with 'undifiend'
But when chenge it to 'json'.. i receive nothing (chrome debuger see nothing)
I set up all encodings to this article http://kunststube.net/frontback/
And i checked it with simple POST requests - it works perfect.
The problem with json.
Any suggestions?
Thanks
Just remove the datatype="json" bit and change the data bit to data: { "string": string }
After that try a print_r(json_decode($_POST['string']));. I'm quite sure that will get you your data.
And indeed remove your beforeSend callback.
I think the prob is the code var postData ="string="+string;
jQuery expects this to be a proper JSON Object.
Next: $string = $_POST['www']; takes a parameter named "www" from your post request, but the name above is "string" (at least).
Try either (!) this:
var getData ="www="+string;
$.ajax({
type: "POST",
dataType: "json",
data: null,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
url: 'restURL.php?' + getData,
and server:
$string = $_GET['www'];
or this (php)
$string = $_POST['string'];
$stringData = json_decode($string);
// catch any errors ....
$quest=$stringData[....whatever index that is...];

Categories