Ajax, add to database and update div content - javascript

Okay, so I am trying to use ajax. I've tried several ways of doing this but nothing is working for me. I believe the main problem I have is that ajax won't add to my database, the rest is managable for me.
Here is the relevant ajax-code:
$(document).ready(function(){
console.log($("going to attach submit to:","form[name='threadForm']"));
$("form[name='threadForm']").on("submit",function(e){
e.preventDefault();
var message = $("#message").val();
//assumming validate_post returns true of false(y)
if(!validatepost(message)){
console.log("invalid, do not post");
return;
}
console.log("submitting threadForm");
update_post(message);
});
});
function update_post(message){
var dataString = "message=" + message;
alert(dataString);
$.ajax({
url: 'post_process.php',
async: true,
data: dataString ,
type: 'post',
success: function() {
posts();
}
});
}
function posts(){
console.log("getting url:",sessionStorage.page);
$.get(sessionStorage.page,function(data){
$("#threads").html(data);
});
}
function validatepost(text){
$(document).ready(function(){
var y = $.trim(text);
if (y==null || y=="") {
alert("String is empty");
return false;
} else {
return true;
}
});
}
Here is the post_process.php:
<?php
// Contains sessionStart and the db-connection
require_once "include/bootstrap.php";
$message = $con->real_escape_string($_POST["message"]);
if (validateEmpty($message)){
send();
}
function send(){
global $con, $message;
$con->create_post($_SESSION['username'], $_SESSION['category'], $_SESSION("subject"), $message);
}
//header("Location: index.php");
?>
And lastly, here is the html-form:
<div id="post_div">
<form name="threadForm" method="POST" action="">
<label for="message">Meddelande</label><br>
<textarea id="message" name="message" id="message" maxlength="500">
</textarea><br>
<input type="submit" value="Skicka!" name="post_btn" id="post_btn"><br>
</form>
create_post is a function I've written, it and everything else worked fine until I introduced ajax.
As it is now, none of the console.log:S are getting reached.
Ajax works when jumping between pages on the website but the code above literally does nothing right now. And also, it works if I put post_process.php as the form action and don't comment out the header in post_process-php.
I apologize for forgetting some info. I am tired and just want this to work.

I would first test the update_post by removing the button.submit.onclick and making the form.onsubmit=return update_post. If that is successful place the validate_post in the update_post as a condition, if( !validate_post(this) ){ return false;}
If it's not successful then the problem is in the php.
You also call posts() to do what looks like what $.get would do. You could simply call $.get in the ajax return. I'm not clear what you are trying to accomplish in the "posts" function.

