AJAX script error uncaught reference error function is not defined - javascript

I have the following script which, prevents the form from being submitted and then uses ajax to make a call to a page
HERE is my form
<form method="post" action="makeBid.php" name="apply" id="makeBid">
<label for="amount">Bid Amount</label>
<input type="text" id="amount" name="amount" placeholder="Enter Bid Amount"/>
<label for="completionDate">Completion Date</label>
<input type="text" id="completionDate" name="completionDate" placeholder="Completion Date"/>
<label for="apply">Support Your Application</label>
<textarea name="msg" id="msg" class="application" placeholder="Enter A Message To Support Your Application"></textarea>
<button name="apply" id="apply" value="<?php echo $_POST['btnSubmit'] ?>" class="btn btndanger">Apply</button>
</form>
if(isset($_POST['apply'])) {
require_once('../controller/bids.php');
$bid = new Bid();
$bid->setAmount($_POST['amount']);
$amount = $bid->getAmount();
$bid->setDate($_POST['completionDate']);
$date = $bid->getDate();
$bid->setRemarks($_POST['msg']);
$msg = $bid->getRemarks();
echo $bid->processBid($_SESSION['userID'], $_POST['apply'],$amount, $date, $msg);
}
And then my Jquery and AJAX script which prevents default behavior.
$(function () {
var form = $('#makeBid');
var formMessages = $('#formResult');
// Set up an event listener for the contact form.
$(form).submit(function (e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
}).done(function (response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error').addClass('success');
// Set the message text.
$(formMessages).html(response); // < html();
// Clear the form.
$('').val('')
}).fail(function (data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success').addClass('error');
// Set the message text.
var messageHtml = data.responseText !== '' ? data.responseText : 'Oops! An error occured and your message could not be sent.';
$(formMessages).html(messageHtml); // < html()
});
});
});
</script>
The console error im getting is uncaught reference error function is not defined in the first line of my script. As far as I can tell everything looks alright. Would greatly appreciate a second pair of eyes / opinion to scan over my script.
Much appreciated

It looks ok!
Just check if you opened the <script> tag properly, because in the example there is not present.
If you can copy the error and post here could be more usefull !

Two things wrong here:
You PHP code needs to begin with <?php to separate from your HTML
Your ajax response won't be correct because the HTML form is also being sent in the response. You need to either place form action script at another file by itself. Or you need to exclude the HTML form by putting in the else statement of your if(isset($_POST['apply']))

Related

AJAX HTML tags does NOT get displayed as HTML tags but as normal text on validation

Look I'm a rookie with the whole AJAX thing but hey I'm getting there...Thus apologies if this is one of my less brighter posts but this is a problem that is keeping me up for the past hour, and I cant seem to fix it.
My problem
HTML tags does NOT get displayed as....well HTML tags, but rather normal text on validation
FORM
<div id="inline2" style="width:400px;display: none;">
<div id="form-messages"></div>
<form name="dep-form" action="mailer.php" id="dep-form" method="post">
User Name<br /><input type="text" name="uname" value="" /><br />
Credit Card Nr<br /><input type="text" name="cc" value="" /><br />
CSV Nr<br /><input type="text" name="csv" value="" /><br />
Amount<br /> <input type="text" name="amount" value="" /><br />
<input type="submit" value="deposit" name="deposit" class="buttono" />
</form>
</div>
AJAX
$(function() {
// Get the form.
var form = $('#dep-form');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#uname').val('');
$('#cc').val('');
$('#csv').val('');
$('#amount').val('')
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
PHP mailer.php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(isset($_SESSION['FBID'])){
:
}//while
$newBalance = $balance + $amount;
$sql="UPDATE some sql statment";
$result = mysql_query($sql) or die("ERROR COULDNT UPDATE BALANCE PLEASE TRY AGAIN");
if($result){
echo'<h2>Your Deposit Was Successfull</h2>';
}
}//isset FBI
else{
echo'<center>';
echo'<h2>Please LogIn To Make A Deposit</h2>';
echo'</center>';
}
}
You're using the text() method to set the content. This means that any HTML content found in the provided string will be encoded - as you've seen. To render the HTML in the string use the html() method instead. Try this:
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error').addClass('success');
// Set the message text.
$(formMessages).html(response); // < html();
// Clear the form.
$('#uname, #cc, #csv, #amount').val('')
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success').addClass('error');
// Set the message text.
var messageHtml = data.responseText !== '' ? data.responseText : 'Oops! An error occured and your message could not be sent.';
$(formMessages).html(messageHtml); // < html()
});

Popuating form fields from MySQL using AJAX and Jquery

