JavaScript Ajax and Mail/Ticket - javascript

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

Related

Why jQuery.ajax() is not sending any data?

Tell me please, there is a form for sending data to the database. Without a script it works fine, but nothing happens with the script. In the console — Form Data has all the data, and the 200th code arrives, but is not added to the database.
PHP:
<?php
$data = $_POST;
if (isset($data['add'])) {
$posts = R::dispense('posts');
$posts->head = $data['head'];
$posts->desc = $data['desc'];
R::store($posts);
}
?>
HTML:
<form method="POST" id="FormID">
<input type="text" name="head" required />
<input type="text" name="desc" required />
<button type="submit" name="add">Добавить</button>
JS:
<script>
$("#FormID").submit(function(e)
{
var form = $(this);
var url = form.attr('action');
e.preventDefault();
$.ajax({
type: "POST",
url: url,
data: $("#FormID").serialize(),
success: function(data)
{
c = "hello";
$('#FormStatus').text(c);
}
});
});
</script>
You said:
if (isset($data['add'])) {
So the code only does anything if add in the data.
<button type="submit" name="add">Добавить</button>
add is a submit button. It will be included in the data when you submit the form.
data: $("#FormID").serialize(),
You aren't submitting the form. jQuery serialize does not include submit buttons because they aren't successful controls when you aren't submitting the form.
Use some other mechanism to determine if there is data to process (such as the presence of head and desc.
You have forget the action for your form
Why don't simply use $data['name'] instead of R::dispense?
If you what to do a POST request why don't you use $.post()?
What you need is these:
PHP Code:
<?php
$data = $_POST;
if (isset($data['add'])) {
if(isset($data['head']) AND !empty($data['head']) AND isset($data['desc']) AND !empty($data['desc'])) {
$head = htmlspecialchars($data['head']);
$desc = htmlspecialchars($data['desc']);
echo "Hello from server";
}
else {
echo "Please fill the form";
}
}
?>
HTML:
<form method="POST" id="FormID" action="path_to_php_file.php">
<input type="text" name="head" required />
<input type="text" name="desc" required />
<button type="submit" name="add">Добавить</button>
</form>
JS:
<script>
$("#FormID").submit(function(e)
{
e.preventDefault();
var form = $(this),
url = form.attr('action');
var data = {};
// To have post paramaters like
// { 'head' : 'Head value', 'desc' : 'Desc value' }
$.each(form.serializeArray(), function(i, field) {
data[field.name] = field.value;
});
$.post(url, data, function(Responses) {
// Will write "Hello from server" in your console
console.log(Responses);
});
});
</script>

run full php-script in ajax/jquery

Sorry for my bad english. I'm trying to run a PHP function through an ajax script. The PHP script should run as a FULL NORMAL php script. My idea is to run a recaptcha by a Submit button WITHOUT refreshing the page. That is working, but I found no way to run a normal php script after that. Here is the part of my script.
php:
if( isset( $_REQUEST['startattack'] )){
$secret="********************";
$response=$_POST["g-recaptcha-response"];
$verify=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
$captcha_success=json_decode($verify);
if ($captcha_success->success==false) {
echo "<script type='text/javascript'>alert('failed!')</script>";
} else if ($captcha_success->success==true) {
echo "<script type='text/javascript'>alert('success!')</script>";
}
}
html:
<form method='post' id="myform">
<center>
<div class="g-recaptcha" data-sitekey="6LfETygTAAAAAMC7bQu5A3ZhlPv2KBrh8zIo_Nwa"></div>
</center>
<button type="submit" id="startattack" name="startattack" onclick="mycall()" class="btn btn-attack">Start Attack</button>
</form>
ajax:
<script>
$(function () {
$('button').bind('click', function (event) {
$.ajax({
type: 'POST',
url: 'post.php',
data: $('button').serialize(),
success: function () {
alert('button was submitted');
type: 'post';
url: 'post.php';
}
});
event.preventDefault();// using this page stop being refreshing
});
});
</script>
I want to check the recaptcha here. If correct, it should echo correct in PHP and I want to add feature later. The same with the false captcha.
I think you can simplify things a bit. You don't return the response in the Ajax is your main problem.
PHP:
Just echo the returned json from the recaptcha (although I have no idea where you get the g-recaptcha-response key/value, you are not sending it anywhere).
if(isset( $_POST['startattack'] )){
$secret = "********************";
// I have added a key/value in the ajax called "sitekey",
// this might be what you are trying to retrieve?
$response = $_POST["g-recaptcha-response"];
echo file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$secret}&response={$response}");
exit;
}
AJAX:
I think since the return from the recaptcha is json anyway, just echo it and pick it up on this side:
$(function () {
$('button').bind('click', function (event) {
var statusBlock = $('#status');
statusBlock.text('button was submitted');
$.ajax({
type: 'POST',
url: 'post.php',
data: {
// Not sure if you are trying to pass this key or not...
"sitekey":$('.g-recaptcha').data('sitekey'),
"startattack":true
},
success: function (response) {
var decode = JSON.parse(response);
var alertMsg = (decode.success)? 'Success' : 'Failed';
statusBlock.text('');
alert(alertMsg);
}
});
// using this page stop being refreshing
event.preventDefault();
});
});
Form:
Leave a spot to post the submit status so it doesn't interfere with the return alert dialog window.
<form method='post' id="myform">
<div id="status"></div>
<center>
<div class="g-recaptcha" data-sitekey="6LfETygTAAAAAMC7bQu5A3ZhlPv2KBrh8zIo_Nwa"></div>
</center>
<button type="submit" id="startattack" name="startattack" onclick="mycall()" class="btn btn-attack">Start Attack</button>
</form>

How to display error messages Jquery ajax?

I am a student and am using jquery and php to add records to database. Records are being added, but i want to display a message "Record inserted" in the if the the record has been successfully been added and an error message if an error occurs.
This is my html code:
<form id="forn-newsletter" class="form-horizontal" method="POST">
<div class="form-group">
<label id="name_label" class="control-label col-xs-2">Name</label>
<div class="col-xs-10">
<input type="text" class="form-control" id="news_name" name="news_name" placeholder="Name" onblur="checkName();"/><font color="red" id="name_error"></font>
</div>
</div>
<div class="form-group">
<label id="email_label" class="control-label col-xs-2">Email</label>
<div class="col-xs-10">
<input type="text" class="form-control" id="news_email" name="news_email" placeholder="Email" onblur="vali()"/><font color="red" id="email_error"></font>
</div>
</div>
<div class="form-group">
<div class="col-xs-offset-2 col-xs-10">
<button id="register-newsletter" type="submit" class="btn btn-primary">Register for Newsletter</button>
</div>
</div>
<div id="dialog"></div>
</form>
This is my registration-newsletter.php
<?php
include('connect.php');
$name=$_POST['name'];
$email=$_POST['email'];
$val=md5($name.$email);
$query = "INSERT INTO newsletter (Id,Name,Email,Val) VALUES('','$name','$email','$val')";
$result=mysql_query($query);
if(!$result){
echo "Some error Occured..Please try later";
}
else{
echo "Your details have been saved. Thank You ";
}
mysql_close($con);
?>
This is my JQuery code
$(document).ready(function(){
$("#register-newsletter").click(function(){
var name=$("#news_name").val();
var email=$("#news_email").val();
var dataString="name="+name+"&email="+email;
var request;
request = $.ajax({
url: "registration-newsletter.php",
type: "POST",
data: dataString
});
//return false;
});
});
Add a span to your html code for displaying error.
<span id="error"></span>
Already you are echoing the message from PHP page to ajax. You can do mysql_affected_rows() to check whether the query updated the table.
$result=mysql_query($query);
if(mysql_affected_rows()>0){ // return the number of records that are inserted
echo "Your details have been saved. Thank You "; // success
}
else{
echo "Some error Occured..Please try later"; // failure
}
exit;
Then you can simply show the echoed message in the span with id error as:
request = $.ajax({
url: "registration-newsletter.php",
type: "POST",
data: dataString,
success:function(response) // response from requested PHP page
{
$('#error').html(response); // set the message as html of span
}
});
$.ajax({
url: 'registration-newsletter.php',
type: 'post',
data: dataString ,
success: function (msg) {
alert(msg);
},
error:function(msg)
{
alert(msg);
}
});
jQuery.ajax({
url: "myfile.php",
type: "POST",
data: dataString,
success:function(response) /* this response is an array which is returning from the myfile.php */
{
$status = response['status'];
if($status == 'success')
{
$('#message').html(response['msg']);
}
else
{
$('#message').html(response['msg']);
}
}
});
The function which you have added success will handle the "text to be append" or "alert to be show". Its quite equal to if condition, If the response came successfully, It will go into the condition.
This is what worked for me for form submit (see those 2 parameters to .then function):
<span id="result">Loading...</span>
<div id="form">
<form>
<input id="personId"> <-- put personID here<br>
<input id="submit" type="submit" value="Generate">
</form>
</div>
<script type="application/javascript">
$(document).ready(function() {
var submit = $('#submit');
var res = $('#result');
$('#form').submit(function() {
submit.prop('disabled', true);
res.text("Sending message...");
$.ajax({
url: '/rest/message',
contentType: "application/json;charset=UTF-8",
method: "POST",
data: JSON.stringify({'personId': $('#personId').val()})
}).then(function(result) { // OK
res.text("Message was generated");
submit.prop('disabled', false);
}, function(reason) { // ERROR
res.css('color', 'red').css('font-weight','Bold');
res.text("An error has occurred: " + reason.responseJSON.message);
submit.prop('disabled', false);
});
return false; // prevent default action
});
});
</script>
error: function(xhr) {
alert(xhr.responseText);
}
You can also get the HTTP status code or the generic message sent by your server (such as "Internal Server Error") in this XHR object if needed. More info : https://api.jquery.com/jQuery.ajax/#jqXHR

$_POST variables not passed by form

I'm hosting a simple contact form on App Engine using PHP, trying to pass $_POST variables from a form to a PHP script that sends the email. As I can read from the logs, the $_POST variables don't seem to get through and I struggle to understand why... hence would appreciate another pair of eyes on this... thank you. Here are the various bits of (simplified) code:
Within index.html at the root:
<form method="post" action="#" id="contactform">
<div>
<label for="email">Enter your email</label>
<input type="text" class="input-field" id="email" name="email" value="">
</div>
<a id="button-send" href="#" title="Send Email" class="button" style="width:100%;">Send E-Mail</a>
<div id="success">Your message has been sent successfully!</div>
<div id="error">Unable to send your message, please try later.</div>
</form>
The PHP file, also at the root:
<?php
$send_email_to = "test#test.com";
$email_subject = "Email subject line";
function send_email($email,$email_message)
{
// using AppEngine's mail function here
}
function validate($email,$message)
{
// a simple validation function
}
if(isset($_POST['email'])) {
$email = $_POST['email']; // this doesn't seem to work
}
else
{$email = "email#email.com";} // did this to confirm the $_POST didn't seem to be passed
$return_array = validate($email,$message);
if($return_array['success'] == '1')
{
send_email(,$email,$message);
}
header('Content-type: text/json');
echo json_encode($return_array);
die();
?>
And the javascript that controls the error messages:
$('#button-send').click(function(event){
$('#button-send').html('Sending message...');
event.preventDefault();
$('html, body').scrollTo( $('#contact'), 'fast' );
$.ajax({
type: 'POST',
url: 'send_form_email.php',
data: $('#contact_form').serialize(),
success: function(html) {
if(html.success == '1')
{
$('#button-send').html('Send message');
$('#success').show();
}
else
{
$('#button-send').html('Send message');
$('#error').show();
}
},
error: function(){
$('#button-send').html('Send message');
$('#error').show();
}
});
And in case this has to do with App Engine, my app.yaml looks like this:
- url: /js
static_dir: js
- url: /send_form_email.php*
script: send_form_email.php
- url: .*
script: index.html
Many thanks again – I've also put the full code on my Google Drive: https://drive.google.com/file/d/0B4yzSrEzbZ5jbk1oc2RWb2xSRWM/edit?usp=sharing
You are trying to serialise #contact_form but you have id="contactform"
The MIME type for JSON is application/json, not text/json.

Javascript function not functioning

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;
});

Categories