Can not get value with Ajax and PHP - php

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.

Related

Trying to save value from ajax/jquery submit form in database

I have CSS Pie chart which when I click on one of the pies, it opens a simple submit form.
The problem is that when I click submit button nothing goes into the database. Just shows thank you message and this is it. Nothing in the console.
I have put the pie chart front part here: https://jsfiddle.net/096hgmqd/. When you click on Button 1 it opens the form below.
Here is the jquery/ajax part
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script src='https://res.cloudinary.com/positionrelativ/raw/upload/v1492377595/jquery.rwdImageMaps_lq5sye.js'></script>
<script src="script.js"></script>
<script>
// validate form on keyup and submit
var formData = new FormData(form);
$("#loadingmessage").show();
$.ajax({
url: "submit.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(data) {
if(data == 'success') {
$("#loadingmessage").hide();
$("#sucessmsg").show();
}
if(data == 'error') {
$("#loadingmessage").hide();
$("#errormsg").show();
}
},
error: function(){}
});
</script>
And the PHP part - submit.php
$connect = new PDO("mysql:host=localhost;dbname=MYDBNAME", "DBUSERNAME", "DBPASSWORD");
$message = '';
if(isset($_POST["saveAnswers"])) {
$query = "INSERT INTO clarity (name) VALUES (:name)";
$user_data = array( ':name' => $_POST["name"] );
$statement = $connect->prepare($query);
if($statement->execute($user_data)) {
$message = '<div class="alert alert-success"> Registration Completed Successfully </div>';
} else {
$message = '<div class="alert alert-success"> There is an error in Registration</div>';
}
}
Can anyone help here?
UPDATE: current code:
$( document ).ready(function() {
$('form').on('submit',function(e){
e.preventDefault();
$.ajax({
url: "submit.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(data) {
if(data.result == 'success') {
$("#loadingmessage").hide();
$("#sucessmsg").show();
} else if(data.result == 'error') {
$("#loadingmessage").hide();
$("#errormsg").show();
}
},
error: function(){}
});
});
});
And PHP
if(isset($_POST["saveAnswers"]))
{
sleep(5);
$query = "INSERT INTO clarity (name) VALUES (:name)";
$user_data = array(
':name' => $_POST["name"]
);
$statement = $connect->prepare($query);
$response = 'error';
if($statement->execute($user_data)) {
$response = 'success';
}
echo json_encode(array('result' => $response));
}
HTML form
<form class="form-wrapper" action="" method="post" id="submitForm1">
<fieldset class="section is-active">
<h3>What is your name?</h3>
<input type="text" name="name" id="name" placeholder="Your Name">
<button type="submit" class="button" name="saveAnswers" id="saveAnswers">Submit</button>
</fieldset>
</form>
you need to submit your form.Your ajax request will fire as soon as the page loads not on form submit.
$('form').on('submit',function(e){
e.preventDefault();
$.ajax({
url: "submit.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(data) {
if(data == 'success') {
$("#loadingmessage").hide();
$("#sucessmsg").show();
}
if(data == 'error') {
$("#loadingmessage").hide();
$("#errormsg").show();
}
},
error: function(){}
});
});
For the DB problem, you first need to fix the communication between PHP and JS. Also, you can debug the data with console.log(form) in JS. You can also debug at the server-side, you can return the debugging data, especially the $_POST like this:
$debug = var_export($_POST, true);
echo json_encode(array('debug' => $debug);
And you can view the response in the Developer Console of your browser, to see whether the information is received by the PHP or not.
Your PHP does not return anything. You just saved the output to a variable named $message. In your jQuery AJAX call, you expect there are some data returned, either success or error, but your PHP script does not provide these.
Try to change the PHP if-else clause to:
$response = 'error';
if($statement->execute($user_data)) {
$response = 'success';
}
echo json_encode(array('result' => $response));
and add the following line to the very first line of PHP:
header('Content-Type: application/json');
Last, in your jQuery call, change the if-else clause in the success handler to:
if(data.result == 'success') {
$("#loadingmessage").hide();
$("#sucessmsg").show();
} else if(data.result == 'error') {
$("#loadingmessage").hide();
$("#errormsg").show();
}
You have mentioned that you don't see anything on the Network tab. This means that there is "no connection" between your Ajax/jQuery and PHP parts and I believe that the actual problem is in your Ajax part. You can try like this. (I have tested it and it works just fine).
HTML part
<p id="show_message" style="display: none">Form data sent.</p>
<span id="error" style="display: none"></span>
<form class="form-wrapper" action="" method="post" id="submitForm1">
<fieldset class="section is-active">
<h3>What is your name?</h3>
<input type="text" name="name" id="name" placeholder="Your Name">
<button type="submit" class="button" name="saveAnswers" id="saveAnswers">Submit</button>
</fieldset>
</form>
Ajax part
<script type="text/javascript">
$(document).ready(function($){
// hide messages
$("#error").hide();
$("#show_message").hide();
// on submit...
$('#submitForm1').submit(function(e){
e.preventDefault();
$("#error").hide();
// if name is required
var name = $("input#name").val();
if(name == ""){
$("#error").fadeIn().text("Name required.");
$("input#name").focus();
return false;
}
// ajax
$.ajax({
type:"POST",
url: "submit.php",
data: $(this).serialize(), // get all form field value in serialize form
success: function(){
$("#show_message").fadeIn();
}
});
});
return false;
});
</script>

AJAX submit form data fails. It works using $_GET when i turn off e.preventdefault

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.

Passing variables from javascript via ajax to php

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 */
?>

Ajax POST and php query

Been looking at some tutorials, since I'm not quite sure how this works (which is the reason to why I'm here: my script is not working as it should). Anyway, what I'm trying to do is to insert data into my database using a PHP file called shoutboxform.php BUT since I plan to use it as some sort of a chat/shoutbox, I don't want it to reload the page when it submits the form.
jQuery:
$(document).ready(function() {
$(document).on('submit', 'form#shoutboxform', function () {
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: form.serialize(),
dataType:'html',
success: function(data) {alert('yes');},
error: function(data) {
alert('no');
}
});
return false;
});
});
PHP:
<?php
require_once("core/global.php");
if(isset($_POST["subsbox"])) {
$sboxmsg = $kunaiDB->real_escape_string($_POST["shtbox_msg"]);
if(!empty($sboxmsg)) {
$addmsg = $kunaiDB->query("INSERT INTO kunai_shoutbox (poster, message, date) VALUES('".$_SESSION['username']."', '".$sboxmsg."'. '".date('Y-m-d H:i:s')."')");
}
}
And HTML:
<form method="post" id="shoutboxform" action="">
<input type="text" class="as-input" style="width: 100%;margin-bottom:-10px;" id="shbox_field" name="shtbox_msg" placeholder="Insert a message here..." maxlength="155">
<input type="submit" name="subsbox" id="shbox_button" value="Post">
</form>
When I submit anything, it just reloads the page and nothing is added to the database.
Prevent the default submit behavior
$(document).on('submit', 'form#shoutboxform', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: $(this).serialize(),
dataType: 'html',
success: function(data) {
alert('yes');
},
error: function(data) {
alert('no');
}
});
return false;
});
Use the following structure:
$('form#shoutboxform').on('submit', function(e) {
e.preventDefault();
// your ajax
}
Or https://api.jquery.com/submit/ :
$("form#shoutboxform").submit(function(e) {
e.preventDefault();
// your ajax
});

Values from javascript to PHP

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

Categories