Issued loading PHP data to HTML file using JavaScript - javascript

I am writing a Shoutbox. The HTML file has 2 buttons: refresh - refreshes all the messages and submit - submits message and refreshes page messages.
Everything works perfectly but one issue. When I click submit, the page doesn't refresh with latest message. But everything works fine afterwards.
HMTL file:
<head>
<link rel="stylesheet" href="css/style.css" type="text/css" />
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
<script src="script.js"></script>
</head>
<body>
<div id="wrap">
<div id="input">
<form>
<input type="text" name="name" id="name" placeholder="Enter a name">
<input type="text" name="message" id="message" placeholder="Enter a message">
<input type="button" id="refresh" value="Refresh">
<input type="button" id="submit" value="Submit">
</form>
</div>
<div id="messages">
<ul id="messageList"></ul>
</div>
</div>
</body>
</html>
JavaScript File
$(document).ready(function() {
$('#refresh').on('click', function(){
$("#messageList").load( "messages.php");
event.preventDefault();
});
});
$(document).ready(function() {
$('#submit').on('click', function(){
var name = $("#name").val();
var message = $("#message").val();
var dataString = 'name='+ name + '&message='+ message;
$.post( "newmessage.php", dataString );
event.preventDefault();
$("#messageList").load( "messages.php");
event.preventDefault();
});
});
messages.php:
<?php
//error_reporting(0);
include 'database.php';
//Create Select Query
$query = "SELECT * FROM shoutbox ORDER BY time DESC";
$shouts = mysqli_query($con, $query);
while($row = $shouts->fetch_object()) {
$time = $row->time;
$name = $row->name;
$message = $row->message;
echo "<li>".$time." - <b>".$name.": </b>".$message."</li>";
}
$con->close();
?>
newmessage.php:
<?php
//error_reporting(0);
include 'database.php';
if(isset($_POST['name']) && isset($_POST['message']))
{
$name = '"'.$_POST['name'].'"';
$message = '"'.$_POST['message'].'"';
$datum = new DateTime();
$timeStamp = $datum->format('Y-m-d H:i:s');
$insert_row = $con->query("INSERT INTO shoutbox(name, message) VALUES($name, $message)");
}
if($insert_row) {
} else {
die('Error : ('. $con->errno .') '. $con->error);
}
$con->close();
?>

From this answer:
I'd recommend strongly that you take the time to understand the nature of asynchronous calls within JavaScript
Please follow the link, there's more info there.
To your code to work:
$(document).ready(function() {
$('#submit').on('click', function(event){ // << event was missing
var name = $("#name").val();
var message = $("#message").val();
var dataString = 'name='+ name + '&message='+ message;
event.preventDefault();
$.post("newmessage.php", dataString, function(){
// this function is a callback, called on AJAX success
$("#messageList").load( "messages.php");
});
});
});

This should do the job. Make sure if you are using event.preventDefault(), you pass the event variable to the function. This can also test if the message was posted successfully
$('#submit').on('click', function(event){
event.preventDefault();
var name = $("#name").val();
var message = $("#message").val();
var dataString = 'name='+ name + '&message='+ message;
var posting=$.post( "newmessage.php", dataString );
posting.done(function(data){
$("#messageList").load( "messages.php");
});
posting.fail(function(){
alert("Something is not right with your message. Please Try Again")
})
});

Related

ajax fails and returns a web page instead of json

