AJAX data, understanding as to what this actually does - javascript

I found some old code which I am trying to understand and unfortunately I did not leave comments which leads to my difficulties. Even with the jQuery documentation, I can't wrap my head around it; I really have looked, but I still don't understand. This program is basically a chat where you type your name and your message and click submit. Then it displays your message in a chat box similar to Facebook. Here is the working code:
My JS
$(document).ready(function() {
$('#submit').on('click', function() {
var name = $('#name').val();
var shout = $('#shout').val();
var outText = 'name=' + name + '&shout=' + shout;
if (name == '' || shout == '') {
alert("Please fill in your name and shout");
} else {
$.ajax({
type: "POST",
url: "database.php",
data: outText,
cache: false,
success: function(html) {
$('#shouts ul').prepend(html);
}
});
}
return false;
});
});
and my PHP
<?php
$connection = mysqli_connect('localhost','root','','muntasirshoutbox');
if(isset($_POST['name']) && isset($_POST['shout']))
{
$name = mysqli_real_escape_string($connection,$_POST['name']);
$shout = mysqli_real_escape_string($connection,$_POST['shout']);
$query = "INSERT INTO shouts(name,shout) ";
$query.= "VALUES ('$name','$shout')";
$result = mysqli_query($connection,$query);
if(!$result)
{
echo "doesent work".mysqli_error($connection);
}
else
{
echo '<li>'.$name.': '.$shout.'</li>';
}
}
?>
So I am confused as to what outText is actuallly doing, the reason I am confused is because, I was under the impression that my PHP was printing the text inside the chat box when I do this echo '<li>'.$name.': '.$shout.'</li>';, but after experimenting with outText, I noticed that if I change some stuff with outText the message I type in wont appear at all in the chat box, or it will appear with whatever string I added to it. What exactly is this doing?!

Related

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

Textbox not clears when clicks the submit button

