ReferenceError: data is not defined or 403 Forbidden - php

and thank you in advance for reading this. I'm new in php and jquery. I've managed to do few forms in php that worked, and now feel a big need (because of how my webpage is shaping) to make them work with jquery. I'm trying but something is not right. This is the form:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method ="post" id="form_Add">
<br>
<div class="Add_field" id="title_div">Title:<input typee="text" class="Add_text" maxlength="100" name="title" id="title"></div>
<br>
<div class="Add_field">Discription:<input typee="text" class="Add_text" maxlength="1000" name="discription" id="discription"></div>
<br>
<div class="Add_field" id="content_div">Content:<textarea class="Add_text" maxlength="65535" name="content" id="content" rows="5" cols="15"></textarea></div>
<br>
<div class="Add_field"><label for="shortstory"><input typee="radio" name="prose" class="" id="shortstory" value="1">Short story</label></div>
<div class="Add_field" id="prose_div"><label for="chapter"><input typee="radio" name="prose" class="" id="chapter" value="2">Chapter</label></div>
<br>
<div class="Add_field" id="typey">type:
<select name="type1">
<option value="1" selected="selected">Fantasy</option>
<option value="2">Action</option>
<option value="3">Romance</option>
</select>with elements of
<select name="type2" id="type2">
<option value="" selected="selected"></option>
<option value="1">fantasy</option>
<option value="2">action</option>
<option value="3">romance</option>
</select>and
<select name="type3" id="type3">
<option value="" selected="selected"></option>
<option value="1">fantasy</option>
<option value="2">action</option>
<option value="3">romance</option>
</select>
</div>
<div class="Add_field"><input typee="submit" name="Add_story" class="Add_button" id="submit_story" value="Add story"></div>
</form>
<div id="response">Something</div>
That is script:
<script>
$('#form_Add').on('submit', function (e) {
e.preventDefault();
checkAdd();
});
var selectType = function(){
var type2 = $('#type2').val();
if(type2 === ""){
$('#type3').attr('disabled', 'disabled');
$('#type3').val("");
}
else{
$('#type3').removeAttr('disabled');
}
}
$(selectType);
$("#type2").change(selectType);
function checkAdd(){
var title = $('#title').val();
var content = $('#content').val();
if(title === ""){
$('#titleErr').remove();
$('#title_div').append("<p id='titleErr'>Please add the title.</p>");
}
else{
$('#titleErr').remove();
}
if(content.replace(/ /g,'').length <= 18){
$('#contentErr').remove();
$('#content_div').append("<p id='contentErr'>Content needs to be at least 19 characters long.</p>");
}
else{
$('#contentErr').remove();
}
if($("#shortstory").not(":checked") && $("#chapter").not(":checked")){
$('#proseErr').remove();
$('#prose_div').append("<p id='proseErr'>Check one of the above.</p>");
}
if($("#shortstory").is(":checked") || $("#chapter").is(":checked")){
$('#proseErr').remove();
}
if($("#titleErr").length == 0 && $("#contentErr").length == 0 && $("#proseErr").length == 0){
$.post('"<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"', { // when using this bit of script I get 403 Forbidden in Firebug console
title: $('#title').val(),
discription: $('#discription').val(),
content: $('#content').val(),
prose: $('input[name=prose]:checked').val(),
type1: $('#type1').val(),
type2: $('#type2').val(),
type3: $('#type3').val()
}, function(d){
alert(d);
console.log(d);
$('#response').html(d);
});
}
/*
var postData = $("#form_Add").serialize(); // when using this bit of script instead of one on top, I get alert fail and ReferenceError: data is not defined in Firebug console
var formURL = $("#form_Add").attr("action");
$.ajax(
{
url : formURL,
typee: "POST",
data : postData,
datatypee: 'json',
success:function(data, textStatus, jqXHR)
{
alert("success");//data: return data from server
console.log(data.error);
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
alert("fail");
console.log(data.error);
}
});
}
*/
};
</script>
And here is php code:
<?php
session_start();
if(isset ($_SESSION['arr'])){
$arr = $_SESSION['arr'];
$uid = $arr['id'];
}
$title = $discription = $content = $prose ="";
if (isset($_POST["Add_story"])) {
$title = stripslashes($_POST["title"]);
$title = mysqli_real_escape_string($connection , $title);
$discription = stripslashes($_POST["discription"]);
$discription = mysqli_real_escape_string($connection , $discription);
$content = stripslashes($_POST["content"]);
$content = mysqli_real_escape_string($connection , $content);
$prose = stripslashes($_POST["prose"]);
$prose = mysqli_real_escape_string($connection , $prose);
$type1 = $_POST["type1"];
$type2 = $_POST["type2"];
$type3 = $_POST["type3"];
$pQuery = "INSERT INTO prose (u_id, data, title_s, discription_s, content_s, prose_s, type1_s, type2_s, type3_s, shows_s)
VALUES ('{$uid}', CURDATE(), '{$title}', '{$discription}', '{$content}', {$prose}, '{$type1}', '{$type2}', '{$type3}', 0)";
$resultP = mysqli_query($connection, $pQuery);
if ($resultP) {
$title = $discription = $content = $prose ="";
}
else {
die("Query failed." . mysqli_error($connection));
}
}
?>
Php code is on the top of the document. Source is on bottom and form is in the middle (I'm using jquery-1.11.1.min.js - source is added in main page, as this one is included in it). I've also tried putting php in separate file and pointing to it through form action instead of <?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> but without any joy. I'm guessing my problem is with post data. It probably has to be in an array or object (and I'm doing it wrong) and when it reaches processing there is some sort of incompatibility. Probably using select and radio buttons complicates the process.
Any tips you can share I will greatly appreciate. Thank you for your time.