I am trying to import a json array from a php script in JavaScript but every time the request fails and the xhr.responseText return the html code of the template of the html template associated to it. I am using xampp.
php code:
<?php
// This script is meant to display the data from Insight sensors DB
include('includes/motebymote.html');
if ($_SERVER['REQUEST_METHOD'] == 'POST'){//Use the post method as a request method to the server
require('mysqli_connect.php');//Give information on which database to use
if(!empty($_COOKIE["mote_ID"]) || !empty($_COOKIE["std"]) || !empty($_COOKIE["end"])){
//Setting variables
$moteID=$_COOKIE["mote_ID"];
$start=$_COOKIE["std"];
$end=$_COOKIE["end"];
if(preg_match("/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/", $start) || preg_match("/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/", $end)) {
if(isset($moteID) && isset($start) && isset($end)){
//Building the query
$q="SELECT date_time, modality, value FROM sensor_data WHERE mote_id = $moteID and date_time BETWEEN '$start' and '$end'";
$r = #mysqli_query ($dbc, $q);//Doing the request
$numRow = mysqli_num_rows($r);
if ($r && $numRow>0){
//echo "<p>There are $numRow data points associated to mote$moteID</p><br>";
//echo"<table align ='center' width ='70%' cellpadding='4'><tr><th>Date&Time</th><th> Sensor Type</th><th> Value</th></tr>";
$moteArray = array();
while($data = mysqli_fetch_array($r, MYSQLI_BOTH)){
//echo "<tr align ='center'><td>" .$data['date_time']. "</td><td>" .$data['modality']. "</td><td>" .$data['value']. "</td></tr>";
$moteArray[] = $data;
}
//echo"</table>";
$JSONMoteArray = json_encode($moteArray);
echo $JSONMoteArray;
}
else if ($numRow==0){
echo "<h1>Sorry there are no data available</h1>
<p>There are no data available for mote$moteID</p>";
}
else{//Give an error message if the query fails
echo '<h1>System Error</h1>
<p class="error">We could not record your order due to a system error. We apologize for any inconvenience.</p>';
}
}
}
else {
echo "<h1> Wrong date format</h1>
<p>Please input the starting date in a yyyy-mm-dd format</p>";
}
}
else{
echo "<h1> Wrong input</h1>
<p> Please make sure that the mote is properly selected and that the start and end dates are entered in yyyy-mm-dd format</p>";
}
mysqli_close($dbc); //close the database
}
exit(); //exits the script
?>
<!DOCTYPE html>
<html lang="eng">
<head>
<meta charset="utf-8">
<title> Motes Data</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="js/mote.js" async></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body><br>
<form action="motebymote.php" method="post">
<p>Please input a mote number: <input type="text" name="moteNo" id="moteNo"></p>
<p> Please input a starting date (yyyy-mm-dd):<input type="text" name="stDate" id="stDate"></p>
<p> Please input an end date (yyyy-mm-dd):<input type="text" name="endDate" id="endDate"></p>
<p><input type="submit" name="submit" value="submit" id="submit"/></p>
<p><input type="submit" name="display" value="display" id="display"/></p>
<div id="columnchart_material" style="width: 800px; height: 500px;"></div>
</form>
</body>
</html>
var but = document.getElementById("submit"); //Looking for the submit button
if(but){ //if the button is clicked activate the event listener
but.addEventListener("click", moteIDDate);
}
//This function goes to fetch the different values and store them with cookies //to allow motebymote.php to use them
function moteIDDate(){
var moteID = $('#moteNo').val();
document.cookie="mote_ID = " + moteID + ";time()+3600";
var start = $("#stDate").val();
document.cookie = "std="+start+";time() 3600";
var end = $("#endDate").val();
document.cookie= "end="+ end+";time() 3600";
};
var jsonData = $.ajax({
url: "http://localhost/Insight/mote2/motebymote.php",
type:"GET",
cache: false,
dataType: "json",
success: function(xhr){
console.log(xhr.responseText);
},
error: function(xhr){
console.log(xhr.responseText);
}
});
The php code has "if...== POST"
your javascript ajax call is sending a "GET"

jQuery ajax not posting values to php script