First you can just submit the form to PHP and see if PHP does what it's supposed to do. If so then try to submit using JavaScript:
$("form[name='threadForm']").on("submit",function(e){
e.preventDefault();
//assumming validate_post returns true of false(y)
if(!validate_post()){
console.log("invalid, do not post");
return;
}
console.log("submitting threadForm");
update_post();
});
Press F12 in Chrome or firefox with the firebug plugin installed and see if there are any errors. The POST should show in the console as well so you can inspect what's posted. Note that console.log causes an error in IE when you don't have the console opened (press F12 to open), you should remove the logs if you want to support IE.
Your function posts could use jQuery as well as it makes the code shorter:
function posts(){
console.log("getting url:",sessionStorage.page);
$.get(sessionStorage.page,function(data){
$("#threads").html(data);
});
}
UPDATE
Can you console log if the form is found when you attach the event listener to it?
console.log($("going to attach submit to:","form[name='threadForm']"));
$("form[name='threadForm']").on("submit",function(e){
....
Then set the action of the form to google.com or something to see if the form gets submitted (it should not if the code works). Then check out the console to see the xhr request and see if there are any errors in the request/responses.
Looking at your code it seems you got the post ajax request wrong.
function update_post(message){
console.log(message);
$.ajax({
url: 'post_process.php',
async: true,
//data could be a string but I guess it has to
// be a valid POST or GET string (escape message)
// easier to just let jQuery handle this one
data: {message:message} ,
type: 'post',
success: function() {
posts();
}
});
UPDATE
Something is wrong with your binding to the submit event. Here is an example how it can be done:
<!DOCTYPE html>
<html>
<head>
<script src="the jquery library"></script>
</head>
<body>
<form name="threadForm" method="POST" action="http://www.google.com">
<label for="message">Meddelande</label><br>
<textarea id="message" name="message" id="message" maxlength="500">
</textarea><br>
<input type="submit" value="Skicka!" name="post_btn" id="post_btn"><br>
</form>
<script>
$("form[name='threadForm']").on("submit",function(e){
e.preventDefault();
console.log("message is:",$("#message").val());
});
</script>
</body>
</html>
Even with message having 2 id properties (you should remove one) it works fine, the form is not submitted. Maybe your html is invalid or you are not attaching the event handler but looking at your updated question I think you got how to use document.ready wrong, in my example I don't need to use document.ready because the script accesses the form after the html is loaded, if the script was before the html code that defines the form you should use document ready.

Related

Stop submitting if innerHTML value is equal to specified value

I'm designing a web page which checks if an email specified is available is database. If it is available, then i must stop submitting the form.
I used ajax for live checking of email and update the response as a span message. If i click submit button, even though the email is already available in the db, the form is submitted and getting redirected to another page. Please do help me get out of this. Thanks in advance.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
function checkemail() {
var email=document.getElementById( "UserEmail" ).value;
if(email) {
$.ajax({
type: 'post',
url: 'check.php',
data: {
user_email:email,
},
success: function (response) {
$( '#email_status' ).html(response);
}
});
}
}
function validateForm(){
var a=document.getElementById("email_status").innerHTML;
var b="Email Already Exist";
if(a==b)
alert('Yes');
else
alert('No');
}
</script>
</head>
<body>
<form method="POST" action="insertdata.php" onsubmit="return validateForm();">
<input type="text" name="useremail" id="UserEmail" onkeyup="checkemail();">
<span id="email_status"></span><br>
<input type="submit" name="submit_form" value="Submit">
</form>
Expected result when i give an email which is already in db:
Yes.
Actual result:
No
You code has design problems.
1.The biggest one is that you are make an ajax call request while user is typing, that will probably cause you big overhead.
2. the same design is causing the validation not working properly.
Allow me to make a proposal.
<form method="POST" action="insertdata.php" id="form" onsubmit="return false;">
<input type="text" name="useremail" id="UserEmail" >
<span id="email_status"></span><br>
<input type="submit" name="submit_form" value="Submit" onClick="checkemail();">
</form>
in this approach i have removed the keyup event form the input and have added the function checkemail() on button click.
var emails = [];
function checkemail() {
var email = document.getElementById('UserEmail').value;
if (email) {
if (!emails.includes(email)) {
$.ajax({
type: 'post',
url: 'check.php',
data: {
user_email: email,
},
success: function (response) {
$('#email_status').html(response);
if (response == 'Email Already Exist') {
console.log("email "+email+" is a spam")
emails.push(email);
} else {
document.getElementById('form').setAttribute('onsubmit', 'return true;');
document.getElementById('form').submit;
}
}
});
}else{
console.log("email "+email+" is a spam")
}
}
}
In this design approach code does
1.on button click executes checkemail function
2.checkemail function checks the emails array if contains the email from the text input, if the email is in the array then a log is written in console, if not then an ajax requset is done.
3.if the email is in the db then an other log is made, else the form is submitted.
This approach provides the ability of keeping every email that the user will possible write. I also suggest your ajax script instead of returning a text message to return a code maybe 0 or 1, that way comparison is safer.
Last but not least, although i don't know where you intend to use that code please keep in mind that a bot will probably bypass this java script code and hit directly your server side script. So you should think of a server side check also.
If you need more help or clarifications don't hesitate to ask.

Trying to send js variables to a php file

I am trying to send js variables from my js file to another php file when the user hits "FINISH" on the main php page. Here is my code so far:
map.php
<form action="./finalmap.php">
<input class="finish-button" type="submit" value="FINISH" onclick="sendData();" />
</form>
map.js
function sendData() {
$.ajax({
method: "POST",
url: "../finalmap.php",
data: {
selectedLoc: selectionArray,
startLoc: start,
endLoc: end,
dist: distance,
locTypes: allLocations
},
beforeSend : function(http) { },
success : function(response,status,http) {
alert(response);
},
error : function(http,status,error) {
$('.response').html("<span class='error'>Something went wrong</span>");
$(".response").slideDown();
}
});
}
finalmap.php
<?php
$data = $_POST['data'];
echo $data;
?>
Post is successful and I'm able to see the contents(my code) in my finalmap.php from the alert command. When I try to console.log $data in finalmap.php, it is empty/null.
My goal is to send the data to finalmap.php and redirect to it.
To solve this problem, you must reduce what you're testing to one thing at a time. Your code has errors and is incomplete. So let's start with the errors first: If you're using AJAX, you don't want HTML to submit the form in the regular way. If you get a page refresh, your AJAX didn't work.
<button type="button" id="submit-button">FINISH</button>
Note, no <form> is needed; you're submitting through AJAX.
Next, you need to be sure that your ajax function is being executed (since you're using $.ajax, I presume you have JQuery loaded):
<button type="button" id="submit-button">FINISH</button>
<script>
// all listener functions need to wait until DOM is loaded
$(document).ready(function() {
// this is the same idea as your onclick="sendData();
// but this separates the javascript from the html
$('#submit-button').on('click', function() {
console.log('hello world');
});
});
</script>
You use your web console to see the console.log message.
Now, try out the ajax command with a simple post:
<button type="button" id="submit-button">FINISH</button>
<script>
// all listener functions need to wait until DOM is loaded
$(document).ready(function() {
$('#submit-button').on('click', function() {
$.ajax({
method: "POST",
// "./finalmap.php" or "../finalmap.php"?
url: "../finalmap.php",
data: {foo: 'bar'},
success: function(response){
console.log('response is: ');
console.log(response);
}
});
});
});
</script>
finalmap.php
<?php echo 'This is finalmap.php';
If you see This is finalmap.php in the web console after pressing the button, then you can try sending data.
finalmap.php
<?php
echo 'You sent the following data: ';
print_r($_POST);
See where we're going with this? The way to eat an elephant is one bite at a time.
./finalmap.php is not a thing.
Instead the code must look like this:
<form action="/finalmap.php">
<input class="finish-button" type="submit" value="FINISH" onclick="sendData();" />
</form>
Try using this instead.
EDIT: OOPS SORRY, I JUST CPED AND PASTED.

using POST to send js variable to php from iframe

I am trying to pass a variable from js to a backoffice page.
So far I've tried using a form and submitting it from javascript (but that refreshes the page, which I don't want)
I ditched the form and when for an iframe (so the page doesn't reload everytime the data is submitted). The function is run every few seconds (so the form should be submitting):
<iframe style="visibility:hidden;display:none" action="location.php" method="post" name="location" id="location">
<script>
/*Some other stuff*/
var posSend = document.getElementById("location");
posSend.value = pos;
posSend.form.submit();
</script>
However my php page does not display the value posted (im not quite sure how to actually get the $_POST variable):
<?php
$postion = $_POST['location'];
echo $_POST['posSend'];
echo "this is the";
echo $position;
?>
I also tried $.post as suggested here Using $.post to send JS variables but that didn't work either.
How do I get the $_POST variable value? I cannot use $_SESSION - as the backoffice is a different session. What is the best method to do this?
EDIT I'd rather avoid ajax and jquery
And i think you no need to use form or iframe for this purpose . You just want to know the user onf without refreshing then use the following method with ajax.
index.html the code in this will
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script>
navigator.geolocation.getCurrentPosition(function(position)
{
pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
$.ajax(
{
url:'location.php',
type: 'POST',
datatype: 'json',
data: {'pos':pos}, // post to location.php
success: function(data) {
aler(data);
// success
},
error: function(data) {
alert("There may an error on uploading. Try again later");
},
});
});
</script>
location.php
echo "position :=".$_POST['pos'];
Instead of using iframe to submit your form with out reloading you submit form using ajax call.
$.ajax({
type: "POST",
url: url,
data: $("#formId").serialize(), // This will hold the form data
success: success, // Action to perform on success
dataType: "JSON" or "HTML" or "TEXT" // return type of function
});
There are various alternative to submit the form without reloading the page check here
Thanks
You can use plugin ajaxForm. On action and method you can form options
$(function() {
$('#form_f').ajaxForm({
beforeSubmit: ShowRequest, //show request
success:SubmitSuccesful, //success
error: AjaxError //error
});
});
Lakhan is right, you should try to use ajax instead of an iframe as they cause a lot of issues. If you absolutely need to use an iframe add a target attribute to your form (target the iframe not the main page) and only the iframe will reload.
<form action="action" method="post" target="target_frame">
<!-- input elements here -->
</form>
<iframe name="target_frame" src="" id="target_frame" width="XX" height="YY">
</iframe>
Here's a fully worked example that makes use of a <form>, the FormData object and AJAX to do the submission. It will update the page every 5 seconds. Do note that in PHP, the use of single quotes ( ' ) and double quotes ( " ) is not always interchangeable. If you use single quotes, the contents are printed literally. If you use double-quotes, the content is interpretted if the string contains a variable name. Since I wanted to print the variable name along with the preceding dollar sign ($) I've used single quotes in the php file.
First, the PHP
location.php
<?php
$location = $_POST['location'];
$posSend = $_POST['posSend'];
echo '$location: ' . $location . '<br>';
echo '$posSend: ' . $posSend;
?>
Next, the HTML
index.html
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
function myAjaxPostForm(url, formElem, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("POST", url, true);
var formData = new FormData(formElem);
ajax.send( formData );
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
var submitIntervalHandle = setInterval( doAjaxFormSubmit, 5000 ); // call the function to submit the form every 5 seconds
}
function doAjaxFormSubmit()
{
myAjaxPostForm('location.php', byId('myForm'), onSubmitSuccess, onSubmitError);
function onSubmitSuccess(ajax)
{
byId('ajaxResultTarget').innerHTML = ajax.responseText;
}
function onSubmitError(ajax)
{
byId('ajaxResultTarget').innerHTML = "Sorry, there was an error submitting your request";
}
}
</script>
<style>
</style>
</head>
<body>
<form id='myForm'>
<input name='location'/><br>
<input name='posSend'/><br>
</form>
<hr>
<div id='ajaxResultTarget'>
</div>
</body>
</html>

Form submit without going to the target page

I have question regarding form submit. I have this simple form on processFabrication.php to submit all the variables then process it to the database in another page called processExceededQty.php
Co, in processFabrication.php, I have
echo "<form action='processExceededQty.php' method='post'>";
When I click submit it goes to the processExceededQty.php.
What I am aiming to do is,
When user click submit, display confirmation yes/no with popup
After user click yes with the confirmation window, stay in processFabrication.php but methods in processExceededQty.php is still executed.
When user click no on the popup, go back and don't do form action
Any help would be greatly appreciated.
Something like this in your javascript:
function doSubmit(){
if (confirm('Are you sure you want to submit?')) {
// yes
return true;
} else {
// Do nothing!
return false
}
}
add the onsubmit to your form in html:
<form action='processExceededQty.php' method='post' onsubmit='doSumit()'>
Addition to #N0M3 answer.
Include below script in your <head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
and slight change in your function
function doSubmit(){
if (confirm('Are you sure you want to submit?')) {
// yes
$(this).submit(function(e){
e.preventDefault();
});
jQuery.ajax({
url : 'processExceededQty.php',
data : {'username':username}, // where first 'username' is your field name, and second one is your field's value
method: 'post',
success: function(data) {
// data is variable which has return data from `processExceededQty.php`
// do whatever you want with data
}
});
} else {
// Do nothing!
return false;
}
}
Use function on the "onsubmit" of the form like below,
<form action='processExceededQty.php' method='post' onsubmit='reutrn show_pop_up()'>
And on script you ca write following
<script>
function show_pop_up()
{
// show pop up
if(op_up_return =="Yes")
return true;
else
return false;
}
</script>
Hope this will help.

javascript return from php no updating anything

Hard to explain in the title...
So i have a form which is validated via javascript and an ajax request is sent to a php page which if succesful inputs the data and sets the database response.
However, on the ajax call getting the correct repsonse it doesnt carry out what i wish it to...
I What i want to happen is when the php returns a success JSON return, the .commentsdiv is reloaded.
This doesnt work however. But the comments are added into the database.
here is the code
part of commentsbox div and form:
<div class="commentsbox">
<form class="addcomment" action="process/addcomment.php" method="post">
<input type="hidden" class="postid" name="postid" value="'.$postID.'">
<input type="hidden" class="usernameuser" name="usernameuser" value="'.$usernameuser.'">
<input type="hidden" class="userid" name="userid" value="'.$userid.'">
<input type="text" name="addpostcomment" class="addpostcomment" placeholder="Add Comment..." />
<input type="submit" id="addcommentbutton" value="Post" />
<br />
<br />
</form>
</div>
Here is the javascript:
The viewbuild.php url is dynamic depending on what post is viewed. Do i need it to be like viewbuild.php?id=1 etc? Because that doesnt work niether.
// JavaScript - Edit Post
$(document).ready(function(){
$(".addcomment").submit(function(){
var $targetForm = $(this);
$targetForm.find(".error").remove();
$targetForm.find(".success").remove();
// If there is anything wrong with
// validation we set the check to false
var check = true;
// Get the value of the blog update post
var $comment = $targetForm.find('.addpostcomment'),
newcomment = $comment.val();
// Validation
if (newcomment == '') {
check = false;
$comment.after('<br><br><br><div class="error">Text Is Required</div>');
}
// ... goes after Validation
$.ajax({
type: "POST",
url: "process/addcomment.php",
data: $targetForm.serialize(),
dataType: "json",
success: function(response){
if (response.databaseSuccess) {
$('.commentsbox').load('viewbuild.php');
}
else {
$ckEditor.after('<div class="error">Something went wrong!</div>');
}
}
});
return false;
});
});
Here is part end of php:
$return['databaseSuccess'] = $dbSuccess;
echo json_encode($return);
Any help is most appreciated! :)
Make sure your php response is setting the proper headers. You need to set the content type as "application/json" for JQuery to call the success function. Try adding debugging to the error or complete callbacks when you call the jquery ajax function.
well , why am i thinking that you should check what value the obj returns ..
i mean ..
if(response.databaseSuccess == ??! ) { ... }
Or why don't you just check for the length of the retruned string.
if(response.databaseSuccess.length > 3){ alert('ok');}
One advise bro, if you are returning JUST one parameter .. use e string .. not JSON .. ;)
so, in php you would have :
echo $databaseSuccess;
And in JS .. the IF wil be more simple :
if(response == "ok"){ alert('ok');}
Get it ?
Hope i've helped.

Categories