You have a serious typo in your submit button
<input typee="submit" name="Add_story"
^ extra "e"
which should read as
<input type="submit" name="Add_story"
Your code's execution relies on your conditional statement:
if (isset($_POST["Add_story"])){...}
Plus, you've made the same typo for all your other inputs typee="xxx"
Change them all to type
A simple CTRL-H (typee/type) in a code editor such as Notepad++ even in Notepad will fix that in a jiffy.
I noticed you have given id's to both <select name="type2" id="type2">
and <select name="type3" id="type3"> but not for <select name="type1">, so that could also be another factor that could affect your code's execution, seeing that you have:
type1: $('#type1').val(),
type2: $('#type2').val(),
type3: $('#type3').val()
Edit:
You've also put a commented message which I only saw now and should have been made clear in your question:
// when using this bit of script I get 403 Forbidden in Firebug console
over to the right of
$.post('"<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"', {
so I didn't see that.
Try changing it to either, and in single quotes only:
$.post('<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>', {
or
$.post('your_file.php', $(this).serialize(), function(data){
This page may help:
https://www.codeofaninja.com/2013/09/jquery-ajax-post-example.html
It contains an example in there that you can base yourself on.
which contains
$.ajax({
type: 'POST',
url: 'post_receiver.php',
data: $(this).serialize()
})
and may need to be added to your script.
You commented out url : formURL, - try using url: 'your_PHP_file.php', in its place, that being the PHP/SQL file that you're using.
If none of this helped, than let me know and I will simply delete this answer.

Related

Delete using ajax with a ajax request

I have the below that doesn't seem to work. Where am i going wrong.
The requesting data works fine but when I want to delete using the id from the retrieved data it doesn't do anything.
date.php
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document)
.ready(function () {
$(".date,.site")
.change(function () {
var site = $("#site")
.val();
var id = $("#date")
.val();
var dataString = 'id=' + id + '&site=' + site;
$.ajax({
type: "POST"
, url: "process.php?process=dselect"
, data: dataString
, cache: false
, success: function (html) {
$(".data")
.html(html);
}
});
});
});
$(document)
.ready(function () {
$(document)
.click('.delete', function () {
var id = $("#data")
.val();
var dataString = 'id=' + id;
alert(dataString);
$.ajax({
type: 'POST'
, url: 'process.php?process=delete'
, data: dataString
, success: function (data) {
if (data == "YES") {
alert("Holiday Deleted")
} else {
alert("can't delete the row")
}
}
});
});
});
</script>
</head>
<body>
<form method="get" action="index.php">
<select name="site" class="site" id="site">
<option>Select Site</option>
<option value="Self Park North">Self Park North</option>
<option value="Self Park South">Self Park South</option>
<option value="Valet North">Valet North</option>
<option value="Valet South">Valet South</option>
<option value="Summer Special">Summer Special</option>
<option value="cleaners">Cleaners</option>
</select>
<br />
<input name="date" type="date" value="" id="date" class="date" />
<p>Select Patroller</p>
<select name="data" class="data" id="data" size="20" style="width:400px;">
</select>
<br />
<input name="delete" type="button" value="delete" class="delete" id="delete" />
<input name="Submit1" type="submit" value="submit" />
</form>
process.php
case "delete":
include('dbconnect.php');
if ($_POST['id']) {
$id = $_POST['id'];
$query = "DELETE FROM taken WHERE id = '$id'";
if ($conn - > query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: ".$conn - > error;
}
}
break;
any help would be appreciated.
I can't tell without complete information - error messages, the definition of the variables you're showing us in the PHP snippet etc. You should check your error logs to see what's actually going on.
That said, there's an error around this:
if ($conn - > query($sql) === TRUE) {
If you try running something simple in PHP to test whether you can expand operators that way you'll see something like the following:
$ php -a
Interactive mode enabled
php > $a = (object) array("1" => "one", "two" => 2);
php > echo $a->two . PHP_EOL;
2
php > echo $a -> two . PHP_EOL;
2
php > echo $a - > two;
PHP Parse error: syntax error, unexpected '>' in php shell code on line 1
You can see that surrounding the operator by whitespace is OK, but splitting it up isn't.
This would cause your script to break, but because you haven't included the errors you're seeing I can't be sure it's the only problem.

Issue with posting data in PHP

Issue
I have a script that's been running fine since forever. It never gave any issues. It was last used in December with no issues whatsoever. No one changed anything. But now, it doesn't work. What it's supposed to do is submit a review and then notify users about the review. But it's not entering that section were it saves and notifies.
What I Have Done And Results
I have taken out that specific piece of the script that saves and notifies users, and tested it. It doesn't return anything which means it doesn't enter it. I've checked the post data, and that displays correct. I have also forced correct data to be posted (by changing params = $('#reviewForm').serialize(); to params = 'counter=1'.
My Code
Here is the form that is filled in by the user:
<form id="reviewForm">
Employee that will be reviewed: <input type="text" id="reviewed" name="reviewed" class="items"/><br>
<div id="openReviews" class="ui-corner-all ui-state-error" style="padding: 5 5 5 5"></div>
Employees that will do the review:<br>
<div id="reviewee_1">
<ul><b>Employee 1:</b>
<li>Name: <input type="text" id="reviewer_1" name="reviewer_1" class="items"/></li>
<li>Position: <select id="position_1" name="position_1" class="items">
<option value="sup">Supervisor</option>
<option value="supp">Peers: Support</option>
<option value="tech">Peers: Technical</option>
<option value="sub">Sub-Ordinate</option>
</select></li>
</ul>
</div>
<input type="hidden" id="counter" name="counter" value="1" class="items"/>
Add Another Reviewer <input type="button" id="add" value="Go >>"/><br>
<input type="button" onClick="sendInfo()" value="Create Review"/>
</form>
When Create Review is clicked, it calls this piece of jQuery code:
function sendInfo()
{
if($('#reviewed').val() != "")
{
var params = $("#reviewForm").serialize();
$.post('reviews.php',
params, // as stated, even if I change this to counter = 1, it doesn't work
function(data) {
$('#reviewForm').hide();
$('<p>' + data + '</p>').insertBefore('#reviewForm');
});
}
else
{
alert("Please complete all fields in this form!");
}
}
And then lastly, the code that processes the request:
if($_POST['counter'] > 0) // check if review was submitted
{
// do stuff...
// it doesn't even enter this...
}
Question
Did something change in the PHP or jQuery specs that could cause this to stop working?
Is there something that I'm missing?
What's going on!?
Please help!
All depends on what JQuery version you use.
I would replace:
var params = $("#reviewForm").serialize();
to
var params = {};
$.each($("#reviewForm").serializeArray(),function(key, elem){ params[elem.name] = elem.value });
and for post i would use
$.ajax({
type: "POST",
'url': 'reviews.php',
'cache': false,
'async': true,
'data': params
}).done(function( data ) {
$('#reviewForm').hide();
$('<p>' + data + '</p>').insertBefore('#reviewForm');
}); //before ; you can use 'fail' methot to catch errors

Can't seem to prevent the page refreshing after submitting this form

Well I have spent a while scouring the internet for what I'd seem to be a simple solution.
I'll show you the code and the ajax template I have been looking at.
<form style="padding:10px 2px;" name="test" class="searchform" action="#" method="GET">
<input style="margin-top:22.5px;" name="input_value" type="text" class="searchbx" size="" placeholder="Search songs..." />
<select name="cbb">
<?php
echo "<option value='artist'>$Artist</option>";
echo "<option value='name'>$Title</option>";
?>
</select>
<input id="sa" style="position:absolute;margin-top:35px;width:90px;" name="submit" type="submit" class="searchbutton" value="OK" />
</form>
<div id="sidebar-query-results">
<ul id="current-list" style="list-style: none; padding: 0;">
<?php
if (isset($_GET['submit']))
{
// Execute this code if the submit button is pressed.
if (empty($_GET['input_value'])) {
die();
}
include "db_config.php";
$input_value = $_GET['input_value'];
$combo_box_value = $_GET['cbb'];
echo $formvalue;
echo $cbbvalue;
$query = "SELECT * FROM `links` WHERE `$combo_box_value` LIKE '%$input_value%' LIMIT 0, 20" ;
$result = mysql_query($query);
if($result) {
while($row = mysql_fetch_assoc($result)){
$cover = $row['cover'];
$title = $row['title'];
$name = $row['name'];
$artist= $row['artist'];
$url = $row['url'];
The rest of the script is simply printing the results etc.
The script itself Works like a charm although I understand it's very "scruffy" but, functionality is all that I am really concerned about at the moment.
Anyway here is the ajax template:
<script>
$('form[name="test"]').submit(function(e) {
e.preventDefault();
$.ajax({
url : #.action,
type : this.method,
data : $(this).serialize(),
success : function(response) {
}
});
});
</script>
Either way it's just the ajax script that I can't get to work the php script I really don't want to have to alter, I have looked dozens of tutorials but, I am having a lot of trouble implementing them into my situation.
That's because the script is actually causing a syntax error so your AJAX binding isn't occurring as expected (the entire <script> is being rejects so therefore it's not being bound to the submit event and never calling .preventDefault())--Mostly because of the following:
url : #.action,
Try changing that to use:
url : $(this).prop('action')
(If you want to reference the <form action="..."> attribute) otherwise use a string like url: '/submit.php',
A more universal script would be something like:
$('form.ajax').on('submit',function(e){
var $form = $(this);
$.ajax({
'type': $form.prop('method'),
'url': $form.prop('action') || document.location,
'data': $form.serialize(),
'success': function(response){
// handle response
}
});
e.preventDefault();
});
Then you can add the ajax class to any form you'd like to be enhanced with ajax (and of course those without javascript support would default back to "traditional" methods).

Post result from a query via php in same page with Ajax

I have a form on my website with 3 drop-down boxes. After user select an option from each one and hit submit the data is posted to an external php file, that makes an query to MySQL and then the page is reloaded and result posted. I'd like to make this more fancy - with ajax without reloading the page. the problem is I'm completely nube. I search interned and tried a couple of examples but no result. Here is the code:
HTML FORM:
<form name="showprice" id="showprice" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="country" id="country">
<option value="">Select Country</option>
</select>
<select name="industry" id="industry" onchange="setOptions(document.showprice.industry.options[document.showprice.industry.selectedIndex].value);">
<option value="">Select Industry</option>
</select>
<select name="quality" id="quality">
<option value=" " selected="selected">Select country and industry first.</option>
</select>
<input value="Submit" type="submit" name="submit" id="submit">
</form>
<script type="text/javascript">
var frmvalidator = new Validator("showprice");
frmvalidator.addValidation("country","req","Please select country");
frmvalidator.addValidation("industry","req","Please select industry");
frmvalidator.addValidation("quality","req","Please select quality");
</script>
NOTE: I have removed the options to save space.
The external view.prices.php:
It is in another folder and now I am calling the result with
<?php include('includes/view.prices.php'); ?>
Present code is:
if(isset($_POST['submit'])) {
include ('config.php');
$con1 = mysql_connect($server, $username, $password);
if (!$con1)
{
die(<b>Could not connect: </b> . mysql_error());
}
echo'<br /><br /><table id="myTable" class="tablesorter" align="center">
<thead>
<tr>
**some table headers (8 columns)**
</tr>
</thead>
<tbody>';
$cou = $_POST['country'];
$ind = $_POST['industry'];
$qua = $_POST['quality'];
$sql = "SELECT * FROM $ind WHERE quality=$qua AND desig=$cou ORDER BY id ASC" or die('<b>Data Insert Error:</b> ' . mysql_error());
echo("<tr>
**Some table results with 8 variables taken from the MySQL database**
</tr>");
if (!mysql_query($sql,$con1))
{
die('Error: ' . mysql_error());
}
}
echo '</tbody>
</table>';
mysql_close($con1);
}}
else {
echo '<div class="grid_9">
<p><b>TIP:</b> Pick country, industry and quality from the drop-down above and hit "Submit" button to view results.</p>
</div>';
}
Any help highly appreciated.
I'd investigate jQuery. You will want to disable the default handler:
e.preventDefault();
Then with jQuery you can do something like:
$.ajax({
type: 'POST',
url: '',
data: $("#showprice").serialize(), dataType: 'json',
success: function(data){
if( data['status'] == 'success' )
{
// Do stuff here
}
}
});
That code assumes that you're going to return a json encoded string. Which jQuery can handle without any problems.
I use jQuery for this all the time.
$(function() {
$('#showprice').sumbit(function() {
$.post('includes/view.prices.php', $(this).serialize(),function(data) {
$('#idoftag').html(data);
})
});
})
With some help from a friend I've managed to do this:
1) In head of the file where is the form add:
<script type="text/javascript" src="path-to-jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var working = false;
$('#id-of-form').submit(function(e){
e.preventDefault();
if(working) return false;
working = true;
//$('#submit').val('Sending..');
$.post('path-to-php-file-to-be-executed',$('#id-of-form').serialize(),function(msg){
working = false;
//$('#submit').val('Submit');
$('#id-of-div-where-result-will-be-outputed').html(msg);
});
});
});
</script>
2) After the form add the div for outputed data
<div id="output_div"></div>
3) In path-to-php-for-execution add:
if(isset($_POST['id-of-form-field-1']) && isset($_POST['id-of-form-field-2']) && isset($_POST['id-of-form-field-3'])) {
// some queries here
}
That's all
in your form, reference your current page as the action value...example, if your page is index.php. then use action="index.php" and method = "post". within the div you want the data to appear, write the php code in the correct format and enclose all this code with an if($_POST){ -your database retrieval code - } ?>. This means that your post action will call the same page which will make the condition surrounding your code to be true, hence executed. Hope this helps, it nagged me back then but i this worked.
In Notepad++, it looks like your { } are mismatched. They line up when I deleted one after the die statement and one above the else.

jQuery POST values to PHP script

I want to post some values from a simple HTML form, validate them with an ajax call and if successful submit to a PHP script and redirect to that script. I have got the ajax part set up, just not sure how to post and redirect (as if you would on a standard form submit without ajax).
Here's what I have:
HTML:
<div id=audiencesearch>
<h1>Audience Search</h1>
<form id="audiencesearchform">
<p>Passion Point</p>
<select id="passionselect">
<option selected="selected">Please select</option>
<option>3D</option>
<option>Music</option>
<option>Playstation</option>
</select>
<p>Gender Bias</p>
<select id="genderselect">
<option selected="selected">Please select</option>
<option>Male</option>
<option>Female</option>
</select>
<p>Sort Group By Age Range</p>
<select id="ageselect">
<option selected="selected">Please select</option>
<option>Under 21</option>
<option>21 - 30</option>
<option>31 - 40</option>
<option>41 - 50</option>
</select>
<br/>
<br/>
<input onClick="ajaxaudiencesearch()" class="submitaudiencesearch" value="Search" type="button"/>
Ajax Call:
<script type="text/javascript">
function ajaxaudiencesearch(){
var passionpoint = $("select#passionselect").val();
var genderbias = $("select#genderselect").val();
var agerange = $("select#ageselect").val();
var passedstring = 'passion='+ passionpoint + '&gender=' + genderbias + '&age=' + agerange;
$.ajax({
type: "POST",
url: "processaudiencesearch.php",
data: passedstring,
success:function(retval){
if (retval == 'oktoprocess'){
audiencesearchprocess();
} else {
audiencesearcherror();
}
}
})
}
function audiencesearcherror(){
$('#audienceerror').html('GOTTA SELECT EM ALL');
}
function audiencesearchprocess(){
window.location.href = "searchresults.php";
//THIS IS WHERE I WANT TO POST AND MOVE TO SEARCHRESULTS.PHP
}
</script>
PHP to handle Ajax:
<?php
include('sonymysqlconnect.php');
session_start();
$nullselection = "Please select";
//get the posted values
$postedpassion = ($_POST['passion']);
$postedgender = ($_POST['gender']);
$postedage = ($_POST['age']);
if (($postedpassion != $nullselection ) && ($postedgender != $nullselection ) && ($postedage != $nullselection)){
echo 'oktoprocess';
} else {
echo 'error';
}
?>
Preferably I could achieve this using jQuery. I'm sure it's extremely simple but I'm not sure how to do it?!
It's worth mentioning that this is all set up correctly. I have used PHP includes.
Thanks in advance...
Why not add action and method attributes to your form and then submit it with .submit()?
With plain html / php it is not even really a true redirect, its just the url value in "action" that can be found in the form element
<form action="/someUrl/someAction" method="POST">
...
</form>
If you're doing it with ajax (jquery), you'd say:
$.ajax({
url: '/someUrl/someAction',
type: 'POST',
data: {
argName1: 'argVal1',
argName2: 'argVal2'
},
success: function( response ) {
// keep in mind that response is usually in json...
// which means you'd be accessing
// the data in object notation: response.data.someVal
if(response == 'whatYouWanted') {
//do something... like redirect?
window.location = '/new/page';
}
});

Categories