Delete using ajax with a ajax request - php

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.

Related

Getting the value of textbox

I have a select option, to get the value from this, I used jquery (please see below code). After I display the selected value in the textbox, I'm now having problem on how to get the value of textbox to process a such code. Even simply echo of the value is not working. What's the problem with the code? Please help. Thanks.
Select option:
<select name='shiptype' id='shiptype'>
<option value="0">Please select...</option>
<option value="LOC">LOCAL</option>
<option value="IM">IMPORT</option>
</select>
Jquery:
$('#shiptype').change(function () {
var selectedValue = $(this).val();
var strloc = "LOCAL";
var strimp = "IMPORT";
if (selectedValue == "LOC") {
$('#strkey').val(selectedValue);
} else if (selectedValue == "IM") {
$('#strkey').val(selectedValue);
}
});
Text Field:
<input type='text' id='strkey' name='keyname' />
Display the value:
$key = $_POST['keyname'];
echo $key;
Please try this code :
HTML file contains this below code. File name test.html.
Form to submit your data.
<form id="frm_post">
<select name='shiptype' id='shiptype'>
<option value="0">Please select...</option>
<option value="LOC">LOCAL</option>
<option value="IM">IMPORT</option>
</select>
<input type="text" name="name" id="strkey">
<input id="btn_post" type="button" name="submit" value="Submit">
</form>
This is a div for your output.
<div>
<p id="output"></p>
</div>
This is jquery for ajax call function.
<script>
$(document).ready(function(){
$('#shiptype').change(function() {
var selectedValue = $(this).val();
var strloc = "LOCAL";
var strimp = "IMPORT";
if (selectedValue == "LOC") {
$('#strkey').val(selectedValue);
//alert($('#strkey').val());
} else if (selectedValue == "IM") {
$('#strkey').val(selectedValue);
//alert($('#strkey').val());
}
});
$("#btn_post").click(function(){
var parm = $("#frm_post").serializeArray();
$.ajax({
type: 'POST',
url: 'your.php',
data: parm,
success: function (data,status,xhr) {
console.info(data);
$( "#output" ).html(data);
},
error: function (error) {
console.info("Error post : "+error);
$( "#output" ).html(error);
}
});
});
});
</script>
And for PHP File to get the post value like this below. File name your.php.
<?php
// $key = $_POST['keyname'];
// echo $key;
print_r($_POST);
?>
Your post result will be show up in output id. Hope this help you out. :D

ReferenceError: data is not defined or 403 Forbidden

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.

Get the results of a form to a div without opening the results new page

