Ajax form not submitting - ajax

I followed the Submit Ajax Form tutorial on tutsplus.com ,
but cannot figure out for the life of me why my data won't have addreply.php applied to it. When I look in my mysql table, the data does not get inserted. Any help would be greatly appreciated. I searched the web and have troubleshooted for many hours.
$(document).ready(function() {
$(".replyLink").one("click", function(){
$(this).parent().after("<div id='contact_form'></div>");
$("#contact_form").append("<form id='replyForm'></form>");
$("#replyForm").append("<input class='enterName' id='enterName' type='text'
name='name' placeholder='name' rows='1' cols='20' />");
$("#replyForm").append("<textarea class='enterReply' id='enterReply' name='comment'
placeholder='reply'></textarea>");
$("#replyForm").append("<input type='hidden' name='id' value=''>");
commentID= $(this).parent().attr('id');
$("#replyForm").append("<input class='replyButton' id='replyButton' type='submit' `value='reply'/>");`
$(".enterReply").slideDown();
$(".replyButton").slideDown();
});
$(".replyButton").click(function() {
var name = $("input#enterName").val();
var reply = $("textarea#enterReply").val();
var dataString = 'name='+ name.val() + '&comment=' + reply.val();
$.ajax({
type: "POST",
url: "addreply.php",
data: dataString,
success: function() {
}
});
return false;
});
**addreply.php**
<?php
session_start();
$replyID= $_POST['id'];
$name= $_POST['name'];
$comment= $_POST['comment'];
$type= $_POST['type'];
$song= $_POST['song'];
if($song == ''){
$song= 'not';
}
include 'connection.php';
if($_SESSION['signed_in'] == 'yes') {
$query1= "INSERT INTO ApprovedComments(name, comment, Authorized, type, reply_ID, song, date)
VALUES('$name', '$comment', 'YES', '$type', '$replyID', '$song', NOW());";
$insertComment= mysql_query($query1);
// echo "hi";
}
if( !isset($_SESSION['signed_in']) ) {
$query2= "INSERT INTO PreApprovedComments(name, comment, reply_ID, song, date)
VALUES('$name', '$comment', '$replyID', '$song', NOW());";
$insertComment= mysql_query($query2);
}
mysql_close();
?>

Try
$.ajax({
type: "POST",
url: "addreply.php",
data: $("#replyForm").serialize()+'name='+ encodeURIComponent(name) +
'&comment=' + encodeURIComponent(reply),
success: function() {
}
});
this will post all the fields in the #replyForm form and the name and comment fields.

Related

Bootstrap Select 'refresh" continues to add new options instead of removing the old ones

Any help here would be appreciated as I can't see what I'm doing wrong.
I have an empty select picker:
<select class='selectpicker' name='new_teamid' id='new_teamid' style='width:200px;margin-left:-5px;margin-top:0px;' required></select>
This is being populated via AJAX call when another select box option has changed
var query_parameter = document.getElementById("new_deptid").value;
var dataString = 'dept=' + query_parameter;
// AJAX code to execute query and get back to same page with table content without reloading the page.
$.ajax({
type: "POST",
url: "helpers/populateteams.php",
data: dataString,
cache: false,
success: function(html) {
document.getElementById("new_teamid").innerHTML=html;
$('#new_teamid').selectpicker('refresh');
}
});
As you can see, its calling another php page which returns an HTMl string for the options. This works, if i inspect the element, the HTML options are updated correctly. im using = not +=. Problem is, the selectpicker is not removing the previous items. It just keeps adding the new items.
Any idea what I may be doing wrong here?
If you are curious, this is the populateteams.php
$theHTML = "";
$theHTML .= '<option value="" selected>Please Select</option>';
$sql = "SELECT * FROM tool_teams WHERE (dept_id=?) ORDER BY teamname asc";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $dept_id);
if ($stmt->execute() === TRUE) {
$result = $stmt->get_result();
if(!empty($result) && $result->num_rows)
{
while ($row = mysqli_fetch_array($result))
{
$theHTML .= '<option value="'.$row['team_id'].'">'.$row['teamname'].'</option>';
}
}
}
echo $theHTML;
resolved this myself. This is dumb, but this is how you need to do it:
$.ajax({
type: "POST",
url: "helpers/populateteams.php",
data: dataString,
cache: false,
success: function(html) {
document.getElementById("new_teamid").innerHTML=html;
$('#new_teamid').selectpicker('destroy');
$('#new_teamid').selectpicker('render');
},
complete: function(html) {
}
});
You need to destroy and render instead of refresh. This is stupid. But it works

Can't send post data from ajax

I have game.php file have this text input which sending three values to javascript:
<script src="js/jq.js"></script>
<script src="js/main.js"></script>
<input type="text" name="textfield2" id="textfield2" onkeyup="home(this.value,<?php echo $uid ?>,<?php echo $row_g['id'] ?>)" />
the javascript is :
function home(homeex,uid,mid){
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "inuphome.php",
data: { homeex: homeex, uid: uid, mid: mid },
success: function (result) {
}
});
}
inuphome.php file try to insert or update received data :
<?php
require_once('connections/connect.php');
$homeex=$_POST['homeex'];
$uid=$_POST['uid'];
$mid=$_POST['mid'];
$exp="SELECT * FROM expects Where uid='$uid' and mid='$mid'";
$result_ex=mysqli_query($berikane,$exp);
$row_ex=mysqli_fetch_assoc($result_ex);
$count = mysqli_num_rows($result_ex);
if ($count==0){
$query = "INSERT INTO expects VALUES ('','$uid','$mid','$homeex','','')";
mysqli_query($berikane,$query);
}
else{
$query = "UPDATE expects SET homeex='$homeex' where uid='$uid' and mid='$mid'";
}
?>
but nothing happens ,how can i solve this , best regards.

How to add value in a $.ajax url in CakePHP 2

Im trying to use ajax to sent request. I have CartsController and a method add. Please help!
<?php
echo $this->Html->link('Add', array('controller'=>'carts',
'action'=>'add', 'product_id'=>$product['Product']['id']),
array('class'=>'btn btn-primary col-md-offset-4',
'data-product-id'=>$product['Product']['id']));
?>
$('a.btn').on('click', function(e){
var this = $(this);
var product_id = this.data('product-id');
this.html('Item Added');
$.ajax({
url: '/cartphp_cart/carts/add/',
type: 'POST',
data: {product_id: product_id},
success: function(count) {
$('#number-of-items').text(' ' + count);
console.log(count);
}
});
e.preventDefault();
});
If the ajax request is OK, than in your add method of CartsController
you can get it by
if ($this->request->is('post') || $this->request->is('put')) {
debug($this->request->data['product_id'])
}
You should be able to access the data you've put in your ajax request by
if( $this->request->is('ajax') ) {
pr($this->request->data['product_id']);
// Or try printing the whole $this->request->data if you need other items.
}

ajax success method not showing data in asp.net mvc

I am working on as asp.net application. Its view has a button like this:
<input type="button" id="btnCall" title="Call" value="Call" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" />
and in document.ready, I have this:
$("#btnCall").click(function () {
alert("here");
$.ajax({
type: "POST",
dataType: "text/json",
url: "/account/getGenericPassword",
success: function (data) {
alert("data" + data);
if (data == null || data == "") {
alert("Generic Password is empty. Please enter generic password");
}
else {
//saveCallRecording();
}
}
});
});
and method is like this:
[Authorize]
public JsonResult GetGenericPassword() {
using (IUserProfileManager profilemanager = new ManagerFactory().GetUserProfileManager()) {
UserProfile profile = profilemanager.GetProfile(CurrentUser.Id, CurrentAccount.Id);
return Json(profile.GenericPassword == null ? "" : profile.GenericPassword, JsonRequestBehavior.AllowGet);
}
}
but alert in success is not shown. Please suggest solution.
Try setting the dataType like so:
dataType: "json"
See the valid dataType options at http://api.jquery.com/jQuery.ajax/
try with these
type:'Post',
url:'#Url.Action("actionname","controller")',
datatype:"json",
data:{},
success:function(data){
}

Jquery and ajax

I am quite new to JS and JQ so I am ask this basic question. I have code like this:
$(".delete").click(function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('1500', function() {$(this).remove();
$('#messages').fadeOut('1000');
});
}
});
return false;
});
For now it is working like it should. But I want to add something more. Div with id #messages contains all messages, and I wish that upon deleting message it fadeout(it is working) and then load new data and present all messages again without the deleted one.
Also, there is a counter that counts unread messages, and I created separate page for ajax purpose, but I don't know how to go on from fadeOut.
This is the code from the seperate page:
<?php if(isset ($messages)) { ?>
<?php foreach ($messages as $msg){ ?>
<div class="col_3">
<?php
if($msg['read'] == 0){ echo 'Status of message: Unreaded';}
elseif($msg['read'] == 1){echo 'Status of message: Readed';}
echo "<p>Message from: $msg[name]</p>";
echo "<p>Sender email: $msg[email]</p>";
echo "<p>Message: <br />$msg[message]</p>"; ?>
Delete message
</div>
I edited code a bit, but still nothing.
$(".delete").click(function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('600', function() {$(this).remove();
$('.messages').fadeOut('2000', function(){$(this).remove();
$('#messages').load("<?php echo site_url('messages/show') ?>").show().fadeIn('1000');
});
});
}
});
return false;
});
When I look page source I can see that the content has been changed, but it is not displayed.
I didn't quite understand what you are trying to do but if this is what you mean by saying but I don't know how to go on from fadeOut you can put a callback function to fadeOut
$('#messages').fadeOut('1000', function () {
// Do something here
);

Resources