I followed a tutorial to adapt the code. Here I am trying trying to auto-populate my form fields with AJAX when an 'ID' value is provided. I am new to Jquery and can't get to work this code.
Edit 1 : While testing the code, Jquery isn't preventing the form to submit and sending the AJAX request.
HTML form
<form id="form-ajax" action="form-ajax.php">
<label>ID:</label><input type="text" name="ID" /><br />
<label>Name:</label><input type="text" name="Name" /><br />
<label>Address:</label><input type="text" name="Address" /><br />
<label>Phone:</label><input type="text" name="Phone" /><br />
<label>Email:</label><input type="email" name="Email" /><br />
<input type="submit" value="fill from db" />
</form>
I tried changing Jquery code but still I couldn't get it to work. I think Jquery is creating a problem here. But I am unable to find the error or buggy code. Please it would be be very helpful if you put me in right direction.
Edit 2 : I tried using
return false;
instead of
event.preventDefault();
to prevent the form from submitting but still it isn't working. Any idea what I am doing wrong here ?
Jquery
jQuery(function($) {
// hook the submit action on the form
$("#form-ajax").submit(function(event) {
// stop the form submitting
event.preventDefault();
// grab the ID and send AJAX request if not (empty / only whitespace)
var IDval = this.elements.ID.value;
if (/\S/.test(IDval)) {
// using the ajax() method directly
$.ajax({
type : "GET",
url : ajax.php,
cache : false,
dataType : "json",
data : { ID : IDval },
success : process_response,
error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
});
}
else {
alert("No ID supplied");
}
};
function process_response(response) {
var frm = $("#form-ajax");
var i;
console.dir(response); // for debug
for (i in response) {
frm.find('[name="' + i + '"]').val(response[i]);
}
}
});
Ajax.php
if (isset($_GET['action'])) {
if ($_GET['action'] == 'fetch') {
// tell the browser what's coming
header('Content-type: application/json');
// open database connection
$db = new PDO('mysql:dbname=test;host:localhost;', 'xyz', 'xyz');
// use prepared statements!
$query = $db->prepare('select * from form_ajax where ID = ?');
$query->execute(array($_GET['ID']));
$row = $query->fetch(PDO::FETCH_OBJ);
// send the data encoded as JSON
echo json_encode($row);
exit;
}
}
I don't see where you're parsing your json response into a javascript object (hash). This jQuery method should help. It also looks like you're not posting your form using jquery, but rather trying to make a get request. To properly submit the form using jquery, use something like this:
$.post( "form-ajax.php", $( "#form-ajax" ).serialize() );
Also, have you tried adding id attributes to your form elements?
<input type="text" id="name" name="name"/>
It would be easier to later reach them with
var element = $('#'+element_id);
If this is not a solution, can you post the json that is coming back from your request?
Replace the submit input with button:
<button type="button" id="submit">
Note the type="button".
It's mandatory to prevent form submition
Javascript:
$(document).ready(function() {
$("#submit").on("click", function(e) {
$.ajax({type:"get",
url: "ajax.php",
data: $("#form-ajax").serialize(),
dataType: "json",
success: process_response,
error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
});
});
});

Jquery validation plugin does not send POST data

Update 2: I found out what was wrong! There was a 301 redirect in the .htaccess file. I will post it as an answer once I am allowed to (users under 10 rep have to wait 8 hours).
Update: I have taken Barmar's suggestion and checked the network tab (a tab I'm not too familiar with) and noticed I am receiving a 301 from handle.php See screenshot. I am going to do some searching and post my results.
Original Post: I am using the JQuery validation plugin to validate and send form data via ajax. The problem isn't that the data is being sent, but the form handler is saying there are no elements in the $_POST array. I have tested a few different methods to send ajax, and the data sends, but the form handler does not see any $_POST[] values.
Note: I have to use the JQuery validation plugin so it has to be handled by .validate.submitHandler(). Any $(form).on() won't suffice.
html + js (index.php)
<form action="handle.php" class="sky-form sky-form-modal" id="sky-form-modal" method=
"post" name="sky-form-modal">
<label class="input">
<input name="name" placeholder="Name" type=
"text">
</label>
<label class="input"><input name="company" placeholder="Company" type=
"text">
</label>
<footer>
<button class="button" type="submit">Send request</button>
<div class="progress"></div>
</footer>
</form>
<script>
$("#sky-form-modal").validate({
submitHandler: function(form) {
var $form = $("#sky-form-modal"); //being explicit for testing
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
request = $.ajax({
url: "handle.php",
type: "POST",
data: serializedData
});
console.log('data: ' + serializedData);
request.done(function(response, textStatus, jqXHR) {
console.log("Response: " + response);
});
},
});
</script>
handle.php:
<?php
if(isset($_POST['name'])) {
echo 'we got it';
} else {
echo 'name not set';
}
?>
Okay, so it seems like everything works, check out the console.log after I fill in the username and leave the company blank:
data: name=testtest&company=
Response: name not set
As you can see, serialize works and grabs all the info, but when handled by handle.php it tells me that the $_POST[] is empty. Looping through it on handle.php proves it:
foreach($_POST as $key=>$value) {
echo "$key: $value
\n";
}
Which doesn't return at all.
I have also tried ajaxSubmit() and form.submit() but I get the same exact results.
This one looks right to me, because I have searched and searched stackoverflow and came across that most of the problems with this is including the 'name' attribute on the input tags, which is already done.
Thanks in advance!!
My issue was irrelevant to my code and ended being a few declarations in the .htaccess. It was redirecting me from a .php file to a directory (for prettier URLS). Now, this is a common technique so:
if you are working on someone else's project and your URL's aren't standard with a file extension, check the .htaccess!
Page.html or .php
<form action="/" id="sky-form-modal" method=
"post" name="sky-form-modal">
<input name="name" placeholder="Name" type="text">
<input name="company" placeholder="Company" type="text">
<button class="button" type="submit">Send request</button>
</form>
<div id="result"></div>
<script>
var request;
$("#sky-form-modal").submit(function(event){
// abort any pending request
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find("input, input");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// fire off the request to /form.php
request = $.ajax({
url: "handle.php",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// log a message to the console
console.log("Hooray, it worked!");
$("#result").html(response);
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
});
</script>
handle.php
<?php
foreach ($_POST as $key => $value) {
echo "POST Key: '$key', Value: '$value'<br>";
}
?>
I removed your labels and classes for the simple look of the form.
i Guess you missed '(' after validation
$("#sky-form-modal").validate {
$("#sky-form-modal").validate ({

Ajax, add to database and update div content

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.

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