Javascript function not functioning - javascript

Ok so i have a little problem with something.
I have a javascript/DOM script that submits a user comment to a php page via ajax, and there it works excellent.
But now i need to implement it on another page, a little differently. And can't seam to make it work . Would appreciate if someone could help me point my errors.
HTML part:
<form name="comment-form-<?php echo $comment['comment_id'];?>" id="comment-form-<?php echo $comment['comment_id'];?>" method="POST">
<div id="comments-approval">
<h1><?php echo $article['naslov'];?></h1>
<h2><?php echo $comment['comment_text'];?></h2>
<h3>[<?php echo date('d\. m\. Y\. H:i', $comment['comment_time']);?>] --- [ <?php echo $comment['comment_name'];?> ]</h3>
</div>
<input type="hidden" name="article_id" id="article_id" value="<?php echo $comment['comment_article_id'];?>" />
<input type="submit" value="✗" onclick="remove_comment('comment-form-<?php echo $comment['comment_id'];?>'); return false;" /> <!-- IKS -->
<input type="submit" value="✔" onclick="add_comment('comment-form-<?php echo $comment['comment_id'];?>'); return false;" /> <!-- OTKACENO -->
</form>
After the php foreach there are N-number of forms created, and every form has it's own unique ID
After that the moderator clicks on the button and calls the function ether ADD or REMOVE which send through the form ID in which the buttons are located.
The javascript part:
function add_comment(formid){
var target = String('"#'+formid+'"');
$(target).submit(function(){
$.ajax({
type: "POST",
url: "approvecomment.php",
data: $(this).serialize(),
dataType: 'text',
success: function(msg){
switch(msg) {
//message
}
}
});
return false;
});
}
I know that maybe it's a dumb mistake but i really don't have a clue what am I doing wrong.
EDIT:
Javascript part:
function add_comment(formid){
var target = '#'+formid;
alert(target);
$(target).submit(function(){
alert($(this).serialize());
$.ajax({
type: "POST",
url: "approvecomment.php",
data: $(this).serialize(),
dataType: 'text',
success: function(msg){
switch(msg) {
//message
}
}
});
return false;
});
}
Ok, so the first alert posts #comment-form-1
And the second does nothing.
and the form with the ID comment-form-1 exists in the document.

