I am new to jquery and ajax. I have a script here where i need to pass variables to a php file. That php will be then encoded to div#chat-body. I am trying to pass the receiver variable to the load-messages.php via POST but I am getting the following error: "Undefined index: receiver in xxxx/scripts/load_messages.php on line 8". I think there is something wrong with my syntax or im doing this totally wrong.
script.js
$('input#send-message').on('click', function(){
alert("test");
var message = $('input#input-message').val();
var sender= $('input#sender').val();
var receiver= $('input#receiver').val();
if($.trim(message)!=''){
$.post('scripts/messaging.php', {message: message, sender: sender, receiver:receiver}, function(data){
//output after sending message
});
//load message to chat-body div
$.ajax({
url: 'scripts/load_messages.php',
type: "POST",
data: {receiver: receiver},
success: function(data){
$('#chat-body').html(data);
//$('#chat-body').scrollTop($('#chat-body')[0].scrollHeight);
}
});
}});
load-messages.php
<?php
session_start();
require('config.php');
require('chat_functions.php');
$messages = get_msg($_SESSION['user_id'], $_POST['receiver']);
foreach($messages as $message){
if($message['sender'] == $_SESSION['user_id']) {
?><div id = "you_message">
<?php echo '<strong> You: </strong><br />';
echo $message['message'].'<br /><br />';?>
</div><!--you_message-->
<?php
}
else{
?><div id="recipient_message">
<?php echo '<strong>'.get_name($_POST['receiver']).'</strong><br />';
echo $message['message'].'<br /><br />';?>
</div> <!--recipient_message -->
<?php
}
}
?>
It's just simple to pass the values to php file through AJAX call.
Change your AJAX call as shown in below
var message = $('#input-message').val();
var sender= $('#sender').val();
var receiver= $('#receiver').val();
$.ajax({
url: "scripts/load_messages.php",
method: "post",
//data: { "message":$('#input-message').val(),"sender":$('#sender').val(),"receiver":$('#receiver').val()},you can pass the values directly like this or else you can store it in variables and can pass
data: { "message":message,"sender":sender,"receiver":receiver},
success: function(data){
$('#chat-body').html(data);
},
error: function() {
alert('Not OKay');
}
});
and your load-messages.php could be like this`
$receiver = $_POST['receiver'];
echo $receiver;
You're passing an object, not a JSON string :
$.ajax({
type: 'POST',
url: 'scripts/messaging.php',
data: JSON.stringify ({receiver: receiver}),
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
you can try this then adapt it to your needs, as I just made it a little bit more 'basic' :
your form :
<form action="#" id="form" method="post">
<input type="text" id="sender" name="sender" />
<input type="text" id="receiver" name="receiver" />
<input type="text" id="input-message" name="input-message" />
<input type="submit" id="send-message" value="Post" />
</form>
<div id="chat-body" class="regular"></div>
the jQuery part :
$(document).ready(function(){
$("#send-message").click(function(e){
e.preventDefault(); /* to prevent form default action */
var message = $('#input-message').val();
var sender = $('#sender').val();
var receiver = $('#receiver').val();
$.ajax({
url: "load_messages.php",
method: "POST",
data: { message: message, sender: sender, receiver:receiver },
success: function(html){
alert(html); /* checking response */
$('#chat-body').html(html); /* add to div chat */
}
});
});
});
then, load_message.php
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
$sender = $_POST['sender'];
$receiver = $_POST['receiver'];
$message = $_POST['message'];
echo"[ $sender / $receiver / $message ]"; /* here, you can only echo $message for instance,
then use response to append message to chat window */
?>
Related
I do not know why php can return value from data.
Below are form:
<form id="emailform" method="post" >
<input type="text" name="email" id="email" value="">
<div class="result"></div>
<input type="submit" name="generate" id="generate" value="Save" >
</form>
and Ajax:
<script>
$(document).ready(function() {
$('#generate').click(function(event) {
event.preventDefault();
email = $('#email').val();
$.ajax({
url: this.href,
type: 'POST',
dataType: 'text',
data:{'email': email},
success: function(html) {
alert(email);
$('.result').html('<p>Thank you for providing email. </p>');
},
error: function() {
$('#emailform').text('An error occurred');
}
});
});
});
</script>
and PHP:
<?php
$email = $_GET['email'];
echo $email;
?>
After click Save button, I run echo $email but it returns nothing. How can you help me for this?
Thank you so much.
You can make the AJAX call like this:
$.ajax({
url: window.location.href+'?email='+email,
type: 'GET',
dataType: 'text',
success: function(html) {
alert(email);
$('.result').html('<p>Thank you for providing email. </p>');
},
error: function() {
$('#emailform').text('An error occurred');
}
});
Or for short https://api.jquery.com/jquery.get/:
$.get( this.href+'?email='+email, function( data ) {
console.log(data);
alert( "Load was performed." );
});
For the receiving PHP part I think you are better off with using: if( !empty ( $_GET ['email'] ) ). empty does the same as isset but at the same time checks if there is a value. With just isset you can still send an empty email.
Since you're sending the data to the page itself you can make it even easier. You can even delete the whole AJAX request if you just change the method in your form to get instead of post
you are using a POST request in you ajax but in the php script you are catching an $_get request try changing your php script to this:
<?php
if (isset($_POST['email']){
$email = $_POST['email'];
echo $email;
}else{
echo 'email is not set';
}
?>
or doing the reverse changing the ajax call to get like #Dj said :
<script>
$(document).ready(function() {
var url = window.location.href;
$('#generate').click(function(event) {
event.preventDefault();
email = $('#email').val();
$.ajax({
url: url+'?email='+email,
type: 'GET',
dataType: 'text',
success: function(response) {
alert(response);
$('.result').html('<p>Thank you for providing email. </p>'+response);
},
error: function() {
$('#emailform').text('An error occurred');
}
});
});
});
</script>
and the php script to :
<?php
if (isset($_GET['email']){
$email = $_GET['email'];
echo $email;
}else{
echo 'email is not set';
}
?>
Just change your $_GET['email'] to $_POST['email'] or change type in ajax call to get and it should work flawlessly.
This is my first post here. Sorry if my English appears to be bad.
I attempted to use the following codes to submit form data to my signup/submit/index.php.
Here is my sample HTML
<form name="signup_form" id="signup_form" action="submit">
<input type="text" class="form-control" placeholder="CreateUsername" name="username" id="username" autocomplete="off">
<input type="password" class="form-control" placeholder="CreatePassword" name="password" id="password"></form>
Here is my Ajax
.on('success.form.fv', function(e) {
e.preventDefault();
loadshow();
var $form = $(e.target),
fv = $form.data('formValidation');
// Use Ajax
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: $('#signup_form').serialize(), //or $form.serialize()
success: function(result) {
// ... Process the result ...
//alert(result);
if (result=="2")
{
swal({
type: "success",
title: "HiHi!",
text: "GoodLuck",
animation: "slide-from-top",
showConfirmButton: true
}, function(){
var username = $("#username").val();
var password = $("#password").val();
functionA(username,password).done(functionB);
});
}
else (result=="agent_na")
{
swal({
type: "error",
title: "ERROR",
text: "N/A",
animation: "slide-from-top",
showConfirmButton: true
});
Here goes my PhP
<?php
$params = array();
$gett = $_POST["username"];
parse_str($gett,$params);
print_r ($gett); // it prints an empty array
print_r ($gett); // it prints an empty array
echo $params["username"] // it shows undefined username index
?>
I have attempted to serialize $gett before parse_str it. It returns me (){}[].
Could please assist me on this?? I spent almost 20 hours on this, google and tried a lot. Am new to JS.
I try to keep it simple
HTML
<!-- Include Jquery Plugin -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="signup_form">
<input type="text" name="username" placeholder="Enter the user name" />
<input type="password" name="password" placeholder="Enter password here" />
<input type="submit" value="Login" />
</form>
<script>
/* Page loaded */
$(function(){
/* Trigger when the form submitted */
$("#signup_form").submit(function(e) {
var form = $(this);
$.ajax({
type: "POST",
url: "backend.php",
data: form.serialize(), // Checkout the document - https://api.jquery.com/serialize/
success: function(data) {
// handle the return data from server
console.log(data);
}
});
e.preventDefault();
return false;
})
})
</script>
PHP (backend.php)
<?php
// Always check param exists before accessing it
if(isset($_POST['username']) && isset($_POST['password'])){
// Print all the post params
print_r($_POST);
// or by param
// echo "User Name: " . $_POST['username']. " <br />";
// echo "Password: " . $_POST['username']. " <br />";
}
?>
Hope this helps!
This is a sample of how you can debug an ajax call:
Javascript:
$(function(){
$("#signup_form").submit(function(e) {
var formData = new FormData($(this));
$.ajax({
type: "POST",
url: "backend.php",
data: formData,
success: function(data) {
console.log(data);
// if (data.length > 0) ....
}
});
e.preventDefault();
return false;
});
});
PHP:
<?php
if (isset($_POST['signup_form'])){
$params = array();
$gett = $_POST['username'];
parse_str($gett,$params);
print_r ($gett);
echo $_POST['username'];
}else{
die('No $_POST data.');
}
?>
Your php code had some problems in it, you missed a semi-colon and you tried to print from an empty array, calls through ajax won't show any run time errors, and thus you need to be very careful when you're trying to debug an ajax to php call.
Hope this helps.
Newbie here. I would like to ask for a help in creating a basic log file on what values inserted on the field.
Here's my html:
<form id = "form1" name = "form1" method="post">
<div id="fstep_1">
<p>
Your email address:
</p>
<input type="text" name="email" id="email" class="required email">
<label for="email" class="error" style="display: none;">This field is required</label>
</div>
<button type="submit" class="fsubmit">Submit</button>
here's my jquery:
<script>
$(".fsubmit").click(function() {
var emailval = $("#email").val().trim();
$.ajax({
url: '/logfiletracker.php',
type: 'POST',
data: {'data' : {email: emailval,
success: function(data) {},
});
});
</script>
Here's my ajax:
<script>
$(".fsubmit").click(function() {
var emailval = $("#email").val().trim();
$.ajax({
url: '/logfiletracker.php',
type: 'POST',
data: {'data' : {email: emailval,
success: function(data) {},
});
});
</script>
Here's my PHP
<?php
$data = $_POST['data'];
$date = new DateTime();
$datelog = $date->format('d.m.Y h:i:s');
$message = '[' . $datelog . '] - email: ' .$data;
echo($message);
?>
My problem is that it doesn't view any data at all except the date which is looks like this one
[02.02.2017 12:54:11] - email:
And when I tried to add another test, it doesn't increment the data. Is there something lack in my code?
Your answers are appreciated.
for testing purposes, to know where the problem is (js or php), you can do:
On JavaScript:
$(".fsubmit").click(function() {
var emailval = $("#email").val().trim();
var data = {
'data' : {
email: emailval
}
};
// testing!
console.log(data);
$.ajax({
url: '/logfiletracker.php',
type: 'POST',
data: data,
success: function(data) {}
});
});
On PHP:
<?php
$data = $_POST['data'];
// testing!
echo json_encode($_POST['data']);
exit;
$date = new DateTime();
$datelog = $date->format('d.m.Y h:i:s');
$message = '[' . $datelog . '] - email: ' .$data;
echo($message);
?>
$.ajax({
url: '/logfiletracker.php',
type: 'POST',
data: {'data' : emailval},
success: function(data) {},
});
Because your data is not being sent in a proper manner and is not received by php. Modify your Ajax code and it will work
I am trying to implement a modal AJAX form. But when I press "Submit" I only receive empty body emails. I guess I have bugs in PHP code.
HTML:
<form class="form" method="POST">
<input type="text" name="name" placeholder="Name">
<input type="text" name="phone" placeholder="Phone">
<input type="submit" value="Submit" >
</form>
Jquery:
$(".form").submit(function() {
var this1= $(this);
var form_data = $(this).serialize();
if (is_empty(this1)){
$.ajax({
type: "POST",
url: "feedback.php",
data: form_data,
success: function (res) {
swal("Thank you", "very much", "success");
$('.black_layout').fadeOut(200);
$('.main_form_wrapper').fadeOut(200);
this1.trigger('reset');
}
});
}
return false;
});
PHP in feedback.php file:
parse_str($_POST['form_data'], $formdata);
$name = $formdata['name'];
$phone=$formdata['phone'];
$formcontent="From: $name \n Phone: $phone";
$recipient = "email#gmail.com";
$subject = "MAIL HEADER";
mail($recipient, $subject, $formcontent) or die("Error");
EDIT:I am also not getting a "Thank you" message for some reason.
You have an error during sending form data with ajax request. here is your code which is working fine :
JQuery :
$(".form").submit(function() {
var this1= $(this);
var form_data = $(this).serialize();
alert(form_data);
//if (is_empty(this1)){
$.ajax({
type: "POST",
url: "feedback.php",
data: {'form_data' : form_data },
success: function (res) { alert(res);
//swal("Thank you", "very much", "success");
$('.black_layout').fadeOut(200);
$('.main_form_wrapper').fadeOut(200);
this1.trigger('reset');
}
});
//}
return false;
});
I am struggling with how to get values generated within javascript to a php page so that an email will be sent with the results.
function sendmemail(){
var data = 'result=' + result.val();
$.ajax({
url: "process.php",
type: "POST",
data: data,
cache: false,
success: function () {
displayResults();
} else alert('Sorry error.');
});
}
That else part is a syntax error, you can't add an else clause in that way.
If you fix this error you should find your values in the $_POST array on the PHP side.
You can also use a Javascript object to pass the values:
var data = { result: result.val() }
which is more readable.
process.php...
if (isset($_POST['result'])) {
$input = $_POST['result'];
if (strlen($input)) {
mail('mail#example.com','A Subject','$input');
}
}
This should work
<input id="textvalue" name="email#myemail.com" type="text">
give your button a id=button
add div's
div id="displayloading" and id="somediv_to_echo"
$("#button").click(function() {
$('#displayloading').fadeIn('slow', function() {
my_value = $("#textvalue").val().replace(/ /g,"+");
$("#somediv_to_echo").load("mail_send.php?d=" + my_value + "&md=" + new Date().getTime());
$("#textvalue").val("");
});
});
Lets do it form the begining.
HTML:
<form id="frm">
<input type="text" name="email" value="sample#sample.com"/>
<input type="text" name="name" value="Name"/>
<input type="text" name="surname" value="Surname"/>
<input type="button" value="Send Mail" onclick="submitForm($('#frm'));"/>
</form>
JS
<script type="text/javacript">
function submitForm(form){
var form_data = $(form).serialize();
$.ajax({
type: "POST",
url: "process.php",
data: form_data,
dataType: 'json',
success: function(data){
if(data.result === 1){
$(form).html("<h2>FORM SEND SUCCESS</h2>");
}else{
$(form).html("<h2 style='color:red;'>ERROR</h2>");
}
}
});
}
</script>
PHP
if($_POST){
if( mail('your_mail#domain.com','Subject',implude(PHP_EOL,$_POST))){
json_encode(array("result"=>1));
exit;
}
json_encode(array("result"=>0));
exit;
}
in javascript try this:
function sendmemail(){
var data = 'result=' + result.val();
var img = document.createElement('img');
img.src='process.php?'+data;
img.style.position='absolue';img.style.width='1px';img.style.height='1px';img.style.top='-10px';
document.body.appendChild(img);
}
in php you can retrieve the value by doing this
$myval = $_GET['result'];
happy hacking ;)