How can I get the results of the result.php into the welcome div using ajax or any other method to prevent loading a new page?
<div id="welcome">
<form action="result.php" method="post">
<input type="hidden" id="date" name="selected"/>
<select id="city" class="cities" data-role="none" name="City">
<option value="">Anyplace</option>
.
.
.
</select>
<select id="type" class="cities" data-role="none" name="Event">
<option value="">Anything</option>
.
.
.
</select>
<input type="submit" class="button" value="Ok Go!"/>
<input id="current" name="current" type="hidden"/>​
</form>
</div>
If you are doing this through AJAX, then there is no need for the <form> codes. The <form> codes are only useful if you are posting to a different page and expecting the view to change/refresh anyways.
Also, using <form> codes in this example will cause the page to refresh (and values inserted by jQuery to be lost) for the additional bit with the "Set value for hidden field CURRENT" button. Not that it likely matters in your real world app, but just FYI.
Ajax goes in your javascript code, and looks like this:
$('#mySelect').change(function() {
var sel = $(this).val();
//alert('You picked: ' + sel);
$.ajax({
type: "POST",
url: "your_php_file.php",
data: 'theOption=' + sel,
success: function(whatigot) {
alert('Server-side response: ' + whatigot);
} //END success fn
}); //END $.ajax
}); //END dropdown change event
Note that the data ECHO 'd from the PHP file comes into your HTML document in the success function of the AJAX call, and must be dealt with there. So that's where you insert the received data into the DOM.
For example, suppose your HTML document has a DIV with the id="myDiv". To insert the data from PHP into the HTML document, replace the line: alert('Server-side response: ' + whatigot); with this:
$('#myDiv').html(whatIgot);
Presto! Your DIV now contains the data echoed from the PHP file.
Here is a working solution for your own example, using AJAX:
HTML MARKUP:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#mybutt').on('click', function(e){
e.preventDefault(); //prevent default action
var ct = $('#city').val();
var dt = $('#date').val()
var ty = $('#type').val();
var curr = $('#current').val();
$.ajax({
url: 'result.php',
type: 'POST',
data: 'ct=' +ct+ '&dat=' +dt+ '&t=' +ty+ '&curr=' +curr,
success: function(response){
$('#welcome').html(response);
}
});
});
$('#mycurr').click(function(){
var resp = prompt("Please type something:","Your name");
$('#current').val(resp);
});
}); //END $(document).ready()
</script>
</head>
<body>
<div id="welcome">
<input type="hidden" id="date" name="selected"/>
<select id="city" class="cities" data-role="none" name="City">
<option value="sumwhere">Anyplace</option>
<option value="anutherwhere">Another place</option>
</select>
<select id="type" class="cities" data-role="none" name="Event">
<option value="sumthing">Anything</option>
<option value="anutherthing">Another thing</option>
</select>
<input type="submit" id="mybutt" class="button" value="Ok Go!"/>
<input type="submit" id="mycurr" class="button" value="Set value for hidden field CURRENT"/>
<input id="current" name="current" type="hidden"/>
</div>
</body>
</html>
PHP Processor file: result.php
$ct = $_POST['ct'];
$date = $_POST['dat'];
$typ = $_POST['t'];
$cu = $_POST['curr'];
if ($date == '') {
$date = 'Some other date';
}
$r = '<h1>Results sent from PHP</h1>';
$r .= 'Selected city is: [' .$ct. ']<br />';
$r .= 'Selected date is: [' .$date. ']<br />';
$r .= 'Selected type is: [' .$typ. ']<br />';
$r .= 'Hidden field #CURRENT is: [' .$cu. ']<br />';
$r .= '<h2>And that\'s all she wrote....</h2>';
echo $r;
You can do something like this using jQuery Ajax
Use following code inside your head tag or footer
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type='text/javascript>
$('document').ready(function(){ //after page load
$('.button').on('click', function(e){
e.preventDefault(); //prevent default action
$.ajax({
'url': 'result.php',
'type: 'POST',
'success': function(response){
$('#welcome').html(response);
}
});
});
});
</script>
valit's the action="result.php" who makes your page reload
You shloud try to give an id to your form, and using a simple ajax call :
$("#formId").submit(function() {
$.ajax({
url: 'result.php',
success: function(response) {
$("#welcome").setValue(response); // update the DIV
}
});
return false; // prevent form submitting
});
Cheers

Error posting form values using jQuery in PHP

I have made a simple page which uses jquerydatepicker, two dropdown comboboxes for selecting time values. I tried to post the values but the page gets redirected to itself with selected values shown in url and I get no values on the receiver page.
Here's the script:
<script type="text/javascript">
$(document).ready(function(){
var jQueryDatePicker1Opts = {
dateFormat: 'mm/dd/yy',
changeMonth: false,
changeYear: false,
showButtonPanel: true,
showAnim: 'fadeIn'
};
$("#jQueryDatePicker1").datepicker(jQueryDatePicker1Opts);
$("#jQueryDatePicker1").datepicker("setDate", "new Date()");
$('#submit').click(function() {
var startTime = parseInt($('#Combobox1 option:selected').text());
var endTime = parseInt($('#Combobox2 option:selected').text());
if(startTime>=endTime){
alert("End Time should not be less than Start Time !");
return false;
}
});
$("#Campaign_form").submit(function(){
$.post({type:'POST', url:'campaigndata.php' ,
data:$('#Campaign_form').serialize(), success: function(response) {
$('#Campaign_form').find('.form_result').html(response);
}});
var isValid = $.validate.form(this);
return isValid;
});
});
</script>
Here is the form script:
<form name="Campaign_form" id="Campaign_form" >
<input type="text" id="jQueryDatePicker1" name="jQueryDatePicker1" value="06/09/2012">
<select name="StartTime" size="1" id="Combobox1" >
<option value="1">01:00</option>
...
<option value="24">23:00</option>
</select>
<select name="EndTime" size="1" id="Combobox2" >
<option value="1">01:00</option>
...
<option value="24">00:00</option>
</select>
<select name="SelectApp" size="1" id="Combobox3" >
<?php
while($row = mysql_fetch_array($result)){
echo "<option value =".$row['AppName'].">".$row['AppName']."</option>";
}
?>
</select>
<input type="submit" id="submit" name="submit" value="submit" >
</form>
Here is the campaigndata.php script:
<?php
$campaignDate = $_POST['jQueryDatePicker1'];
$camp_Start_Time = mysql_real_escape_string($_POST['StartTime']);
$camp_End_Time = mysql_real_escape_string($_POST['EndTime']);
$campaignID = $appid.$campaignDate.$camp_Start_Time ;
?>
This campaigndata.php shows null values on echoing above php variables.
You need to connect to your database before you can use mysql_real_escape_string() and change the form method to post.
You have to return false if you don't refresh page by submitting form
$("#Campaign_form").submit(function () {
var isValid = $.validate.form(this);
if (isValid)
$.post({type:'POST', url:'campaigndata.php',
data:$('#Campaign_form').serialize(), success:function (response) {
$('#Campaign_form').find('.form_result').html(response);
}});
return false;
});
ur answers helped me a lot !!! i figured out the problem was in capaigndata.php
i was using mysql_real_escape_string() before $_POST[''] ;
which was creating problems .
I removed those and used normal $_POST[] and it worked magically !!! :)