If you're already using JQuery - why not just bind the submit buttons to JQuery's .click() handler instead of hard coding it in the HTML itself?
(Note that I'm assuming your AJAX function for removing comments is "removecomment.php")
Updated HTML:
<form name="comment-form-<?php echo $comment['comment_id'];?>" id="comment-form-<?php echo $comment['comment_id'];?>" method="POST">
<div id="comments-approval">
<h1><?php echo $article['naslov'];?></h1>
<h2><?php echo $comment['comment_text'];?></h2>
<h3>[<?php echo date('d\. m\. Y\. H:i', $comment['comment_time']);?>] --- [ <?php echo $comment['comment_name'];?> ]</h3>
</div>
<input type="hidden" name="article_id" id="article_id" value="<?php echo $comment['comment_article_id'];?>" />
<input type="submit" class="comment-remove" value="✗" /> <!-- IKS -->
<input type="submit" class="comment-add" value="✔" /> <!-- OTKACENO -->
Updated JS:
//COMMENT ADD CLICK HANDLER
$("input.comment-add").click(function() {
$.ajax({
type: "POST",
url: "approvecomment.php",
data: $(this).parent().serialize(),
dataType: 'text',
success: function(msg){
switch(msg) {
//message
}
}
});
return false;
});
//COMMENT REMOVE CLICK HANDLER
$("input.comment-remove").click(function() {
$.ajax({
type: "POST",
url: "removecomment.php",
data: $(this).parent().serialize(),
dataType: 'text',
success: function(msg){
switch(msg) {
//message
}
}
});
return false;
});

Related

JavaScript Ajax and Mail/Ticket

I'm working on some project which there is a Bootstrap modal it sending tickets but I want also send email to the same person at the same time. But I'm missing something I guess.
<div class="modal-body">
<form onsubmit="return false" id="new_message_form" autocomplete="off">
<input type="hidden" name="form_type" value="new_message">
<input type="hidden" name="ticket_id" id="ticket_id" value="<?=$id;?>">
<div class="row">
<div class="col-md-12">
<div class="form-group no-margin">
<textarea class="ckeditor" id="message_new" name="message_new"></textarea>
</div>
</div>
</div>
</div>
<div class="modal-footer">
Close
<button id="ticket_message_add" class="btn <?=$this->Configs->get_info("theme_buttons");?>">Send</button>
</form>
and it sends it to admin.js
$("#ticket_message_update").click(function (){
CKEDITOR.instances['message_update'].updateElement();
$("#UpdateMessageModal").modal("hide");
$.post(base_admin+"support", $("#update_message_form").serialize() ,function(data){
var data= JSON.parse(data);
if(data.update== 1){
$('#update_message_form')[0].reset();
location.reload();
}
});
});
So here is the thing. I have fully working ajax form with php mail system.(PHPMailer on github) When I click send button it automatically sending email to target mail addresses. But when I try to merge the ticket and email system seems not working but in logic it should be.
I'm adding function on button/input fields
onclick="AjaxFunction();"
<button id="ticket_message_add" onclick="AjaxFunction();" class="btn <?=$this->Configs->get_info("theme_buttons");?>">Send</button>
and adding my script also;
<script>
function AjaxFunction() {
var bilgi = {
userid: $('#user').val(),
ad: $('#ticket_id').val(),
soyad: $('#message_new').val()
}
$.ajax({
type: 'post',
url: 'gonder.php',
data: {query: bilgi},
success: function(result) {
}
});
}
</script>
And it needs to send the variables to "gonder.php" right? But it doesn't. Apparently I'm missing something.
Hi try to send the data like this:
function AjaxFunction() {
var bilgi = [{
userid: $('#user').val(),
ad: $('#ticket_id').val(),
soyad: $('#message_new').val()
}];
$.ajax({
type: 'post',
url: 'gonder.php',
data: {query: JSON.stringify(bilgi)},
success: function(result) {
}
});
}
then on the server side:
<?php
$data = json_decode($_POST["query"]);
// will echo the JSON.stringified - string:
echo $_POST["query"];
// will echo the json_decode'd object
var_dump($data);
//traversing the whole object and accessing properties:
foreach($data as $cityObject){
echo "userid: " . $cityObject->userid. ", ad: " . $cityObject->ad. "<br/>";
}
?>
Hope it Helps

Send js value to php controller by ajax

I have this button
<button id="<?php echo $u['id']?>" name="activation" onclick="handleButton(this);" type="submit" class="btn btn-success"></button>
And this button related to this
<td id="<?php echo $u['id']?>"><?php echo $u['id']?></td>
I'm using this script to send value of button to my php controller
function handleButton(obj) {
var javascriptVariable = obj.id;
// alert (javascriptVariable);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: 'myname='+javascriptVariable,
success: function (data){
}
});
}
When I use alert, the result of javascriptVariable is correct and I want it in my controller so I'm trying in my controller to do this:
if(isset($_POST['activation']))
{
$name = $this->input->post('myname');
var_dump($name);
}
But I get null value, what is the wrong?
When you pass data from the browser via AJAX only the data you pass in the data: parameter is sent to the PHP script.
So if you want to test for activation in the PHP script you must actually send that parameter
Also see the amendment to the data: parameter creation below. Its easier to read and a lot easier to code correctly when passing more than one parameter as you dont have to remember &'s and + concatenation.
function handleButton(obj) {
obj.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: {activation: 1, myname: obj.id}, // add parameter
success: function (data){
alert(data);
}
});
}
Now the PHP will see 2 parameters in the $_POST array activation and myname
if(isset($_POST['activation']))
{
$name = $_POST['myname'];
var_dumb($name);
}
Or if you are using a framework which I assume you are
if(isset($this->input->post('activation')) {
$name = $this->input->post('myname');
var_dumb($name);
}
EDIT:
Spotted another issue your button has an attribute type="submit" this will cause the javascript to run AS WELL AS the form being submitted in the normal way.
Remove the type="submit" attribute and to be doubly sure that the form will not be submitted as well as the AJAX add a call to preventDefault(); as well before the AJAX call
Since the php script is conditioned by a second POST variable [if(isset($_POST['activation']))], you should post that as well.
function handleButton(obj) {
var javascriptVariable = obj.id;
// alert (javascriptVariable);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: 'myname='+javascriptVariable+'&activation=1',// <-- RIGHT HERE
success: function (data){
alert(data);
}
});
}
SIDE NOTE: you could also echo instead of dump the variable:
if(isset($_POST['activation']))
{
echo $this->input->post('myname');
}
Try this in your ajax function :
function handleButton(obj) {
var javascriptVariable = obj.id;
//alert (javascriptVariable);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: {myname: javascriptVariable},
success: function (data) {}
});
}
And in your PHP script, you can do $_POST['myname'] to get it (maybe $this->input->post('myname') can work, you can test it)
Look two id
<button id="<?php echo $u['id']?>" name="activation" onclick="handleButton(this);" type="submit" class="btn btn-success"></button>
AND
<td id="<?php echo $u['id']?>"><?php echo $u['id']?></td>
For both html elements id is same.It can not be used with in the same page.This may cause a problem for you...

Uncaught TypeError: Cannot read property 'html' of undefined - AJAX post answer only in spesific div

