Php variable not getting incremented in jquery - php

I want to increment $j in $.each function of jquery. But $j is not getting incremented. What may be the reason. My code is as follows:
$.ajax
({
url : "test.php",
type : "post",
data : {
"categoryIds" : categoryIds
},
dataType : "json",
success : function(resp){
var html = "";
var i = 1;
<?php $j = 1; ?>
$.each(resp,function(key,questions ){
<?php
$j = 1;
$testdataIndex = "answer_".$j;
?>
var test = "<?php echo $testdataIndex?>";
alert(test);
var res = "<?php echo $_SESSION['testdata'][$testdataIndex]; ?> ";
var index = "<?php echo $j++;?>";
alert(index);
});
});
Each time test prints 'answer_1' and index as 1

Fixed session issue :
$.ajax
({
url : "test.php",
type : "post",
data : {
"categoryIds" : categoryIds
},
dataType : "json",
success : function(resp){
var html = "";
var i = 1;
<?php $j = 1; ?>
$.each(resp,function(key,questions ){
var testdataIndex = "answer_" + i ;
var filename = "getsession.php?sessionName="+testdataIndex;
$.get(filename, function (data)
{
sessionValues = data;
$("#"+testdataIndex).text(sessionValues);
});//get
html += '<textarea class="form-control answer" rows = "5" style="width:127%;" id="answer_'+i+'" name="answer_'+i+'" required="required"></textarea>';
i++;
});//each
});//ajax
getsession.php
<?php
session_start();
$sessionName = $_GET['sessionName'];
print ($_SESSION['testdata'][$sessionName]);
?>
I have answered my question for other who face same problem.

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

Ajax post not passing data to 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'];
}

Get values from array of data from jquery data ajax object

Hi I am trying to get attribute values from array of elements...
JQuery
function sendM(){
$.ajax(
{
type:'POST',
url:'../business_logic/send_chat_user.php', //URL
data:{ u_id: <?php echo $_SESSION['uid']?>,c_id }, //Data
beforeSend:function(){},
success:function(data,status){ //Data,status
var item = $(data).hide().slideDown("slow");
var el = $.parseHTML(data);
var e = $("a", el).attr ("value"); // This only gives me single value.. I want an array
$('#msg').append(item);
}
});
}
send_chat_user.php file
echo '<ul class="nav nav-list">';
for($i = 0 ; $i < count($list) ; $i++)
{
echo '<li>';
echo '<div class="user_list">';
echo '<img src="../images/default_profile_pic/d_boy.png" class="img-rounded">';
echo ''.$list[$i]['fn'].' '.$list[$i]['ln'].'';
echo '</div>';
echo '</li>';
}
echo '</ul>';
I want to get array of values from attribute 'value' of Anchor tag . I am able to get single value in jquery in variable e ... but i want array of values.
$.ajax({
type:'POST',
url:'../business_logic/send_chat_user.php', //URL
data:{ u_id: <?php echo $_SESSION['uid']?>,c_id }, //Data
beforeSend:function(){},
success:function(data,status){ //Data,status
var arr = [];
var item = $(data).hide().slideDown("slow");
var el = $.parseHTML(data);
var e = $("a", el);
e.each(function(index) {
arr.push($(this).attr('value'));
});
alert(arr.toString());
$('#msg').append(item);
}
});

AJAX cannot access an object data value passed from php

I have a php.php file to receive data then pass the result back to AJAX, like this:
<?php
$p1 = $_POST["p1"];
$c1 = $_POST["c1"];
$resultx['r1'] = "XXX";
$resultx['r2'] = 0;
$resultx['r3'] = 100;
$resultx['r4'] = 1000;
echo json_encode($resultx);
And in my js file I have:
$.ajax({
url: 'php.php',
type: 'POST',
data: {
p1: 5,
c1: 100
},
cache: false,
success: function (resultx) {
var result = resultx;
console.log(result);
var my1 = document.getElementById('my1');
var my2 = document.getElementById('my2');
var my3 = document.getElementById('my3');
var my4 = document.getElementById('my4');
my1.textContent = "Id : "+result.r1;
my2.textContent = "Rank : "+result.r2;
my3.textContent = "Total players : "+result.r3;
my4.textContent = "Top credit : "+result.r4;
},
});
The my1 my2 my3 my4 fields all print with undefined even though the console log show the value of:
{"r1":"XXX","r2":0, "r3":100, "r4":1000}
When I change the statement
var result = resultx;
to
var result = JSON.parse(resultx)
the javascript console prints a error message of uncaught syntax error unexpected token.
Please help!

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

Categories