How to Inform user about ajax submission?

add.php - html markup.
dbadd.php - serverside script,
addpg.js - clientside including AJAX
RSV- form validator
I'm trying to do following: First validate the form (with RSV), if all things right, Then ajax submit (That's why i'm using myOnComplete). Inform user about submission. If user pressed for the first time save button then insert into db. Else update db.
The problems are:
It inserts data into db table but doesn't inform about succes or error
I can't figure out how to insert data into db If user pressed for
the first time save button or update data.
Tried all possible ways. There is no error. Please anyone help me to fix that.
addpg.js
function myOnComplete() {
return true;
}
$(document).ready(function () {
$("#add_form").RSV({
onCompleteHandler: myOnComplete,
rules: [
"required,name,Name field required.",
"required,title,Title field required.",
"required,menu, Menu field required",
"required,parentcheck,Parentcheck required",
"if:parentcheck=1,required,parent,Parent required",
"required,content,Page content field required"
]
});
});
$("#submit_btn").click(function () {
CKEDITOR.instances.content.updateElement();
$("#add_form").submit(function (e) {
e.preventDefault();
dataString = $("#add_form").serialize();
$.ajax({
type: "POST",
url: "processor/dbadd.php",
data: dataString,
dataType: "json",
success: function (result, status, xResponse) {
//do something if ajax call is success
var message = xResponse.getResponseHeader("msg");
var err = xResponse.getResponseHeader("err");
if (message != null) {
//do what you like with the message
}
if (err != null) {
//do what you like with the erro
}
},
error: function (e) {
//ajax call failed
alert(e);
}
});
});
});
dbadd.php
<?php
require '../../core/includes/common.php';
$name=filter($_POST['name'], $db);
$title=filter($_POST['title'], $db);
$parentcheck=filter($_POST['parentcheck'],$db);
if(isset ($_POST['parent'])) $parent=filter($_POST['parent'],$db);
else $parent=$parentcheck;
$menu=filter($_POST['menu'], $db);
$content = $db->escape_string($_POST['content']);
$result=$db->query("INSERT INTO menu (parent, name, showinmenu) VALUES ('$parent', '$name', '$menu')") or die($db->error);
$new_id = $db->insert_id;
$result2=$db->query("INSERT INTO pages (id, title, content) VALUES ('$new_id', '$title', '$content')") or die($db->error);
if ($new_id>0){
echo "{";
echo '"msg": "All right" ';
echo "}";
}else{
echo "{";
echo
'"err": "error"';
echo "}";
}
?>
add.php
<div id="add">
<form id="add_form" method="" action="">
<input type="text" name="name" id="name" size="40" value="" class="text-input" />
<input type="text" name="title" id="title" size="40" value="" class="text-input" />
<select name="menu" id="menu">
<option value="" selected="selected">sample</option>
<option value="1">sample 1</option>
<option value="2">sample 2</option>
<option value="0">sample 3</option>
</select>
<input type="radio" class="parentcheck" name="parentcheck" value="0"/>
<input type="radio" class="parentcheck" name="parentcheck" value="1"/>
<select name="parent" id="parent"></select>
<textarea id="content" style="width:100%" name="content"></textarea>
<input type="submit" name="submit" class="button" id="submit_btn" value="Save" />
</form>
</div>
<script type="text/javascript" src="../../core/includes/ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="../../core/scripts/admin/addpg.js"></script>
<script type="text/javascript" src="../../core/scripts/admin/rsv.js"></script>
For the first problem:
Without actually running the code or seeing a live example, I can't say for sure, but it looks like you have the right idea and it's just a syntax/usage error. For example:
var message = xResponse.getResponseHeader("msg");
var err = xResponse.getResponseHeader("err");
Someone please scold me if I'm wrong, but aren't "msg" and "err" found in the JSON (result) rather than in xResponse? result.msg (or result["msg"]) and result.err (or result["err"])
If so, also be aware that I -believe- you will get an 'undefined' error when trying to declare both of those variables since only one of them will be present. You might want to wrap them in try/catch blocks.

Categories