I am new with jquery and ajax, so please be patient.
I have this link:
<a href="#message" style="text-decoration:none" class="common2 simple3" >Message</a>
that shows this pop up when clicked:
<div id="message" class="modalDialog">
<div>
<h3>Create A Message</h3>
<form id="msgForm" name="msgForm" action="#" method="post">
<textarea id = 'msgContent' cols="48" rows="10" ></textarea>
<br>
<div id="create_btn">
<a href='' id = 'send' class="common simple2" style='margin-left:50px;text-decoration: none;'>Send</a>
</div>
<div id="cancel_btn">
<a href="#close" class="common simple2" style='margin-left:40px;text-decoration: none;'>cancel</a>
</div>
</form>
</div>
</div>
when I entered text in the textarea and show its content by alert(msgContent) in the script below, it shows
$(document).ready(function()
{
$("#send").click(function(e)
{
e.preventDefault();
var msgContent = $("#msgContent").val();
alert(msgContent);
$.ajax({
url: 'message.php?message='+ msgContent,
type: 'GET',
dataType: 'json',
context: this,
success: function(result)
{
//if (result == true)
$(this).html('Send');
}
});
})
})
but when I try to pass it to a php page through ajax, it won't pass. What could be wrong?
this is message.php
$message = $_POST['message'];
$result = false;
$sql="INSERT INTO MESSAGE_LOG (sender,recepient, message)
VALUES($viewer,$viewed,$message)";
if (!mysqli_query($connection,$sql))
{
die('Error: ' . mysqli_error($connection));
}
You need to read the value from $_GET:
$message = $_GET['message'];
Or use the post method, with data attribute:
$(document).ready(function()
{
$("#send").click(function(e)
{
e.preventDefault();
var msgContent = $("#msgContent").val();
alert(msgContent);
$.ajax({
url: 'subscribe.php',
type: 'POST',
data: {message: msgContent},
//dataType: 'json', from your php I don't that that you are looking for json response...
context: this,
success: function(result)
{
//if (result == true)
$(this).html('Send');
}
});
})
})
Your JS should be this:
$(document).ready(function() {
$("#send").click(function(e) {
e.preventDefault();
var msgContent = $("#msgContent").val();
$.ajax({
url: 'message.php',
type: 'POST',
dataType: 'json',
data: {message: msgContent},
context: this,
success: function(result) {
alert('Message has been sent');
}
});
});
});
And your PHP this:
$message = $_POST['message'];
$result = false;
$sql="INSERT INTO MESSAGE_LOG (sender,recepient, message)
VALUES($viewer,$viewed,'$message')";
if (!mysqli_query($connection,$sql)) {
die('Error: ' . mysqli_error($connection));
}
Related
I have a form on my front-end and when the submit button is clicked I want to send the details to my get-emp.php file without page reload.
The code looks like this:
index.html
<form class="form-emp-details hide" action="">
<div class="form-group">
<label for="">First name:</label>
<input type="text" class="form-control input-emp-firstname" name="input_emp_firstname">
</div>
<div class="form-group">
<label for="">Last name:</label>
<input type="text" class="form-control input-emp-lastname" name="input_emp_lastname">
</div>
<div class="form-group">
<label></label>
<button type="submit" class="btn btn-default btn-submit-1" name="submit_emp_details">Save</button>
</div>
</form>
custom.js
$(".form-emp-details").("submit", function(e) {
var input_first_name = $(".input-emp-firstname").val();
$.ajax({
type: "POST",
url: "get-emp.php",
data: {
input_emp_firstname:input_first_name,
},
success: function(data) {
console.log(data)
},
error: function(xhr,status,error) {
console.log(error);
}
});
});
get-emp.php
if(isset($_POST['submit_emp_details'])) {
$firstname = $_POST['input_emp_firstname'];
echo $firstname;
}
I want to display the submitted form data on get-emp.php file but it seems that I am not able to detect the submitted button and echo the form data on.
My goal is to capture all form data with a single request variable or identifier $_POST['submit_emp_details']
Any help is greatly appreciated. Thanks
$("#MyformId").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(),
success: function(data)
{
// success..
}
});
});
You passing the POST data of firstname and lastname by:
input_emp_firstname
input_emp_lastname
so, you need to change the $_POST['submit_emp_details'] to $_POST['input_emp_firstname'] on file get-emp.php to
<?php
if(isset($_POST['input_emp_firstname'])) {
$firstname = $_POST['input_emp_firstname'];
echo $firstname;
}
Edit 2:
$.ajax({
type: "POST",
url: "get-emp.php",
cache: false,
data: {
submit_emp_details: {
input_emp_firstname:input_first_name,
input_emp_lastname:input_last_name
}
},
success: function(data) {
console.log(data)
},
error: function(xhr,status,error) {
console.log(error);
}
});
I am trying to hide the submit button if the email is the same with the one in the database from action.php. How could I implement this in my following code:
<form onsubmit="return submitdata();">
<input type="text" id="mail">
<input type="submit" value="Check">
</form>
<p id="msg"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function submitdata()
{
var name=document.getElementById('mail').value;
$.ajax({
type: 'post',
url: 'action.php',
dataType: 'text',
data: {
'name':name
},
cache:false,
success: function (data) {
console.log(data);
$('#msg').html(data);
}
});
return false;
}
</script>
action.php:
<?php
require_once 'config.php';
$email_ck=$_POST['name'];
if(extract($crud->get_email($email_ck))){
echo "Response: ".$email;
$hide = 1;
}else{
echo 'hmmmm';
}
?>
When the email coincide I get the correct message, but how could I call back $hide to determine to hide my submit button?
Instead of returning a message, return an indication.
(In the JS script write the message accordingly)
A detailed json string would be a good idea but for simplification see the following.
PHP:
<?php
require_once 'config.php';
$email_ck=$_POST['name'];
if(extract($crud->get_email($email_ck))){
echo "already_exists";
}else{
echo 'not_exists';
}
?>
JS:
$.ajax({
type: 'post',
url: 'action.php',
dataType: 'text',
data: {
'name':name
},
cache:false,
success: function (data) {
if(data == 'already_exists'){
$('#buttonId').hide();
} else if(data == 'not_exists'){
$('#msg').html('Response: ' +name);
}
}
});
I can't get the ajax response when submitting a modal dialog form. It works perfectly when the form is not modal.
The form:
<div id="form2" style="display: none">
<form id="objectInsert" action="element/create" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="name">Name</label>
<input class="form-control" type="text" name="name" id="name"/>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" name="description"></textarea>
</div>
</form>
Here i get the ajax success part in the console!
$("#objectInsert").submit(function(e) {
e.preventDefault();
resetErrors();
var form = this;
var url = $(this).attr('action');
var data = new FormData($(this)[0]);
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
cahe:false,
processData: false,
contentType: false,
success: function(resp) {
console.log(resp);//Working
},
error: function() {
console.log('there was a problem checking the fields');
}
});
});
Here i get the ajax error part in the console! can someone tell me where i'm doing wrong?
$("#add_element").click(function(){
$("#form2").dialog({
modal:true,
width:400,
buttons:{
Send:function(e){
e.preventDefault();
var form = $("#objectInsert");
var url = form.attr('action');
var data = new FormData(form[0]);
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
cahe:false,
processData: false,
contentType: false,
success: function(resp) {
console.log(resp);//not working
},
error: function(xhr, status, error) {
console.log('there was a problem checking the fields');
console.log(xhr);
console.log(error);
}
});
return false;
},
Cancel:function(){
$(this).dialog("close");
}
}
});
});
The controller
public function create() {
try{
$this->form = new Form();
$this->form->post('name');
$this->form->val('isEmpty', 'name');
$this->form->post('description');
$this->form->val('isEmpty', 'description');
$this->form->fetch();
$this->form->submit();
$data = $this->form->get_postData();
$this->model->insert($data);
echo json_encode('success');
} catch (Exception $ex) {
$errors = $this->form->get_error();
$_SESSION["errors"] = $errors;
//This is for ajax requests:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])
== 'xmlhttprequest') {
echo json_encode($_SESSION['errors']);
exit;
}
foreach ($_SESSION["errors"] as $errors){
echo $errors;
echo '<br/>';
}exit;
}
}
see this code you have not closed the function block
success: function(resp) {
console.log(resp);//not working
},//This is not closed for success function
error: function() {
console.log('there was a problem checking the fields');
}
I have this Div which includes the users messages where the newest message is right at the very bottom of the Div and initiates a scroll bar if the messages start to go lower than the div height:
<div class="list-group-message" style="overflow-y: scroll;height:385px;width:680px">
<div id="content">
/// My messages
</div>
</div>
And I am using Jquery from my js folder to bring the scroll bar to the bottom of the messages on Page load to show the newest message:
var $content = jQuery(".list-group-message");
$content.scrollTop($content[0].scrollHeight);
This works well, unless a new message is added to the page, the scroll bar won't automatically scroll down again unless you refresh the page or unless you add a new message. So you have to manually scroll down everytime you get a new message.
I am using an automatic Div reload script to show new messages:
<script>
setInterval(function() {
$("#content").load(location.href+" #content","");
}, 5000);
</script>
And I am using this Ajax script to add new replies:
<script>
function loadDoc() {
$.ajax({
url: 'system/reply_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
})
.done(function() {
$.ajax({
url: 'system/sars_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
})
.fail(function() {
console.log("error");
})
}
</script>
Is there a way I can set up the Jquery to run on success of my Ajax so that the scroll bar will be sent to the bottom upon a new message, something like this, which I have tried and found it doesn't work:
<script>
function loadDoc() {
$.ajax({
url: 'system/reply_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
})
.done(function() {
var $content = jQuery(".list-group-message");
$content.scrollTop($content[0].scrollHeight);
$.ajax({
url: 'system/sars_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
})
.done(function() {
console.log("success");
var $content = jQuery(".list-group-message");
$content.scrollTop($content[0].scrollHeight);
})
.fail(function() {
console.log("error");
})
})
.fail(function() {
console.log("error");
})
}
</script>
Additional code included as requested:
<div class="list-group-message" style="overflow-y: scroll;height:385px;width:680px">
<div id="content">
<?
$res6=mysqli_query($conn, "SELECT * FROM ap_messages WHERE conversation_id = '$conversation_id' ORDER BY time_sent ASC");
while($row6=mysqli_fetch_array($res6))
{
$me_message = $row6['message'];
$me_message_id = $row6['message_id'];
$me_sender_id = $row6['sender_id'];
$todaysdate = date('d/m/Y');
$me_time_sent_date = date('d/m/Y', strtotime($row6['time_sent']));
$me_time_sent_date_and_time = date('d/m/Y H:i:s', strtotime($row6['time_sent']));
$me_time_sent_time = date('H:i', strtotime($row6['time_sent']));
if($todaysdate == $me_time_sent_date){
$me_time = ''.$me_time_sent_time.'';
} else {
$me_time = ''.$me_time_sent_date.' '.$me_time_sent_time.'';
}
$me_time_read = $row6['time_read'];
$res7=mysqli_query($conn, "SELECT * FROM ap_users WHERE user_id = '$me_sender_id'");
while($row7=mysqli_fetch_array($res7))
{
$me_first_name = $row7['first_name'];
$me_last_name = $row7['last_name'];
$me_display_img = $row7['display_img'];
}
mysqli_query($conn, "UPDATE ap_messages SET time_read = NOW() WHERE message_id = '{$me_message_id}' AND time_read = '0000-00-00 00:00:00' AND conversation_id = '$co_conversation_id' AND sender_id != '$user_id'");
?>
<div class="media" style="max-width: <? echo $screenwidth; ?>px;">
<div class="media-left">
<a href="#">
<img src="userimg/<? echo $me_display_img; ?>" alt="user" width="64px" height="64px" hspace="10px" class="media-object" align="left">
</a>
</div>
<div class="media-body" style="position: relative !important;">
<div style="display:inline"><b><? echo ''.$me_first_name.' '.$me_last_name.''; ?></b></div> <div align="right" style="float:right; display:inline"> <? echo $me_time; ?> </div><br>
<? echo $me_message; ?>
</div>
</div>
<?
}
?>
</div>
</div>
<form action="" method="post" id="reply" name="reply" onsubmit="loadDoc()">
<div class="form-group">
<textarea class="form-control" rows="3" cols="80" id="message" name="message" placeholder="Send a reply..."></textarea>
<input type="hidden" id="conversation_id" name="conversation_id" value="<? echo $co_conversation_id; ?>">
<input type="hidden" id="sarssystem" name="sarssystem" value="<? echo $sarssystem; ?>">
<input type="hidden" id="user_id" name="user_id" value="<? echo $user_id; ?>">
</div>
<div class="form-group" align="right">
<div class="btn-group" align="left" style="float:left">
<button type="button" class="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<span class="glyphicon glyphicon-cog" aria-hidden="true"></span> <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li>Delete Conversation</li>
<li>Visit Profile</li>
<li>Report User</li>
<li role="separator" class="divider"></li>
<li>Change Display Photo</li>
</ul>
</div>
<button type="reset" class="btn btn-default btn-sm">Cancel</button>
<button type="submit" class="btn btn-primary btn-sm">Send Message</button>
</div>
<script>
setInterval(function() {
$("#content").load(location.href+" #content","");
}, 5000);
</script>
<script>
function loadDoc() {
$.ajax({
url: 'system/reply_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
success: function(data) {
console.log("success");
var $content = $(".list-group-message");
$content[0].scrollTop = $content[0].scrollHeight;
// Second ajax
$.ajax({
url: 'system/sars_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
success: function(data) {
$content[0].scrollTop = $content[0].scrollHeight;
},
error: function(e) {
//called when there is an error
console.log('fail');
}
});
},
error: function(e) {
//called when there is an error
console.log('fail');
}
});
}
</script>
</div>
When your script is done, you can use the following script:
$content[0].scrollTop = $content[0].scrollHeight;
Example:
$.ajax({
url: 'system/reply_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
success: function(data) {
console.log("success");
var $content = $(".list-group-message");
$content.text(data); // Here you have to insert the received data.
$content[0].scrollTop = $content[0].scrollHeight;
// Second ajax
$.ajax({
url: 'system/sars_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
success: function(data) {
$content.text(data); // Here you have to insert the received data.
$content[0].scrollTop = $content[0].scrollHeight;
},
error: function(e) {
//called when there is an error
console.log('fail');
}
});
},
error: function(e) {
//called when there is an error
console.log('fail');
}
});
Hope it helps.
Try like this:
$.ajax({
url: 'system/sars_system.php',
type: 'POST',
dataType: 'json',
data: $('#reply').serialize(),
}),
success: function(response) {
console.log(response);
var $content = $(".list-group-message");
$content[0].scrollTop = $content[0].scrollHeight;
},
error: function(response) {
console.log(response);
}
});
This is the one that how I approached. First access the parent div that you want to load the data. Then scroll down using jquery.
$.ajax({
type: "GET",
url: baseURL + "notification/get_load_notif_member_message",
data: "member_id=" + member_id + "&message_id=" + message_id,
contentType: 'html',
success: function (html) {
$('.msg_history').html(html);
$("input[name='text']").val('');
var $content = $(".msg_history");
$content[0].scrollTop = $content[0].scrollHeight;
},
error: function (html) {
$('.msg_history').html('Something went wrong. Please try again.');
}
});
I have a modal form with Bootstrap that is associated with a specific item that is customized by the user before being added to the cart. I'm trying to trigger an Ajax request when the "Add to Cart" button is clicked. But the button doesn't seem to be triggering anything. I'm using a modified version of Bootstrap's sample code: http://getbootstrap.com/javascript/#modals-related-target
Any suggestions on how to get the button to trigger an ajax request properly?
UPDATE: I've added the PHP code below in case that might be the issue.
HTML:
<div class="modal-body">
<form name="formBasic" id="formBasic">
<input type="hidden" name="function" value="basic-form">
<div class="form-group">
<label for="message-text" class="control-label">Enter customized information</label>
<textarea class="form-control" id="customized-information"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="basic-submit">Add to Cart</button>
</div>
Javascript:
$(document).ready(function () {
var formBasic = function () {
var formData = $("#formBasic").serialize();
$(form).ajaxSubmit({
type: 'post',
data: formData,
dataType: 'json',
url: 'http://localhost/forms.php'
error: function () {
console.log(output);
alert("There was an error processing this page.");
return false;
},
complete: function (output) {
$('#formBasicResults').html(output.responseText);
}
});
return false;
};
$("#basic-submit").on("click", function (e) {
e.preventDefault();
formBasic();
});
});
PHP:
//formBasic Processing
function formBasic(){
$output = 'Output from Form Basic:
';
foreach ($_POST as $key => $value) {
$output .= $key . ': ' . $value . '
';
}
echo $output;
}
//FormAdvanced Processing
//. . .
if(in_array($_POST['function'], array('formBasic','formAdvanced'))){
$_POST['function']();
}else{
echo 'There was an error processing the form';
}
Your code should be:
$(document).ready(function () {
var formBasic = function () {
var formData = $("#formBasic").serialize();
$.ajax({
type: 'post',
data: formData,
dataType: 'json',
url: 'http://localhost/forms.php',
error: function () {
alert("There was an error processing this page.");
return false;
},
complete: function (output) {
$('#formBasicResults').html(output.responseText);
}
});
return false;
};
$("#basic-submit").on("click", function (e) {
e.preventDefault();
formBasic();
});
});
Issues:
1- Missing comma on line:
url: 'http://localhost/forms.php'
2- form not defined:
$(form).ajaxSubmit({
Working fiddle: http://jsfiddle.net/p9v2eg4u/2/
$('#basic-submit').click(function() {
var formData = $("#formBasic").serialize();
console.log(formData);
added a console.log(); of the value of form data
$('#formBasic').ajaxSubmit({
type: 'POST',
data: formData,
dataType: 'JSON',
url: 'http://localhost/forms.php',
added missing comma after URL
error: function () {
alert("There was an error processing this page.");
return false;
},
complete: function (output) {
console.log(output);
another console.log of output object
$('#formBasicResults').html(output.responseText);
},
success: function(output) {}
consider using success instead of complete, complete will execute if success or error.
});
return false;
});