i have a function which insert my data into my database. But at the same time i want that my javascript add the content to my list #div.
my php file
function xhrInsertPost() {
// echo $_POST[''];
$title = $_POST['title'];
$msg = $_POST['msg'];
$sth = $this->db->prepare('INSERT INTO posts (post_title, post_content) VALUES (:title, :msg) ');
$sth->execute(array(
':title' => $title,
':msg' => $msg
));
$data = array( 'post_title' => $title, 'id' => $this->db->lastInsertId());
echo json_encode($data);
}
my js file
$('#postText').submit(function() {
var url = $(this).attr('action');
var data = $(this).serialize();
$.post(url, data, function(data) {
console.log(data);
console.log(data.msg);
$('#listMsg').append('<tr><td>' + data.post_title + '</td><td><a class="del" rel="'+ data.post_id + '" href="#"> delete</a></td></tr>');
}, 'json');
return false;
});
i think it didn't work because my column called different. my code works but my "data.post_id" is undefined.. in my other method (if i refresh the page) it works
Related
I am customizing a plugin, which gives recent orders and plays a sound notification. However i want to add an ajax call to a custom button that shows in every row:
This is my method so far:
// ajax function in plugin file
<?php
function my_action_javascript($order_id) {
$order = wc_get_order( $order_id ); // returns correct order id in every button
?>
<script type="text/javascript"> // initiate script
jQuery(function($){
$('pluginchangebutton').click( function(e){
e.preventdefault();
$.ajax({
type: 'POST',
dataType: 'json',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: {
'action': 'my_action', // send php function ?
'order_id': <?php echo $order_id; ?>, // Here we send the order Id
},
success: function(response) { // no response at all
alert('ok');
},
error: function(response) { // no response at all
alert('error');
}
});
});
});
</script> <?php
}
add_action( 'wp_ajax_my_action', 'my_action' );// register my_action to wp ajax
function my_action() {
if ( isset($_POST['order_id']) && $_POST['order_id'] > 0 ) {
$order = wc_get_order($_POST['order_id']);
$order->update_status('completed'); // function to update status
die();
}
}
// ajax end
This is the ajax function which i place on top of the plugin file.
And this is how i display my table:
// get recent orders
$recent_orders = wc_get_orders(array(
'limit' => $show_order_num,
'orderby' => 'date',
'order' => 'DESC',
'status' => $show_order_statuses,
));
$content = "<h1>Нови порачки</h1>";
$content .= "<table id='customers-new-order-notification'>";
$content .= "<tr><th>Последни порачки</th></tr>";
$content .= "<tr><th>Порачка бр.</th><th>Дата на порачка</th><th>Статус на порачка</th><th>Детали за порачка</th></tr>";
foreach ($recent_orders as $recent_order) {
// get order details .. ... .. .. .. .. ..
$order_id = $recent_order->get_id();
$_order = wc_get_order($order_id);
$order_date = $_order->get_date_created();
$order_status = $recent_order->get_status();
$order_link = get_site_url();
$order_link .= "/wp-admin/post.php?post=";
$order_link .= $order_id;
$order_link .= "&action=edit";
$billing_first_name_plugin = $recent_order->get_billing_first_name();
$billing_address_1_plugin = $recent_order->get_billing_address_1();
$billing_city_plugin = $recent_order->get_billing_city();
$billing_postalcode_plugin = $recent_order->get_billing_postcode();
$billing_email_plugin = $recent_order->get_billing_email();
$billing_phone_plugin = $recent_order->get_billing_phone();
$billing_country_plugin = $recent_order->get_billing_country();
$order_shipping_method_plugin = $recent_order->get_shipping_method() . ' - ' . $recent_order->get_shipping_total() . ' rsd';
$order_get_subtotal_plugin = $recent_order->get_subtotal() . ' rsd';
$order_get_total_plugin = $recent_order->get_total() . ' rsd';
$order_javena='Непотврдена';
$customer_note_plugin = $recent_order->get_customer_note();
$statusPrefix = "wc-";
$_orderStatus = $statusPrefix . $order_status;
$_order_status = $order_status_map[$_orderStatus];
$date_format = get_option('date_format'); // format
$time_format = get_option('time_format'); // format
$format_order_date = $time_format . " - " . $date_format;
$items = $recent_order->get_items(); // get product items from order
// add content to $content .. table .. .. . .. row 1
// .... .... ... ... ... ... ... ... row 2
// row 3 start
$content .= "<td>" . esc_html($order_javena) ."<br>";
$content .= my_action_javascript($_order) . "<button class=pluginchangebutton type=submit>Потврди</button>";
$content .="</td>"; // row 3 end
// row 4 add .. .. ..
// row 4 end
if (!$isNew) {
delete_option('_new_order_id_for_notification');
$time = $refreshTime;
header("Refresh:" . esc_html($time) . "");
add_action('wp_head', 'wpb_hook_javascript');
}
echo $content;
}
In inspecting, the $.ajax gets the correct order id for every button, however i do not get a response at all. I've tried with console.log as well but still, no response.
I have tried inserting type, datatype and url with ' ', as well as " ", still nothing.
This code is in the plugin file.
I have tried adding it to functions.php, it does not work.
Can i get some guidance?
How to display the data title, image and content?
Here's the code:
view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$dataArr = array();
$responseArr = array();
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
array_push($dataArr, $data);
}
echo json_encode($dataArr);
}
mysqli_free_result($result);
} else {
echo "No Record";
}
}
index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
alert(data)
}
});
});
});
What I'm trying to do is to get the title, image and content.
How to get the value of title, image and content?
How to call the "title", "name" and "content" from the php?
console.log('DATA: ' + data);
No need to use while loop for result. Also remove extra $dataArr and $responseArr
Update your code to:
in view.php
$id = $_REQUEST['edit_literature_id'];
$literature = $_REQUEST['literatureID'];
$module = $_REQUEST['edit_moduleId'];
if (isset($id)) {
$sql = "SELECT * FROM $literature WHERE `id`='".$id."'";
if ($result = mysqli_query($conn, $sql)) {
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_array($result);
$data['title'] = $row['title'];
$data['name'] = 'data:image/jpeg;base64,' . base64_encode($row['name']);
$data['content'] = $row['content'];
echo json_encode($data); exit;
}
mysqli_free_result($result);
}
}
$data['error'] = "No Record";
echo json_encode($data); exit;
Index.php
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
rowId = $(this).attr('data-id');
moduleData = $(this).attr('data-module');
literatureData = $(this).attr('data-literature');
$('#edit_id').val(rowId);
$('#edit_module').val(moduleData);
$('#edit_literature').val(literatureData);
$('#edit_imageId').val(rowId);
$('#update').val('update');
$.ajax({
type: 'POST',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (data) {
var response = jQuery.parseJSON(data);
var title = response.title;
var name = response.name;
var content = response.content;
alert(title);
alert(name);
alert(content);
}
});
});
});
After taking data from jQuery side, you can set value in html side using id or class attribute in jQuery.
How your ajax receiving .php file should look:
$validLiteratureIds = ['yourTable1', 'yourTable2'];
if (!isset($_GET['edit_literature_id'], $_GET['literatureID']) || !in_array($_GET['literatureID'], $validLiteratureIds)) {
$response = ['error' => 'Missing/Invalid Data Submitted'];
} else {
$conn = new mysqli('localhost', 'root', '', 'dbname');
$sql = "SELECT title, name, content
FROM `{$_GET['literatureID']}`
WHERE `id` = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $_GET['edit_literature_id']);
$stmt->execute();
$stmt->bind_result($title, $name, $content);
if (!$stmt->fetch()) {
$response = ['error' => 'No Record'];
} else {
$response = [
'title'=> $title,
'name' => 'data:image/jpeg;base64,' . base64_encode($name),
'content' => $content
];
}
}
echo json_encode($response);
Important practices:
Validate the user input so that only qualifying submissions have the privilege of accessing your database.
Write the failure outcomes before success outcomes consistently throughout your project, this will make your scripts easier to read/follow.
Always use prepared statements and bind user-supplied data to placeholders into your query for stability/security.
The tablename cannot be bound like the id value; it must be written directly into your sql string -- this is why it is critical that you validate the value against a whitelist array of literature ids.
There is no need to declare new variables to receive the $_GET values; just access the values directly from the superglobal array.
I am going to assume that your id is a primary/unique key in your table(s), so you don't need to loop over your result set. Attempt to fetch one row -- it will either contain data or the result set was empty.
Call json_encode() only once and at the end of your script.
It is not worth clearing any results or closing a prepared statement or a connection, because those tasks are automatically done when the script execution is finished anyhow -- avoid the script bloat.
As for your jquery script:
$(document).ready(function () {
$(document).on('click', '#btnModalUpdate', function (e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: '../../crud/read/view.php',
data: $('#modalFormUpdate').serialize(),
dataType: 'json',
success: function (response) {
if (response.hasOwnProperty('error')) {
console.log(response.error);
} else {
console.log(response.title, response.name, response.content);
}
}
});
});
});
I've trim away all of the irrelevant lines
changed POST to GET -- because you are merely reading data from the database, not writing
parseJSON() is not necessary -- response is a ready-to-use object.
I am checking for an error property in the response object so that the appropriate data is accessed.
Both scripts above are untested (and completely written from my phone). If I have made any typos, please leave me a comment and I'll fix it up.
I trying to get $comments_id,$comments_timestamp, $user_firstname, $user_lastname values and pass back to ajax, but in the if statement was execute only one object array which is ['successful-submit-comment'] = true;.
Ajax
$.ajax({
type:'post',
url:'getcomment_detail.php',
data:{comment_id: comment_id,user_desc:user_desc},
cache:false,
dataType:'json',
success: function (data){
console.log(data);
var ttes1 = data.comments_timestamp;
alert(ttes1);
}
});
getcomment_detail.php :
$u_id = $_SESSION['u_id'];
$submit_comment_status = array();
if($sql = "INSERT INTO comments (post_id, user_id, user_desc) VALUES ('$comment_id','$u_id','$user_desc')"){
mysqli_query($conn,$sql);
mysqli_close($conn);
$get_comment_user_detail = "SELECT comments.id, comments.timestamp, user.firstname, user.lastname FROM comments INNER JOIN user ON user.id = comments.user_id WHERE user.id = $u_id ORDER BY comments.id DESC LIMIT 1";
if($stmt = $conn->prepare($get_comment_user_detail)) {
$stmt->execute();
$stmt->bind_result($comments_id, $comments_timestamp, $user_firstname, $user_lastname);
while ($stmt->fetch()) {
$comments_userdetails = array(
'comments_id' => $comments_id,
'comments_timestamp' => $comments_timestamp,
'u_firstname' => $user_firstname,
'u_lastname' => $user_lastname
);
header('Content-Type: application/json');
echo json_encode($comments_userdetails);
}
$stmt->close();
}
$submit_comment_status['successful-submit-comment'] = true;
header('Content-Type: application/json');
echo json_encode($submit_comment_status);
}
Console return value:
Alert return value:
Undefined
Why don't you just put it into the array and return it all as a json file?
$comments_userdetails = array(
'comments_id' => $comments_id,
'comments_timestamp' => $comments_timestamp,
'u_firstname' => $user_firstname,
'u_lastname' => $user_lastname,
'successful-submit-comment' => true
);
header('Content-Type: application/json');
echo json_encode($comments_userdetails);
and in your ajax you just get the value like
console.log(data['successful-submit-comment']);
I have some problem with the returned value of ajax.
this is the ajax code:
$(document).ready(function() {
var request;
$("#flog").submit(function(event) {
if(request)
request.abort();
event.preventDefault();
var form = $(this);
var serializedData = form.serialize();
var btnname = $('#log').attr('name');
var btnval = $('#log').val();
var btn = '&'+btnname+'='+btnval;
serializedData += btn;
request = $.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: serializedData,
});
request.done(function(data, status, jdXHR) {
alert(data);
});
request.fail(function(jdXHR, status, error) {
});
});
});
it takes data from a form and send it to another page.
this is the second page:
<?php include 'head.php'; ?>
<?php
if($_POST['login']) {
session_regenerate_id(true);
$con = mysqli_connect("localhost", "Alessandro", "ciao", "freetime")
or die('Could not connect: ' . mysqli_error($con));
$query = 'SELECT * FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
if(mysqli_num_rows($result) == 0) {
mysqli_close($con);
session_unset();
session_destroy();
$res = false;
return $res;
}
$query = 'SELECT password FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
$line = mysqli_fetch_array($result, MYSQL_ASSOC);
if(md5($_POST['password']) != $line['password']) {
mysqli_close($con);
session_unset();
session_destroy();
return false;
}
?>
<?php include 'foot.php'; ?>
and in .done the returned data is all the html page.
How can I retrieve only a data, like $res? I tried with json_encode() but with no results.
If in the second page I delete the lines include 'head.php' and include 'foot.php' it works. But I need that the secon page is html, too.
Somenone can help me?
Dont use the Data attribute from AJAX.
Replace
request.done(function(data, status, jdXHR) {
alert(data);
});
with
request.done(function(data, status, jdXHR) {
alert(jdXHR.responseText);
});
You could do it in a much simpler way.
In PHP store the result of the attempted login into a variable, for instance $result =0; to start with
If the login is valid change it to 1 and return it to ajax by doing an echo at the end of your PHP file. If you need other value returned such as the name you could add it to the variable with a separator such as || for instance.
in javascript collect your return and go data = data.split('||');
if (data[0] == 0){alert("Welcome back " + data[1]);}else{alert("wrong login...")}
Previous use is correct, you need to escape the user collected in your PHP script.
Hope this helps.
Index File
<h4>Dates</h4>
<?php
foreach($dates as $date){
echo TbHtml::ajaxButton(date("D, d M" ,strtotime($date->date)),
array(
'matches/countryVenue'
),
array(
// 'dataType'=>'json',
'type'=>'POST',
'data'=>array('id'=>$date->id),
'success'=>'js: function(data) {
alert(data);
}',
'failure'=>'js: function(data) {
alert("error");
}',
),
array(
"id"=>$date->id,
"onmouseover"=>"date(this.id);"
)
);
echo "<br>";
}
?>
</div>
JS Code
<script>
function date(x){
//alert("Date " + x);
};
</script>
Matches Controller File :
public function actionCountryVenue(){
if(isset($_POST['id'])){
$id = $_POST['id'];
}
// echo $id;
$criteria = new CDbCriteria();
$criteria->select = "*";
$criteria->condition = "DATE = ".$id;
$countryVenue = Matches::model()->findAll($criteria);
if(!empty($countryVenue)){
echo CJSON::encode(array('countryVenue'=>$countryVenue));
}
}
My Question
I need help from someone to give an exact idea of callback and ajax.
Moreover what I plan to do is onmouseover of the ajaxButton, I want to make an ajax call sending the ID of the button to the controller and return json data from the controller and convert into php array.
Edit Info
I have managed to send the data from the controller to the index file but can not render json data in php.