Getting undefined on my Ajax call - javascript

I'm getting undefined in the console when trying to log the "data.billAmount" statement. Why is this happening and how do I fix it?
I tried doing JSON.parse and JSON.stringify but those didn't work. I tried using dataType: 'json' but that didn't work. I'm not sure what else to try. I'm stuck.
PHP:
if (#$_POST['action'] == 'addBill')
{
$billName = $_POST['bill_name'];
$billAmount = intval($_POST['bill_amount']);
$data = array(
'billName' => $billName,
'billAmount' => $billAmount,
);
echo json_encode($data);
$stmt = $db->prepare("INSERT INTO bills (billName, billAmount) VALUES(?,?)");
$stmt->bindParam(1, $billName);
$stmt->bindParam(2, $billAmount);
$stmt->execute();
}
JavaScript:
$(".addBill").on("click", function(e) {
e.preventDefault();
var billAmount = $('.billAmount').val();
var billName = $('.billName').val();
$.ajax({
type: "POST",
url: "index.php",
data: {
billAmount: billAmount,
billName: billName,
action: 'addBill'
},
success: function(data) {
console.log(data.billAmount);
}
});
});

Suggest you to move functionality which is responsible for adding bill into separate file. Then make AJAX call to that file and everything would works well, because if you want a particular value point request to particular file which echo that value for you...
No needs to looking for workaround when that could be done in clear and right way by separating functionality into smaller junks.
In case if you insist to use index.php
after
$stmt->execute();
put one more line
exit();
As Mohamed-Yousef commented on question.

Related

How to bring a json result into PHP

I have some results from a fetch.php using json and I successfully brought all results to my bootstrap modal HTML screen.
When the Modal is being shown, I would like to run a MYSQL query using a value coming from the same json I used for the modal, however I can't put this value into a PHP variable to run the SQL query.
How can I get this?
I am trying to bring the same value I input into the HTML textbox (modal), but it is not working. I also tried to use the value from json '$('#PCR').val(data.PCRNo);)', but nothing happen.
This is the script to collect information from database using fetch.php file:
<script>
$(document).ready(function(){
$('#table').on('click', '.fetch_data', function(){
var pcr_number = $(this).attr('id');
$.ajax({
url:'fetch.php',
method:'post',
data:{pcr_number:pcr_number},
dataType:"json",
success:function(data){
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
}
});
});
});
</script>
This is the PHP code
<?php
//trying to get the value I have included on #PCR (textbox) which has ID='PCR' and name ='PCR' **
$PCR= $_POST['PCR'];
//running now the code to check if the database has the value and return the desired response to be shown **
$sql1 = mysqli_query($dbConnected,"SELECT * FROM change_management.tPCN");
while ($row1 = mysqli_fetch_array($sql1)) {
if ($row1['PCRNo']==$PCR){
echo $row1['PCNNo'];
echo "<br/>";
}else{
}
}
?>
I would like include value from this val(data.PCRNo) json return into the $PCR variable, so the MYSQL query is going to work
There are a number of quite basic logical issues with your code which are preventing it from working.
1) data: { pcr_number: pcr_number}- the name pcr_number doesn't match the value PCR which the server is searching for using $_POST['PCR'];. The names must match up. When making an AJAX request, the name you gave to the form field in the HTML does not matter (unless you use .serialize()) because you are specifying new names in the data parameter.
2) Your SQL query doesn't make sense. You seem to be wanting to read a single row relating to a PCR number, yet your query makes no usage of the input PCR value to try and restrict the results to that row. You need to use a SQL WHERE clause to get it to select only the row with that ID, otherwise you'll fetch all the rows and won't know which one is correct. (Fetching them all and then using an if in a PHP loop to check the correct one is very inefficient.) I wrote you a version which uses the WHERE clause properly, and passes the PCR value to the query securely using prepared statements and parameters (to project against SQL injection attacks).
3) Your output from the PHP also makes no sense. You've told jQuery (via dataType: "json" to expect a JSON response, and then your code inside the "success" function is based on the assumption you'll receive a single object containing all the fields from the table. But echo $row1['PCNNo']; echo "<br/>"; only outputs one field, and it outputs it with HTML next to it. This is not JSON, it's not even close to being JSON. You need to output the whole row, and then use json_encode() function to turn the object into a JSON string which jQuery can parse when it receives it.
Here's a version of the code containing all the above changes:
JavaScript:
$(document).ready(function(){
$('#table').on('click', '.fetch_data', function(){
$.ajax({
url: 'fetch.php',
method: 'post',
data: { pcr: $(this).attr('id'); },
dataType: "json",
success: function(data){
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
}
});
});
});
PHP:
<?php
$PCR = $_POST['pcr'];
$stmt = $dbConnected->prepare("SELECT * FROM change_management.tPCN WHERE PCRNo = ?");
$stmt->bind_param('s', $PCR);
$stmt->execute();
$result = $stmt->get_result();
//an "if" here will cause a single row to be read
if ($row = $result->fetch_assoc()) {
$output = $row;
}
else
{
$output = new StdClass();
}
$stmt->free_result();
$stmt->close();
//output the result
echo json_encode($output);
?>
N.B. I would potentially suggest studying some tutorials on this kind of subject, since this is a fairly standard use case for AJAX/JSON, and you should be able to find samples which would improve your understanding of all the different parts.
P.S. Currently the PHP code above will return an empty object if there is no matching row in the database. However, this is probably an error condition (and will cause your JavaScript code to crash due to trying to read nonexistent properties), so you should consider how you want to handle such an error and what response to return (e.g. 400, or 404, and a suitable message).
You need to first return json from php by using json_encode.
Inside this loop
while ($row1 = mysqli_fetch_array($sql1)) {
$data = array('PCRNo' => 'itsvalue', 'PCC' => 'itsvalue', 'Creation_Date' => 'itsvalue')
}
print json_encode($data)
store all the data in an associative array and then convert it into json using json_encode and return the json.
Use json data in you ajax file
$.ajax({
url:'fetch.php',
method:'post',
data:{pcr_number:pcr_number},
dataType:"json",
success:function(data){
var data = JSON.parse(data);
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
}
});
Below is the changed script to store different values in $PCR variable
<script>
$(document).ready(function(){
var i = 1;
$('#table').on('click', '.fetch_data', function(){
if(i == 1) {
var pcr_number = $(this).attr('id');
} else {
var pcr_number = $('#PCR').val();
}
$.ajax({
url:'fetch.php',
method:'post',
data:{pcr_number:pcr_number},
dataType:"json",
success:function(data){
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
i++;
}
});
});
});
</script>