I am having a problem with posting a value to my php script via jQuery/ajax. I have searched around looking for a solution but cannot seem to figure it out why i am not getting the value posted.
here's my code.
page.html
<body>
input message:<p><input type="text" id="note" name="note" placeholder="enter something that made you feel this way"></p><br />
<p><button name="submitMessage">submit</button></p>
<script src="../js/jquery-3.1.1.js"></script>
<script src="../js/welcomeScript.js"></script>
<script> $( document ).ready(function() {
$('[name=submitMessage]').on('click', function (e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '../php/post-note.php',
data: {data: $('#note').attr('val')},
success: function(){
alert('added your note, you will now go to main app!');
window.location.href = "../home.php";
}
});
});
});
</script>
</body>
post-note.php
session_start();
$note = $_POST['data'];
if(isset($note) && isset($_SESSION['username'])){
$username = $_SESSION['username'];
$sqlMessage = "UPDATE mt_tbl SET note = '$note' WHERE userName = '$username'";
mysqli_query($conn, $sqlMessage);
echo "note: ".$note. " added to the dB!";
}
Instead of $('#note').attr('val') use $('#note').val()
Why? the reason is given below:-
console.log($('#note').attr('val'));
console.log($('#note').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id = "note" value = "2">

Form validated but no email send

have some problems with my form which is being validated correctly, but when clicking submit button no email is going out. Mail fucntion is enabled on server as i checked raw mail sending. What can be wrong here? See my code below
HTML and JS:
....
<!-- Bootstrap Css -->
<link href="bootstrap-assets/css/bootstrap.min.css" rel="stylesheet">
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.0.min.js"></script>
<script type="text/javascript" src="js/validator.min.js"></script>
<!-- Style -->
<link href="plugins/owl-carousel/owl.carousel.css" rel="stylesheet">
<link href="plugins/owl-carousel/owl.theme.css" rel="stylesheet">
<link href="plugins/owl-carousel/owl.transitions.css" rel="stylesheet">
<link href="plugins/Lightbox/dist/css/lightbox.css" rel="stylesheet">
<link href="plugins/Icons/et-line-font/style.css" rel="stylesheet">
<link href="plugins/animate.css/animate.css" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<!-- Icons Font -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<script>
$(document).ready(function () {
$("#contactForm").validator().on("submit", function (event) {
if (event.isDefaultPrevented()) {
// handle the invalid form...
console.log("rrrr");
} else {
console.log("fff");
// everything looks good!
event.preventDefault();
submitForm();
}
});
});
$(document).ready(function submitForm() {
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
$.ajax({
type: "POST",
url: "process.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
}
}
});
});
$(document).ready(function formSuccess() {
$("#msgSubmit" ).removeClass( "hidden" );
});
</script>
contact form:
<form role="form" id="contactForm">
<div class="row">
<div class="form-group">
<input type="text" class="form-control" name="name" id="name" placeholder="Wpisz swoje imię, nazwisko" required="required">
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Enter email" required>
</div>
<div class="form-group">
<textarea id="message" name="message" class="form-control" rows="5" placeholder="Enter your message" required></textarea>
</div>
<button type="submit" id="form-submit" class="btn-block">Wyślij wiadomość</button>
<div id="msgSubmit" class="h3 text-center hidden">Message Submitted!</div>
</div>
</form>
procrss.php:
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
$EmailTo = "george#hgtg.com";
$Subject = "New Message Received";
// send email
$success = mail($EmailTo, $Subject, $message, $email);
// redirect to success page
if ($success){
echo "success";
}else{
echo "invalid";
}
?>
The fourth argument of mail should be additional headers, not just the sender's email address. So you've to rewrite your function:
$headers = 'From: ' . $email . "\r\n";
$success = mail($EmailTo, $Subject, $message, $headers);
But I'd suggest you add the sender's email to the message body. Since the suggested solution is vulnerable due to missing checks on the sender's email address.
$message .= "\n\n" . 'From: '. $email;
$success = mail($EmailTo, $Subject, $message);
The second function isn't what you seem to think it is, it's just DOM ready handler that you have given a name to, and you should see an error in the console telling you that submitForm() is not defined.
Change it to just
function submitForm() {
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
... etc
}
instead of
$(document).ready(function submitForm() {
// Initiate Variables With Form Content
var name = $("#name").val();
....
EDIT: open the console (F12), and add some logs to see what's happening
$(document).ready(function() {
$("#contactForm").validator().on("submit", function(event) {
if (event.isDefaultPrevented()) {
console.log("rrrr");
} else {
event.preventDefault();
submitForm();
}
});
$("#msgSubmit").removeClass("hidden");
});
function submitForm() {
$.ajax({
type: "POST",
url: "process.php",
data: $("#contactForm").serialize(),
success: function(text) {
console.log(text); // should be "invalid" or "success"
},
error : function() {
console.log('epic fail');
}
});
}
Hiding your "Message submitted" message and clearing the inputs after a specified time is straightforward.
You would do this with a call to setTimeout(). Something like this:
setTimeout( function() { myCleanupFunction(); }, 5000 );
That will call myCleanupFunction() after a 5 second wait.
Documentation on how to use setTimeout().
or what it looks like in the original code:
formSuccess() {
$("#msgSubmit" ).removeClass( "hidden" );
setTimeout( function() { myCleanupFunction(); }, 5000 );
}
Several of your javascript functions are being called at page load time, which is not what you are intending.
Only put functions in a $(document).ready() statement when you want those functions to run at page load time.
Here's a working version of your javascript, and a jsfiddle that replaces the $.ajax function with a test function called testAjax. All testAjax does is call your success function. (replace ajaxTest with $.ajax in production). You'll see that the jsfiddle behaves as you want.
function formSuccess() {
$("#msgSubmit" ).removeClass( "hidden" );
document.getElementById('msgSubmit').innerHTML = 'Message submitted!';
setTimeout( function () {
$("#msgSubmit" ).addClass( "hidden" );
}, 5000
);
}
// test version of ajax, replace with real "$.ajax()" in production
function ajaxTest( ajaxData ) {
// just a test, so call the success callback
ajaxData.success( 'success' );
}
function submitForm() {
// Initiate Variables With Form Content
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
// replace 'ajaxText' with '$.ajax' in production
ajaxTest({
type: "POST",
url: "process.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success : function(text){
if (text == "success"){
formSuccess();
}
}
});
}
$(document).ready(function () {
$("#contactForm").on("submit", function (event) {
// prevent default form submit
event.preventDefault();
// call our own submit
submitForm();
}
);
});

Ajax call not working after page reload.

I have my home page in php with checkboxes by the names of brand and store list.and in the end one submit button which is given below
<html>
<head>
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
function get_check_value() {
var c_value = [];
$('input[name="brand"]:checked').each(function () {
c_value.push(this.value);
});
return c_value.join(',');
}
function get_store_value(){
var d_value=[];
$('input[name="store"]:checked').each(function () {
d_value.push(this.value);
});
return d_value.join(',');
}
$(document).ready(function(){
$('#btnSubmit').on('click', function (e)
{e.preventDefault();
alert("hi");
//var os = $('#originState').val();
//var c = $('#commodity').val();
//var ds = $('#destState').val();
var ser = get_check_value();
var store=get_store_value();
//var queryString = "os=" + os;
var data = "?ser=" + ser;
var queryString = "&ser=" + ser;
alert(ser);
$.ajax({
//alert("ajax");
type: "POST",
url: "sortingajax.php",
data: {ser:ser,store:store},
dataType : 'html',
success: function (b) {
// alert(a+' ok. '+b)
$('#results').html(b);
console.log(b);
}
});
});
});
</script>
brand
<input type="checkbox" name="brand" value="Sunbaby" />Sunbaby
<br/>
<input type="checkbox" name="brand" value="Advance Baby" />Advance Baby
<br/>
store
<br/>
<input type="checkbox" name="store" value="JCPenny" />JCPenny
<br/>
<input type="checkbox" name="store" value="Supermart" />Suoermart
<br/>
<input type="checkbox" name="store" value="Target" />Target
<br/>
<button id="btnSubmit">sort</button>
<div id="results">
</div>
</body>
</html>
On click of submit,button it goes for ajax call and displays the result in results div.
<?php
include('connection.php');
$query=$_POST['ser'];
$query1=$_POST['store'];
echo $query;
echo $query1;
$query=explode(",",$query);
$query = array_filter($query);
$query1=explode(",",$query1);
$query1 = array_filter($query1);
$result=count($query);
$result1=count($query1);
//echo $result;
echo $result1;
$parts = array();
$limit = 10;
$offset = 0;
if(!empty($query))
{
foreach( $query as $queryword ){
$parts[] = '`BRAND` LIKE "%'.$queryword.'%"';
}
$brandsql='SELECT * FROM XML WHERE ('.implode ('OR',$parts).') order by price asc';
$brandsql1=mysql_query($brandsql);
$numrows = mysql_num_rows($brandsql1);
$countArray=array();
print($brandsql);
echo "<br />";
while($row = mysql_fetch_array($brandsql1)) {
// Append to the array
$countArray[] = $row;
//echo $row['PID']."<BR />";
}
}
$parts1=array();
if(!empty($query1)){
foreach( $query1 as $queryword1 ){
$parts1[] = '`STORE` LIKE "%'.$queryword1.'%"';
}
$storesql='SELECT * FROM XML WHERE ('.implode ('OR',$parts1).') order by price desc';
$storesql1=mysql_query($storesql);
$numrows1 = mysql_num_rows($storesql1);
$countArray=array();
print($storesql);
while($row = mysql_fetch_array($storesql1)) {
// Append to the array
$countArray[] = $row;
//echo $row['PID']."<BR />";
}
}
?>
<?php
foreach($countArray as $array)
{
?>
<div>
hi</div>
<?php $i++; } ?>
But iF I refresh my page or press F5 from keyboard,after getting content in results div,it goes back to previous content i.e.first page with checkboxes and submit button.
Please tell me where m doing wrong in the code or what do i need to include so that after ajax call if i refresh the page,content should remain same,should not go to previous content...
Use setTimeout() to run a refresh on the page after X seconds inside the AJAX callback, after you display content.
You could use the _SESSION variable in your PHP script to store what checkboxes were selected most recently, and display results on your results div, appropriately.
Although, if a user clicks refresh he might want to reset the choices he made anyway. You could give him a warning that his changes will be lost if he refreshes.
window.onbeforeunload = function() {
return confirm("You have made changes to this form. Do you want to continue without saving these changes?");
}

Pushing in MySQL data with javascript and php

I'm working on a program but I'm new to js/jQuery/Ajax. I am trying to get user input from a form (html) and send it over to a php file that will insert the data into a MySQL database and then ultimately spit out the information into a div. I press submit but my user submitted data does not get inserted into the database. I initially had the submission redirect to my php file through the tag (action="post.php") which had worked in terms of inserting the data into the mysql database but had also redirected it to that post.php file upon submission.
my js file datawire.js:
$( 'button#submit').on('click', function() {
var uName = $('input#uName').val();
var uMessage = $('input#uMessage').val();
if ($.trim(uName) != '' && $.trim(uMessage) != '') {
$.post('post.php', {username: uName, message: uMessage}, function(data) {
$('div#viewer').text(data);
});
}
});
My php file post.php
<?php include("config.php");
$username = isset($_POST['username']);
$message = isset($_POST['message']);
if (($username && $message) && (empty($_POST['username'] === false) && empty($_POST['message']) === false)) {
$username = $_POST['username'];
$message = $_POST['message'];
// insert into database
$nowTime = getDateTime();
$userIp = getIp();
$sql = "INSERT INTO commentdb (id,username, message,date,ip) VALUES ('','$username','$message', '$nowTime', '$userIp') ";
$result = mysql_query($sql);
}
?>
and my HTML file:
<html>
<head>
<!-- latest jQuery direct from google -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!-- for getting data -->
<script src="datawire.js"></script>
<!-- for posting data -->
<script type="text/javascript">
$(document).ready(function() {
$('#viewer').load("getdata.php");
});
</script>
</head>
<body>
<div id="viewer"> </div>
<br>
<!-- User form -->
<form method='post'>
<input type="text" id="uName" name="username" placeholder="Name" value="" maxlength="15" />
<br />
<input type="text" id="uMessage" name="message" placeholder="Message" value="" maxlength="100" />
<br />
<button id="submit" type="submit">Submit!</button> <button type="reset">Clear!</button>
</form>
</body>
</html>
Try wrapping the contents of datawire.js with $(document).ready like you did in html file. This insures $ is actually defined before it's used.
Prevent your form submit with preventDefault() function
$( 'button#submit').click(function(e) {
e.preventDefault();
var uName = $('input#uName').val();
var uMessage = $('input#uMessage').val();
if ($.trim(uName) != '' && $.trim(uMessage) != '') {
$.post('post.php', {username: uName, message: uMessage}, function(data) {
$('div#viewer').text(data);
});
}
});
Return the text message from the server like this
<?php include("config.php");
$username = isset($_POST['username']);
$message = isset($_POST['message']);
if (($username && $message) && (empty($_POST['username'] === false) && empty($_POST['message']) === false)) {
$username = $_POST['username'];
$message = $_POST['message'];
// insert into database
$nowTime = getDateTime();
$userIp = getIp();
$sql = "INSERT INTO commentdb (id,username, message,date,ip) VALUES ('','$username','$message', '$nowTime', '$userIp') ";
$result = mysql_query($sql);
if($result)
{
echo " Data Inserted Successfully";
}else{
echo " Data insert failed - ".mysql_error();
}
}else{
echo " Required fields are missing";
}
?>

Categories

Resources