I have this error:
Uncaught TypeError: Cannot read property 'html' of undefined
What I'm trying to create is a voting system for each video on my page from a database. I've managed to make it with AJAX the only problem is that I can't output the answer in the correct div class 'this' because it gets posted in each div with the class - so in under every video.
I need a working solution to identify the parent div the user clicked vote button on and change only its own child bot others.
Please help. Here is my jQuery code.
$(function() {
$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var acdc = $('#ab').attr('class');
var potato = 'potato';
var parent = $(this);
if(name=='up')
{
$.ajax({
type: "POST",
url: "up_vote.php",
data: dataString,
cache: false,
success: function(html) { acdc.html(html);
}});
}
else
{
$(this).fadeIn(200).html('<img src="img/icon-down.png" align="absmiddle" style="height: 10px;width:10px;">');
$.ajax({
type: "POST",
url: "down_vote.php",
data: dataString,
cache: false,
success: function(html){
parent.parent().find('.this').html(html);
}});
}
return false;
});
});
here is html with video posts and div class'this' where my AJAX answer should be posted - but only in current one - as php script adds one vote to only the video with the spesific id, not all!
<div class='botto'>
<div class='icon-wrap'>
<form action="blossom.php" method="post"><?php $id = $row["idv"]; ?>
<input type="hidden" id="id" value="<?php echo $row['idv']; ?>" />
<div cass='homesick'>
<button type='submit'name='up' style="background-color:transparent; border-color:transparent;outline: none; " class='icon vote' name="up"><img src='img/thumbsup.png' alt='up' name='up' class='icon vote icon-up' id="<?php echo $row['idv']; ?>" ></button>
<span class='number-vote this'>
<?php
echo $row['votev'];
?></span>
<button type='submit' name='down' style="background-color:transparent; border-color:transparent;outline: none; " class="vote" name="down"><img src='img/icon-down.png' alt='down' class='icon icon-down vote' id="<?php echo $row['idv']; ?>"></button>
</div>
</form>
</div>
</div>
var acdc = $('#ab').attr('class') attempts to retrieve the string value of the attribute class, which in this case is resolving to undefined.
If you'd like to use the jQuery html method, you should do it on a DOM node, such as:
var acdcElement = $('#ab');
var html = acdcElement.html();

Submit form for php without refreshing page

I've search for many solution but without success.
I have a html form;
<form id="objectsForm" method="POST">
<input type="submit" name="objectsButton" id="objectsButton">
</form>
This is used for a menu button.
I'm using jquery to prevent the site from refreshing;
$('#objectsForm').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/php/objects.php',
data: $('#objectsForm').serialize(),
success: function () {
alert('success');
}
});
});
In my php file I try to echo text to the body of my site;
<?php
if (isset($_POST["objectsButton"])){
echo '<div id="success"><p>objects</p></div>';
} else {
echo '<div id="fail"><p>nope</p></div>';
}
?>
I know the path to my php file is correct, but it doesn't show anything? Not even the "fail div".
Does anyone has a solution for me?
Thanks in advance!
The success function takes two parameters. The first parameter is what is returned from the php file. Try changing it to:
success: function (xhr){ alert(xhr);}
Based in your php source..
$.ajax({
type: 'post',
dataType: "html", // Receive html content
url: '/php/objects.php',
data: $('#objectsForm').serialize(),
success: function (result) {
$('#divResult').html(result);
}
});
PHP scripts run on the server, that means any echo you do won't appear at the user's end.
Instead of echoing the html just echo a json encoded success/ failure flag e.g. 0 or 1.
You'll be able to get that value in your success function and use jQuery to place divs on the web page.
PHP:
<?php
if (isset($_POST["objectsButton"])){
echo json_encode(1); // for success
} else {
echo json_encode(0); // for failure
}
?>
jQuery:
var formData = $('#objectsForm').serializeArray();
formData.push({name:this.name, value:this.value });
$.ajax({
type: 'post',
url: '/php/objects.php',
dataType: 'json',
data: formData,
success: function (response) {
if (response == 1) {
alert('success');
} else {
alert('fail');
}
}
});
EDIT:
To include the button, try using the following (just before the $.ajax block, see above):
formData.push({name:this.name, value:this.value });
Also, have the value attribute for your button:
<input type="submit" name="objectsButton" value="objectsButton" id="objectsButton">

AJAX pass data to PHP

I've been searching this forum, but I had no good result. I have this HTML:
<form method="post" id="postform">
<input type="text" name="message" id="message" placeholder='Say "Hello!"' class="mymessage" maxlength="255"/>
<br />
<input id="submit" type="button" value="Send"/>
</form>
PHP:
<?php
include ('connect.php');
session_start();
if (isset($_POST['message'])){
mysql_query("INSERT INTO messages VALUES ('','".$_POST['message']."','".$_SESSION['user']."')");
}
?>
And jQuery:
$('#submit').click(
function(){
var message = $('#message').val();
$.ajax({
url: post.php,
type:'POST',
data: {"message":message}
});
});
I need to pass #message content to PHP without refreshig the page. This is what I've made, but it's not working.
Check your syntax:
Wrap url with quotes '
Remove single quotes around 'message' variable
$.ajax({
url: 'post.php',
type: 'POST',
data: {message : message}
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
See the first example of $.ajax() at the bottom of its documentation page.
I need to pass #message content to PHP without refreshig the page.
Handle form submit instead:
$("#postform").submit(function(){
var message = $('#message').val();
$.ajax({
url: 'post.php',
type:'POST',
data: {message:message}
}).done(function( data) {
// handle response from the server in case of success.
});
return false; //to prevent submitting and refreshing the page.
});

Categories