I am trying to clear the txtSubTotal text box after clicking the PROCEED button. It's not working though I tried some code examples, even in SO.
btnProceed/HTML
<input type="submit" name="btnProceed" id="btnProceed" value="PROCEED" onclick="clearSubTotal();"/>
clearSubTotal()/JS
function clearSubTotal() {
$('#txtSubTotal').val('');
}
txtSubTotal
<input name="txtSubTotal" type="text" id="txtSubTotal" size="15" value="<?php
$sql=mysqli_query($connection,"select sum(amount) from sales_temp");
$row = mysqli_fetch_array($sql);
echo $row[0];
?>"/>
form/HTML
<form id="manageSalesForm" name="manageSalesForm" method="post" action="<?php echo BASE_URL?>includes/functions/sales_functions.php">
Appreciate your help on this.
NOTE: Found that on the second button press, the text box clears. How to set this correctly for the first button perss?
ADD button/JS
function submitdata() {
var listItemName = document.getElementById("listItemName").value;
var listStock = document.getElementById("listStock").value;
var txtUnitPrice = document.getElementById("txtUnitPrice").value;
var txtQuantity = document.getElementById("txtQuantity").value;
var listCustomer = document.getElementById("listCustomer").value;
var txtReceiptNo = document.getElementById("txtReceiptNo").value;
var TheDate = document.getElementById("TheDate").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = {listItemName:listItemName, listStock: listStock, txtUnitPrice: txtUnitPrice, txtQuantity: txtQuantity, listCustomer: listCustomer, txtReceiptNo: txtReceiptNo};
if (listItemName == '' || listStock == ''|| txtUnitPrice == ''|| txtQuantity == ''|| listCustomer == ''|| txtReceiptNo == ''|| TheDate == '') {
salesitemsAddFail();
}
else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "/pms/includes/functions/sales_temp_functions.php",
data: dataString,
cache: false,
success: function(html) {
//reload the sales datagrid once add the item details to temporary table (sales_temp)
$('#list').trigger("reloadGrid",[{page:1}]);
window.location.reload();
}
});
}
}
$('#btnProceed').click(function(event) {
event.preventDefault(); // stops form submission
$('#txtSubTotal').val('');
});
ADD button/HTML
<td width="46"><button type="button" name="btnSave" id="btnSave" onclick="submitdata(); check_qty(); showSubTotal();">ADD</button></td>
sales_functions.php
<?php
//Start the Session
if(!isset($_SESSION))
{
session_start();
}
include ("/../../pages/sales.php");
include("/../../dbutil.php");
if(isset($_POST['listCustomer'])){ $customer = $_POST['listCustomer'];}
if(isset($_POST['staff'])){ $user = $_POST['staff']; }
if(isset($_POST['btnProceed'])){
$result=mysqli_query($connection,
"INSERT INTO sales(cus_id,item_id,stock_id,receipt_no,qty,unit_price,amount,user_id,purchase_id)
SELECT C.cus_id, I.item_id, S.stock_id, $receipt_no, ST.qty, ST.unit_price, ST.amount, U.id, P.purchase_id
FROM customers C, items I, stock S, sales_temp ST, users U, purchase_items P
WHERE ST.staff='$user'
AND C.customer_name='$customer'
AND I.item_name=ST.item_name
AND S.stock_code=ST.stock_code
AND ST.purchase_id=P.purchase_id");
//Update available qty from purchase_items relevant only to the logged in user(sales_temp table may have records from multiple users)
$resultUpdate=mysqli_query($connection, "UPDATE purchase_items P INNER JOIN sales_temp ST ON (P.purchase_id = ST.purchase_id) SET P.avail_qty = (P.avail_qty - ST.qty) WHERE ST.staff='$user'");
//Delete records relevant only to current user. Here 'WHERE' clause use to prevent deleting other user's records.
$resultDelete=mysqli_query($connection, "DELETE FROM sales_temp WHERE staff='$user'");
if (!$result) {
printf("Errormessage: %s\n", mysqli_error($connection));
}
// use exec() because no results are returned
if ($result) {
}
else
{
echo '<script type="text/javascript">',
'salesAddFail();',
'</script>';
}}
?>
After clicking on the submit button, the form is being submitted and your custom function is not being executed.
Delete the onclick from your input element and edit your jQuery code:
$('#btnProceed').click(function(event) {
event.preventDefault(); // stops form submission
$('#txtSubTotal').val('');
});
You can try it in your browser: https://jsfiddle.net/hy7jwg8m/1/
It is working perfect for me. And after clicking on submit it might be working for you but with the same time page will be redirected to new action
I found the solution, added the do_onload(id) to calculate the total on loadComplete event which is triggered after each refresh (also after delete)
function do_onload(id)
{
//alert('Simulating, data on load event')
var s = $("#list").jqGrid('getCol', 'amount', false, 'sum');
jQuery("#txtSubTotal").val(s);
}
And changed the phpgrid code accordingly.
$opt["loadComplete"] = "function(ids) { do_onload(ids); }";
$grid->set_options($opt);

PHP Get POST Value from Ajax to PHP with 2 condition

Assume I have 2 textbox, that's serial_no10 and serial_no12. That 2 textbox appear not simultaneously depends on case
1 PHP file for checking the SN.
1 DIV status to display the data.
jQuery Ajax
var serial_no10 = $("#serial_no10").val();
var serial_no12 = $("#serial_no12").val();
$.ajax(
{
type: "POST",
url: "chk_dvd_part_no.php",
data: 'serial_no10='+ serial_no10 +'&serial_no12='+ serial_no12,
success: function(msg)
{
$("#status").ajaxComplete(function(event, request, settings)
{
}
}
}
HTML
<div id="status"></div>
PHP File
if(!empty($_POST['serial_no12']))
{
echo "Serial No 12";
}
else if(!empty($_POST['serial_no10']))
{
echo "Serial No 10";
}
Now I'm facing the problem when get POST from textbox serial_no_12, the value is undefined. But if get POST from textbox serial_no_10, I got the value.
Is that something wrong with that PHP code? Or I do something that should not be.
You have to just empty the variables before filling up. As if value is not reset then last value computed would remain in variavar
serial_no10 = $("#serial_no10").val();
var serial_no12 = $("#serial_no12").val();ble
change it with
var serial_no10='';
var serial_no12='';
serial_no10 = $("#serial_no10").val();
serial_no12 = $("#serial_no12").val();
Noww do things it will all good
Give your form tag an id if it has no anyone. and than do something like this.
var form = $("#form_id").serialize();
$.ajax({
type: "POST",
url: "chk_dvd_part_no.php",
data: form,
success:function(msg)
{
$("#status").ajaxComplete(function(event, request, settings)
{
//do your stuff
});
}
});
and in php file get your post variable by its name, suppose you have 2 inputs name serial_no10 and serial_no12
now do your php code like this.
if( isset($_POST['serial_no10']) && $_POST['serial_no10'] != '' ){
echo 'Serial No 10';
}
if( isset($_POST['serial_no12']) && $_POST['serial_no12'] != '' ){
echo 'Serial No 12';
}

Message error its not showing using ajax via jQuery

Im trying to update data in a form via ajax with jQuery.
Im doing the update with sucess, but when I have empty fields Im not getting my error message saying: myModal('config_datas_errempty','alert','Fill al fields please');
And also if I write a wrong format for email I dont have any message too.
Do you see where might be the error? Because for me everyting seems fine and I already review the code many times!
My php:
switch ($action)
{
case 'data_update':
$d['adress'] = $_POST['adress'];
$d['phone'] = $_POST['phone'];
$d['fax'] = $_POST['fax'];
$d['email']= $_POST['email'];
if(in_array('',$d))
{
echo 'errempty';
}
else if(!valMail($d['email']))
{
echo 'erremail';
}
else
{
$updateData= $pdo->prepare("UPDATE config_data set adress=?, phone =?, fax=?, email=? WHERE id = ?");
$updateData->bindValue(1, $d['adress']);
$updateData->bindValue(2, $d['phone']);
$updateData->bindValue(3, $d['fax']);
$updateData->bindValue(4, $d['email']);
$updateData->bindValue(5, '1');
$updateData->execute();
}
break;
default: echo 'Error';
}
My jQuery:
$('form[name="config_data"]').submit(function(){
var forma = $(this);
var data = $(this).serialize() + '&action=data_update';
$.ajax({
url: url,
data: data,
type: 'POST',
beforeSend: function(){
forma.find('.load').fadeIn("fast");
},
success: function( datas ){
if(datas == 'errempty'){
myModal('config_datas_errempty','alert','Fill al fields please');
}else if((datas == 'erremail')){
myModal('config_datas_accept','accept','Sucess update');
}
},
complete: function(){
forma.find('.load').fadeOut("fast");
}
});
return false;
});

mysql query executed even though fields are empty

I have created a simple tagging system for my schools websites for the students. Now the tagging system is working perfectly now i also have to save tags in a notifications table with respective article id to later notify the students which article they have been tagged in even that i managed to do. But now if by chance you want to remove the tags sometime realizing while typing the article you don't need to tag that person, then the first put tag also gets updated in the db.
//ajax code (attach.php)
<?php
include('config.php');
if(isset($_POST))
{
$u=$_POST['v'];
mysql_query("INSERT INTO `notify` (`not_e`) VALUES ('$u')");
}
?>
// tagsystem js code
<script type="text/javascript">
var id = '<?php echo $id ?>';
$(document).ready(function()
{
var start=/%/ig;
var word=/%(\w+)/ig;
$("#story").live("keyup",function()
{
var content=$(this).text();
var go= content.match(start);
var name= content.match(word);
var dataString = 'searchword='+ name;
if(go.length>0)
{
$("#msgbox").slideDown('show');
$("#display").slideUp('show');
$("#msgbox").html("Type the name of someone or something...");
if(name.length>0)
{
$.ajax({
type: "POST",
url: "boxsearch.php",
data: dataString,
cache: false,
success: function(html)
{
$("#msgbox").hide();
$("#display").html(html).show();
}
});
}
}
return false();
});
$(".addname").live("click",function()
{
var username=$(this).attr('title');
$.ajax({
type: "POST",
url: "attach.php",
data: {'v': username},
});
var old=$("#story").html();
var content=old.replace(word,"");
$("#story").html(content);
var E="<a class='blue' contenteditable='false' href='profile2.php?id="+username+"'>"+username+"</a>";
$("#story").append(E);
$("#display").hide();
$("#msgbox").hide();
$("#story").focus();
});
});
</script>
Looks like your problem appears on the if statement in php code:
even though $_POST['v'] is empty and the sql still get excuted.
There is the quote from another thread:
"
Use !empty instead of isset. isset return true for $_POST because $_POST array is superglobal and always exists (set).
Or better use $_SERVER['REQUEST_METHOD'] == 'POST'
"
Or in my opinion.
Just put
if ($_POST['v']){
//sql query
}
Hope it helps;)
<?php
include('config.php');
$u = $_POST["v"];
//echo $a;
if($u != '')
{
mysql_query("your insert query");
}
else
{
}
?>

Categories