I dont know if i'm doing this the wrong way but I can't think of another way to do it.
I have a function in php that i'm calling with $.post and I want it to return an array. It sounds like I need to use a callback function and i'm trying but it just wont work.
Here is the code:
Jquery:
$("#e_del_date_btn").click(function(){
var new_date = $("#edited_del_date").val();
if (new_date == '') {new_date = $("#edited_del_date").attr("placeholder");}
var new_time = $("#edited_del_time").val();
var non = $("#non").html();
function getarray(new_date, new_time, non, callback) {
$.post('http://localhost:8080/wsad2/post.php',{'new_date':new_date,'new_time':new_time,'non':non}, function(data) {
callback(data);
});
}
getarray(new_date,new_time,non, function(data) {
alert(data[0]);
$("#odi_span").html(data[0]);
$("#e_del_date_pencil").attr("value",data[1]);
$("#e_del_date_pencil").attr("value2",data[2]);
});
$("#e_del_date").hide();
$("#e_del_date").css("z-index","0");
$("#po_main_div_test").css({ opacity : 1.0 });
});
PHP Code:
$returndata = array();
$returndate = $returntime = $returntext = '';
if ($fail == "false") {if ($row['complete'] == "no") {$returntext .= '(When Completed) ';}}
$returntext .= 'This order is scheduled to be delivered on<br>';
if ($fail == "false") {$returntext .= $new_date_2;$returndate = $new_date_2;} else {$returntext .= $orig_deldate;$returndate = $orig_deldate;}
$returntext .= ' between ';
if ($fail == "false") {$returntext .= $new_time_2;$returntime = $new_time_2;} else {$returntext .= $orig_time;$returntime = $orig_time;}
if ($fail == "true") {$returntext .= '<br>The New Delivery Date must be tomorrow or later.';}
$returndata[0] = $returntext;
$returndata[1] = $returndate;
$returndata[2] = $returntime;
//echo ($returntext);
return $returndata;
from some of the things I've read I might be trying to use $.post improperly, but basically I need to pass the date/time variables and then have the php return the value but they can be changed in the PHP code (which is the point of this, to edit a delivery date/time) so i need the value sent from the php back to the JavaScript in case it was changed, so i can update the attribute in case they decide to change it again w/out refreshing the page.
My problem is, the alert is always blank (the alert is for testing purposes) and basically it SEEMS to be working, but the 3 jquery calls in the getarray() function do not seem to be firing, or if they are they aren't working. right now the HTML field i'm updating doesn't change no matter what I do.
am I using the callback function improperly? I really need $.post to return an array, not just echo data so that I can update multiple fields instead of just one.
Also, i've left out some of the php code as I didn't think it was relevant. i just wanted to show the creation of the array and it being filled with data.
You can echo an array with PHP with JSON:
PHP:
http://php.net/manual/en/function.json-encode.php
Javascript:
http://api.jquery.com/jquery.parsejson/
Furthermore: How to send a proper POST request with JQuery:
$.ajax({
url: "test.php",
data: {my_$_Post1: "value"}
}).done(function() {
//whatever you want to do
});
Or(NOT RECOMMANDED):
Answer = $.ajax({
url: "test.php",
async: false
data: {my_$_Post1: "value"}
});
alert(Answer);
http://api.jquery.com/jquery.ajax/
One option is to print the data from your PHP code as a JSON (JavaScript) array. Then use JSON.parse() in your JavaScript code to parse the text and turn it into an array.
Related
Trying to use Javascript to pass the value from a button
to execute a PHP Script (The script simply changed a boolean column to 1 / True.
However i cannot get the code to work, i am not sure if its my Formatting, but i am not very familiar with Javascript
i am simply trying to change the value in the SQL Database on a column without any redirection.
index.php
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script language="javascript">
$("body").on("click","button", function(ev){
ev.preventDefault(); // prevent submitting a form ...
let data={id: $(this).data("id")}
$.post("viewed.php",data)
.done(function (result) {
console.log("Message:",result);
});
});
</script>
My Button index.php
<div><button name="Delete" data-id='<?echo $data['orderReference']?>'">Delete</button></div>
and Viewed.php
$orderID = $_POST['id'] ;
if ($_POST)
{
try {
$sqlOrderviewed = "UPDATE `Order_Header` SET `orderViewed` = '1' WHERE `Order_Header`.`orderReference` IN ($orderID) ";
$resultOrderupdate = $products->conn->query($sqlOrderviewed); // Execute Statement
echo $count = $resultOrderupdate->rowCount();
} catch
(PDOException $e) { // If error in SQL
echo "One or more errors occurred saving to database This transaction will be rolled back:" . $e->getMessage(); // Display Message on End Point
// $products->conn->rollback(); // Rollback SQL
}
}
I am aware of the SQL Injection in this example, this is not production just trying to get an example working
To do this I would suggest making REST API type behaviour in your PHP that accepts JSON (as an example) which you can define with headers. So your JavaScript can stay mostly the same, just make sure you are pointing to the correct URL. But I think your PHP should look more like this:
<?php
// Headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST'); //maybe make this an update to be Semantic with the SQL operation you are doing
// Get raw data from the post you made in JavaScript
$data = json_decode(file_get_contents("php://input"));
$id = $data.id;
// Use the data in your SQL
$sqlOrderviewed = "UPDATE `Order_Header` SET `orderViewed` = '1' WHERE `Order_Header`.`orderReference` IN ($id) ";
?>
If you need more information on creating APIs with PHP I suggest these resources:
https://www.youtube.com/watch?v=OEWXbpUMODk
https://shareurcodes.com/blog/creating%20a%20simple%20rest%20api%20in%20php
https://github.com/bradtraversy/php_rest_myblog
I am not sure that $(this).data("id") is getting the data you want. I assume you want to get the value of data-id in your button? If so I would change your JavaScript to something more like this:
<script language="javascript">
$("body").on("click","button", function(ev){
ev.preventDefault(); // prevent submitting a form ...
let id = ev.target.getAttribute("data-id");
let data={id: id};
$.post("http://localhost:{port}/viewed.php",data)
.done(function (result) {
console.log("Message:",result);
});
});
</script>
I hope this helps!
P.S this is how I might have written the JS for this, I just find it a bit more readable (Not tested, just written in the MD editor while answering the question):
let buttons = document.querySelectorAll("button");
buttons.forEach((button) => {
button.addEventListener("click", (e) => {
e.preventDefault();
let id = e.target.getAttribute("data-id");
let data = {
id: id
};
$.ajax({
type: 'POST',
url: '/viewed.php',
data: data,
success: function(result){
console.log( "result: " + result );
}
})
})
});
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>
Project Link: https://databasetable-net.000webhostapp.com/
This following code correctly deletes a row in a table:
$('#example').on('click', '.delete_btn', function () {
var row = $(this).closest('tr');
var data = table.row( row ).data().delete;
console.log(data);
alert("delete_btn clicked");
row.remove();
});
However, it is not permately deleting the row. If you refresh the page, the row that got 'deleted' still exists. I believe this is because I am not deleting the row out of the database. Normally in php you safely remove a row in a database with something like this:
id = mysqli_real_escape_string($con, $_GET['del']);
$stmt = $con->prepare("DELETE FROM employees WHERE id = ? LIMIT 1");
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->close();
header('location: index.php');
EDIT: Revised Code Index.php:
(document).ready(function() {
var asc = true;
var table = $('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "server.php",
"type": "POST",
},
//http://live.datatables.net/xijecupo/1/edit
columnDefs: [{
targets: -1,
defaultContent: '<button type="button" class="delete_btn">Delete</button>'
}],
rowGroup: {
dataSrc: 1
}
});
$(function(){
$(document).on('click','.delete_btn',function(){
var del_id= $(this).closest('tr');
var ele = $(this).parent().parent(); //removed the "$" from the ele variable. It's a js variable.
console.log(del_id);
$.ajax({
type:'POST',
url:'delete.php',
dataType: 'json', //This says I'm expecting a response that is json encoded.
data: { 'del_id' : del_id},
success: function(data){ //data is an json encoded array.
console.log('Data: ' + data); //Going to display whats in data so you can see whats going on.
if(data['success']){ //You are checking for true/false not yes or no.
console.log('You successfully deleted the row.');
alert("delete btn clicked");
ele.remove();
}else{
console.log('The row was not deleted.');
}
}
});
});
}); //http://jsfiddle.net/zfohLL0a/
}); //end doc ready
delete.php code:
$del_id = $_POST['del_id'];
$stmt = $conn->prepare("DELETE FROM employees WHERE id = ?"); //LIMIT 1
$stmt->bind_param('i', $del_id);
$confirmDelete = $stmt->execute();
$array['success'] = FALSE; //Initialize the success parameter as false.
if($confirmDelete){ //Check to see if there was an affected row.
$array['success'] = TRUE;
}
echo json_encode($array);
?>
Partial Solution: Sample format how to setup the ajax. You have to start off by using the datatables.net "ajax": method for the original server.php. But then after that you use the normal $.ajax methods for the add.php, delete.php, etc. It is confusing because you use two different syntax for ajax. Easiest to just look at the sample link. Youtube video for same code
Another helpful link that discusses sending info to and from the ajax/json are one two three Four
Updated answer using your latest updated code.
JS
$(function(){
$(document).on('click','.delete_btn',function(){
var del_id= $(this).closest('tr');
var ele = $(this).parent().parent(); //removed the "$" from the ele variable. It's a js variable.
console.log(del_id);
$.ajax({
type:'POST',
url:'delete.php',
dataType: 'json', //This says I'm expecting a response that is json encoded.
data: { //Set up your post data as an array of key value pairs.
'del_id' : del_id
},
success: function(data){ //data is an json encoded array.
console.log('Data: ' + data); //Going to display whats in data so you can see whats going on.
if(data['success']){ //You are checking for true/false not yes or no.
console.log('You successfully deleted the row.');
ele.fadeOut().remove();
}else{
console.log('The row was not deleted.');
}
}
});
});
});
delete.php
$del_id = $_POST['del_id'];
$stmt = $con->prepare("DELETE FROM employees WHERE id = ?"); //LIMIT 1
$stmt->bind_param('i', $del_id);
$confirmDelete = $stmt->execute();
$array['success'] = FALSE; //Initialize the success parameter as false.
if($confirmDelete){ //Check to see if there was an affected row.
$array['success'] = TRUE;
}
echo json_encode($array); //Your ajax is setup to expect a json response.
//json_encode the $array and echo it out. You have to do this.
//When you "echo" out a value, that is what the server is going to submit back to the ajax function.
//If you do not do this, the ajax script will not recieve a response from the delete.php page.
This code should work for you.
In addition to Joesph's response who was extremely helpful:
"The console shows "Uncaught RangeError: Maximum call stack size exceeded". It looks as though the Ajax call isn't being issued (nothing is showing on the network tab) - so it must be when creating the request. I suspect I may need to JSON.stringify your del_id."
Someone suggested this:
"The main stack problem is caused by var edit_id = $(this).closest('tr'); . You try to send that whole jQuery object as data in the ajax. Then jQuery can't serialize it internally and throws a fit
You probably want some property like ID or a data attribute from that row to send (not clear what expectations are)."
Please post if you have any recommendations. I will edit in any finalized code solution soon.
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
I am making a simple web chat application using ajax,php,javascript and mysql.
What I am trying to do here is to avoid fetching the whole database after an interval of 1 sec(which is normally done in basic chat application ) but rather I want to fetch and display(by appending) also those chats which have been newly entered into the database by any user.
To implement this ,First when the user first opens the chat screen the whole database is loaded in the chat window(not shown in this code snippet),and then I am using the variable msgid to fetch the latest value of MSg_ID (which is the auto-increment primary key in my chat table) through an ajax request to the page 'Msg.php' which returns the required value of msg_id.
Now using this value of msgid and comparing it with the max value of Msg_ID every second in the database through the ajax request to the page 'Chat3.php'.
If the Max value of Msg_ID has changed the required rows are returned . After this I m updating the value of 'msgid' using the same earlier ajax request to the page 'Msg.php'
The pages Msg.php and Chat3.php are working perfectly ,as I have tested them thoroughly.
My question here is what is the problem in my code , why is not working?
Can we use an ajax request inside a ajax call back function or not?
What else can be a probable source of error?
Any input will be valuable :)
If you have any problem in understanding the code,leave a comment.
'#yyy' and '#zzz' are random div elements which i am using to test the data value of ajax callback function.
I can even post the rest of the code if it helps.
<script type"text/javascript">
$(document).ready(function() {
var dept = '<?php echo $deptId; ?>';
$.ajax({
url: 'scripts/php/Msg.php',
data: {dept:dept},
success: function(data) {
$('#yyy').html(data);//this displays the correct value
var msgid=data;
}
});
var interval = setInterval(function() {
$.ajax({
url: 'scripts/php/Chat3.php',
data: {dept:dept,msgid:msgid},
success: function(data) {
if(data!='bad'){
//$('#messages').prepend(data);
$('#zzz').html(data);//does not display any value although Chat3.php is returning the correct value.
//below ajax request to update the value of msgid
$.ajax({
url: 'scripts/php/Msg.php',
data: {dept:dept},
success: function(data) {
var msgid=data;
$('#zzz').html(data); //not displaying anything although above one is was displaying
}
});
}
}
});
}, 1000);
});
</script>
Here is my Msg.php
<?php
require '../../includes/database/connect.db.php';
function get_msg($dept){
$query= "SELECT Msg_ID,Sender, Message ,Time_stamp FROM chat WHERE Dept_ID='$dept' ORDER BY Msg_ID DESC" ;
$run=mysql_query($query);
$messages =array();
while($message=mysql_fetch_assoc($run)){
$messages[] =array('msgid'=>$message['Msg_ID'],
'sender'=>$message['Sender'],
'message'=>$message['Message'],
'time_stamp'=>$message['Time_stamp']);
}
return $messages;
}
$dept=$_GET['dept'];
$messages = get_msg($dept);
$x=count($messages);
if($x){
foreach($messages as $message) {
if($x==count($messages)){
echo $message['msgid'];
}
$x--;
}
}
?>
Here is my Chat3.php
<?php
require '../../includes/database/connect.db.php';
function get_msg($dept,$msgid){
$query1= "SELECT MAX(Msg_ID) as msg_id FROM chat" ;
$run1=mysql_query($query1);
$row = mysql_fetch_assoc($run1);
$result =$row['msg_id'];
$messages =array();
if($result>$msgid)
{
$query= "SELECT Sender, Message ,Time_stamp FROM chat WHERE Dept_ID='$dept' AND Msg_ID>'$msgid' ORDER BY Msg_ID DESC" ;
$run=mysql_query($query);
while($message=mysql_fetch_assoc($run)){
$messages[] =array('sender'=>$message['Sender'],
'message'=>$message['Message'],
'time_stamp'=>$message['Time_stamp']);
}
return $messages;
}
else
{
return $messages;
}
}
$dept=$_GET['dept'];
$msgid=$_GET['msgid'];
$messages = get_msg($dept,$msgid);
if(count($messages)){
foreach($messages as $message) {
echo '<strong>'.$message['sender'].' Sent</strong><br>';
echo $message['message'].' <i><small><div align="right">'.$message['time_stamp'].'</i></small></div>';
}
}
else {
echo 'bad';
}
?>
The problem is the msgid
In your first AJAX Request you are setting the variable var msgid=data; which is in local scope.
I think you are trying to access that variable in the second AJAX request while sending the datas
url: 'scripts/php/Chat3.php',
data: {dept:dept,msgid:msgid}, // Trying to access the local variable of previous ajax request
EDIT:
Try removing the var from var msgid=data; in your first AJAX request. Removing var will make the variable GLOBAL, Although its not good to pollute the global scope, but you can definitely try out this for the time being