How to fix success problem while getting data from php to javascript file?

I have used before these jquery-ajax and php codes. Everything was fine but know there is a problem that success function not working. However, php codes are working, I can add data to mysql database, but I couldn't post info back to javascript file again by use "echo" or any way. Is this problem could originate because of server? I need your support.
I have checked php file is working or not and there was no problem about php. In javascript file in ajax codes, I have tried beforeSend and complete functions, everything were fine. But success function not working.
JS codes:
var userCookie = 1;
var question_txt = document.getElementById("question_txt").value;
var category_slct = document.getElementById("category_slct").value;
$.ajax({
type: "POST",
url: websitePHP + "ask.php",
data: {
user : userCookie,
quest : question_txt,
cat : category_slct
},
beforeSend: function(){
},
success: function(data){
alert(data);
if(data == 'ok'){
alert('Question added');
}
}
})
PHP codes:
include("ayar.php");
$userID = $_POST['user'];
$categoryID = $_POST['cat'];
$question_txt = $_POST['quest'];
$askedTime = time();
$addQuestion = $vt->prepare("INSERT INTO ".$QUESTIONS." (userID, categoryID, question, image, link, sight, pinned, bestAnswerID, askedTime, publishedTime, published)
VALUES (?,?,?,?,?,?,?,?,?,?,?)");
$addQuestion->execute(array(''.$userID.'',''.$categoryID.'', ''.$question_txt.'', '', '', 0, 0, '', ''.$askedTime.'', '', 0));
echo 'ok';
exit();
I need to get back response from php to js by success function in ajax.
Thanks for your help,
Best regards.
Can you try
return 'ok'; instead of echo 'ok'; and removing exit(); function

How to GET javascript data in PHP file without page reload

I am building my best attempt at a twitter clone and have run into a bit of a problem. I want to be able to click on a post and, without a page refresh, display that post in the overlay of the page (as you would on a twitter feed to look at replies, etc.).
In script.js, I check for a click and try to change the url.
$('body').on("click", ".chirp", function(){
var uid = $_GET['id'];
var pid = $(this).attr("id");
var pidSplit = pid.split("chirp");
var messageID = pidSplit[1];
var obj = {foo: "status"};
$('.chirpOverlay').addClass("active");
window.history.pushState(obj, "Status", "profile.php?id="+uid+"&status="+pid);
});
The javascript works as intended...but as I will soon find out, the victory is short-lived.
In profile.php, I attempt to GET the status id from the URL parameter.
<?php
$status_id = $_GET['status'];
$sql = $db->query("SELECT * FROM chirps WHERE id='$status_id'");
if (mysqli_num_rows($sql) > 0) {
$c = $sql->fetch_object();
}
?>
This doesn't work because, as I've learned, using 'window.history.pushState' only changes the url- but doesn't load the page. Thus the $_GET statement fails. I need a way to get the id of the post I click on into profile.php without a page refresh. Even if it means taking a different approach (instead of using a URL parameter).
PS: I tried to do an XMLHttpRequest as well- to no avail. :(
Thanks in advance!
$('body').on("click", ".chirp", function(){
var uid = $_GET['id'];
var pid = $(this).attr("id");
var pidSplit = pid.split("chirp");
var messageID = pidSplit[1];
var obj = {foo: "status"};
$('.chirpOverlay').addClass("active");
$.ajax({
url: "profile.php?id="+uid+"&status="+pid,
type: "GET",
data: obj,
dataType: "html",
success: function(data){
console.log(data);
}
});
});
You need to just get something up and going that works and then you can add more to it as you figure things out. This should give you a good starting place.
Here are your two files. Make sure they are both in the same directory.
You will need to make sure you have a jquery version loaded. Put this on whatever page you are calling the script.js from.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
script.js
$(document).ready(function(){
$('body').click(function(){
var id; //define your id.
var pid; //define your pid.
var datastring = 'id=' + uid + '&status=' + pid;
console.log(datastring);
$.ajax({
url: 'profile.php',
type: 'POST',
cache: false,
data: datastring,
dataType: 'json',
success: function(data){
console.log('Made it to the success function: ' + data);
if (data) {
//It works, do something.
console.log(data);
} else{
//It does not work, do something.
console.log('Your ajax failed to get the info from your php page. Keep troubleshooting');
}
}
});
});
});
profile.php
<?php
/*
$status_id = $_POST['status']; //This needs to be sanitized and validated.
$sql = $db->query("SELECT * FROM chirps WHERE id='$status_id'"); //This is unsafe sql practice.
if (mysqli_num_rows($sql) > 0) {
$c = $sql->fetch_object();
}
echo json_encode($c); //This is what gets sent back to script.js
*/
echo 'You made it to your php page.';
?>
A few things:
You can not call any php variable from within your js. var uid = $_GET['id']; does not work.
Any value that you pass to the php page needs to be validated to make sure it is a legitimate value.
Your SQL query is prone to sql injections. Please read up on how to parameterize your queries. Good Mysqli Practices
I have finally found a AJAX-based solution to my problem.
I created a new php file called "chirp_open_ref.php" and added this ajax to script.js:
var datastring = 'status=' + messageID;
$.ajax({
url: "chirp_open_ref.php",
type: "POST",
data: datastring,
cache: false,
dataType: "text",
success: function(data){
$('.chirp-container').html(data);
}
});
Inside of 'chirp_open_ref.php':
<?php
require 'core.inc.php';
if (isset($_POST['status']) && isset($_SESSION['user_id'])){
$chirp_id = $_POST['status'];
$c = "";
$sql = $db->query("SELECT * FROM chirps WHERE id='$chirp_id'");
if (mysqli_num_rows($sql) > 0){
$c = $sql->fetch_object();
}
include'chirp.inc.php';
}
?>
'chirp.inc.php' is simply a template for the layout/structure of each post.
This works like a charm, but I am always open to any criticism of how I am performing this. Thanks for all the help guys!

Ajax call to submit text into database don't work

I have a page where users can put comments below photos, everything works fine in php, comments go to the database and displayed below the photo.
Now I'm trying to make it work with ajax but I have some troubles.
I have an javascript document with this:
$(document).ready(function(){
$("#btnSubmit").on("click", function(e){
var update = $("#activitymessage").val()
$.ajax({
method: "POST",
url: "./ajax/save_comment.php",
//data: { update: update}, - first version, not correct
data: { activitymessage: update},
datatype: 'json'
})
.done(function(response) {
console.log("ajax done");
console.log (response.message);
var ht = "<li>" + update + "</li>";
$("#listupdates").append(ht);
});
e.preventDefault();
});
});
The php page (save_comment.php) where I tell what to do with the input text:
<?php
spl_autoload_register(function ($class) {
include_once("../classes/" . $class . ".class.php");
});
$activity = new Comment();
if (!empty($_POST['activitymessage'])) {
$activity->Text = $_POST['activitymessage'];
try {
//$activity->idPost = $_GET['nr'];
//$activity->idUser = $_SESSION['user_id'];
// with this it works, but not yet correct
$activity->idPost = 66;
$activity->idUser = 3;
$activity->SavePost();
$response['status'] = 'succes';
$response['message'] = 'Update succesvol';
} catch (Exception $e) {
$error = $e->getMessage();
$response['status'] = "error";
$response['message'] = $feedback;
}
header('Content-type: application/json');
echo json_encode($response);
}
There is also the file Comment.class.php with the 'Comment' class and the function SavePost(). This works without ajax, so I assume the function is correct.
What works
the comment (var update) is printed on the screen into the list.
The console says : "ajax done"
What don't work
The input text don't insert into the database (and disappears when page refresh)
The console says: "undefined" (there must be something wrong with the 'response I use in this function)
I hope you guys can help me out. Thanx
update
I changed the: data: { activitymessage: update} line in the js file, and set manually values for the $activity->idPost = 66; $activity->idUser = 3; And everything works !
Only one thing I want to get fixed
the values of the $_GET['nr'] and $_SESSION['user_id'] are now set manually. Is this possible to get these automatic?
The $_GET['nr'] is the id of the page were the photo is and the comments. In this way I can make a query that returns all comments for this page.
The $_SESSION['user_id'] is the id of the user,so I can echo the username and profile photo.
You are sending data with the key being update not activitymessage
Change data to:
data: { activitymessage: update}
Or change $_POST['activitymessage'] to $_POST['update']
Also you have no $_GET['nr'] in url used for ajax. Nothing shown would help us sort that out but you would need the url to look more like:
url: "./ajax/save_comment.php?nr=" + nrSourceValue,
Not sure why you need to use $_GET['nr'] and don't use $_POST for that also and and nr property to data object being sent

How do I get two arrays in Ajax call?

JS CODE:
$.ajax({
url: 'assignavailtrainers.php',
data: {action:'test'},
type: 'post',
success: function(data) {
}
});
PHP CODE:
<?php
$username = "trainerapp";
$password = "password";
$hostname = "localhost";
$link = #mysql_connect($hostname, $username, $password);
if(#mysql_select_db("trainer_registration"))
{
$select_query_num = #mysql_query("select program_id,facilitator_id,availability_status from program_facilitator where availability_status in (1,2)");
$select_query_name = #mysql_query("select facilitator_id,firstname,lastname,email_id from facilitator_details");
$num_rows = #mysql_num_rows($select_query_num);
$trainerdetails = [];
$traineravaildetails = [];
$i = 0;
$j = 0;
while($row = #mysql_fetch_assoc($select_query_num))
{
$trainerdetails[$i]['pgidi'] = $row['program_id'];
$trainerdetails[$i]['facilitatorid'] = $row['facilitator_id'];
$trainerdetails[$i]['avail_status'] = $row['availability_status'];
$trainerdetails[$i]['idi'] = $row['facilitator_id'];
$i++;
}
while($row1 =#mysql_fetch_assoc($select_query_name))
{
$traineravaildetails[$j]['facilitatorid'] = $row1['facilitator_id'];
$traineravaildetails[$j]['firstname'] = $row1['firstname'];
$traineravaildetails[$j]['lastname'] = $row1['lastname'];
$traineravaildetails[$j]['emailidvalue'] = $row1['email_id'];
$j++;
}
echo json_encode(array('result1'=>$trainerdetails,'result2'=>$traineravaildetails));
}
?>
Please help me with the code in the ajax success function area. I've tried using initChart2 but I get an error which says initChart2 is not defined. I don't seem to understand of how to get two arrays from PHP in ajax since I'm a newbie ajax. If someone can help me with the code along with explanation, it'd be great. And I also need to know how to differentiate outputs in ajax which are sent from PHP.
You have two choices:
First one is to simply parse received (text) data to JSON:
var jsonData = JSON.parse(data);
// or simply data = JSON.parse(data);
But the best one in my oppinion is to specify json dataType to the $.ajax() request:
$.ajax(
data: {action:'test'},
type: 'post',
dataType: 'json',
success: function(data) {
...
}
});
This way, $.ajax() will also check for the validity of the received JSON data and error callback will be called instead of success one in case of wrong JSON data received.
...also is important to note you missed to send the json content-type header in your php with:
header("Content-Type: application/json");
Sending this header the dataType: 'json' parameter is no longer (strictly) necessary because $.ajax() guesses it by default attending to the received content-type. But, personally, I prefer to do both.
See $.ajax() documentation.
You forgot:
header("Content-Type: application/json");
… in your PHP.
While you are outputting JSON, you are telling the browser that it is HTML (which is the default for PHP) so jQuery isn't converting it to a useful data structure.
Add that and then you should be able to access data.result1 and data.result2.
To get ajax data:
$.ajax({
url: 'assignavailtrainers.php',
data: {action:'test'},
type: 'post',
success: function(data) {
data.result1;
data.result2;
}
});
You can use console.log(data); to view data structure

Categories