POST Form Submission in JQuery/AJAX and PHP - javascript

I'm a bit new to working with form submissions in JQuery/AJAX and PHP, so I've been trying to follow some tutorials online and have run into a few issues.
I am trying to build a form that handles submissions through PHP. Here's what I have for my index.html file.
<body>
<h1>Food Preference</h1>
<p>Please let us know what types of foods you would like to see on the menu.</p>
<form id="food-form">
<label for="appetizer">Appetizer</label>
<input type="text" id="appetizer" required>
<label for="entree">Entree</label>
<input name="entree" type="entree" id="entree" required>
<label for="dessert">Dessert</label>
<textarea name="dessert" id="dessert" required></textarea>
<button id="submit_button" type="submit">Send</button>
<p id="form_content">
</p>
</form>
And here is my index.js file
jQuery.ajax({
url: "handler.php",
data: "appetizer=" + $("#appetizer").val() +
"&entree=" + $("#entree").val() +
"&dessert=" + $("#dessert").val(),
type: "POST",
success: function(data) {
$("#form_content").html(data);
},
error: function() {}
});
And here is handler.php
<?php
class runForm {
public function handle_food_form($request) {
if(opinion($_POST["appetizer"], $_POST["entree"], $_POST["dessert"])) {
print "<p class='success'>Thank you for your opinion.</p>";
return array('post_id' => $new_post_id );
}
}
}
runForm();
?>
It doesn't seem like my submission saves anywhere, or if it does, I'm not sure how to find it. Can anyone give any pointers for anything I might be doing wrong?
I am wondering if this line in handler.php is correct, since I haven't really defined "opinion".
if(opinion($_POST["appetizer"], $_POST["entree"], $_POST["dessert"]))

You have many issues in this code snippet, and you should first check the errors that PHP shows to you and try to resolve them first.
The PHP file (handler.php)
opinion() function is not defined.
runForm() is not a function , it's a name of a class, if you want to call handle_food_form() function, then you can make it a static function and call it like this runForm::handle_food_form();
The final version of your PHP file should be something like this
<?php
class RunForm {
public static function opinion($appetizer, $entree, $dessert)
{
// do your logic here and return true or false
return true;
}
public static function handle_food_form() {
if (!isset($_POST["appetizer"])) $_POST["appetizer"] = null;
if (!isset($_POST["appeentreetizer"])) $_POST["entree"] = null;
if (!isset($_POST["dessert"])) $_POST["dessert"] = null;
if(SELF::opinion($_POST["appetizer"], $_POST["entree"], $_POST["dessert"])) {
$htmlMsg = "<p class='success'>Thank you for your opinion.</p>";
/*
$con is a MySQLI object
$con->query("insert into table ........");
$new_post_id = $con->insert_id;
*/
return array('post_id' => $new_post_id, 'htmlMsg' => $htmlMsg );
} else {
return array('post_id' => null , 'htmlMsg' => "");
}
}
}
echo RunForm::handle_food_form()['htmlMsg'];
The client side
You should use encodeURIComponent() to encode the paramters of the URL to prevent something like this dessert=cheesecake&pancake from corrupting the URL, or pass an object of the parameters as the data to ajax function and jquery will do the encoding for you internally
jQuery.ajax({
url: "handler.php",
data: {
appetizer: $("#appetizer").val(),
entree: $("#entree").val(),
dessert: $("#dessert").val()
},
type: "POST",
success: function(data) {
$("#form_content").html(data);
},
error: function() {}
});

Separate the variables with commas.
In jQuery.ajax, do as like:
jQuery.ajax({
url: "handler.php",
data: "appetizer=" + $("#appetizer").val(),
"entree=" + $("#entree").val(),
"dessert=" + $("#dessert").val(),
type: "POST",
success: function(data) {
$("#form_content").html(data);
},
error: function() {}
});

Related

Send variable from Javascript to PHP using AJAX post method

I am trying to pass a variable from javascript to php, but it doesn't seem to be working and I can't figure out why.
I am using a function that is supposed to do three things:
Create a variable (based on what the user clicked on in a pie chart)
Send that variable to PHP using AJAX
Open the PHP page that the variable was sent to
Task one works as confirmed by the console log.
Task two doesn't work. Although I get an alert saying "Success", on test.php the variable is not echoed.
Task three works.
Javascript (located in index.php):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
// Task 2 - send var to PHP
$.ajax({
type: 'POST',
url: 'test.php',
dataType: 'html',
data: {
'itemNum' : itemNum,
},
success: function(data) {
alert('success!');
}
});
// Task 3 - open test.php in current tab
window.location = 'test.php';
}
}
PHP (located in test.php)
$item = $_POST['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
Thanks to anyone who can help!
From what i can tell you don't know what ajax is used for, if you ever redirect form a ajax call you don't need ajax
See the following function (no ajax):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
window.location = 'test.php?itemNum='+itemNum;
}
}
change:
$item = $_GET['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
or better you do a simple post request from a form like normal pages do :)
Try this:
success: function(data) {
$("body").append(data);
alert('success!');
}
Basically, data is the response that you echoed from the PHP file. And using jQuery, you can append() that html response to your body element.
you should change this code
'itemNum' : itemNum,
to this
itemNum : itemNum,
Seems contentType is missing, see if this helps:
$.ajax({
type: 'POST',
url: 'test.php',
dataType: "json",
data: {
'itemNum' : itemNum,
},
contentType: "application/json",
success: function (response) {
alert(response);
},
error: function (error) {
alert(error);
}
});
you can easily pass data to php via hidden variables in html for example our html page contain a hidden variable having a unique id like this ..
<input type="hidden" id="hidden1" value="" name="hidden1" />
In our javascript file contains ajax request like this
$.ajax({
type: 'POST',
url: 'test.php',
data: {
'itemNum' : itemNum,
}
success: function (data) {
// On success we assign data to hidden variable with id "hidden1" like this
$('#hidden1').val(data);
},
error: function (error) {
alert(error);
}
});
Then we can access that value eighter on form submit or using javascript
accessing via Javascript (Jquery) is
var data=$('#hidden1').val();
accessing via form submit (POST METHOD) is like this
<?php
$data=$_POST['hidden1'];
// remaining code goes here
?>

Uploading a file through AJAX with a Django Form

I've been trying to create a system that allows uploads of text and a file through my Django form. Whenever I try post the form I can only seem to get the message part of the form. I've been following this answer for reference but I've been running into trouble. First, my form looks like this:
class MessageForm(forms.Form):
message = forms.CharField(widget=forms.Textarea, required=False)
file = forms.FileField(label="Attachment", required=False)
and it's rendered to HTML like this:
<form id="message-form" enctype="multipart/form-data">
{{form.message}}<br>
{{form.file}}
<div class="sectio4-bottom">
<div class="right-bottom">
<input id="send-button" type="submit" value="Send"/>
</div>
</div>
</form>
The current version of my JS function I'm working with looks entirely like this:
$('html').on('submit', '#message-form', function(e){
e.preventDefault();
var data = new FormData($('#message-form').get(0));
$.ajax({
url: '#',
type: 'POST',
data: {
'data': data,
'csrfmiddlewaretoken': $('.csrftoken').text()
}
});
return false;
})
but the part I'm interested in is var data = new FormData($('#message-form').get(0));. I got this from the linked question but when it runs it gives me an empty object. I've also tried passing the data as 'data': $('#message-form').serialize() but when it gets to the backend and I look at request.POST I see that the only thing included in data is the message I send. request.FILES is empty.
How can I access the specified file?
Try adding:
data.append('file',$("#file").files[0]); #Assume 'file' is id of your file field
after
var data = new FormData($('#message-form').get(0));
Here an example function that I'm using
function saveVeichle() {
$(".sk-wave").show();
var dati = new FormData();
dati.append('csrfmiddlewaretoken','{{csrf_token}}');
dati.append('note',$("#note").val());
dati.append('dip',$("#dip-0").val());
dati.append('stato',$("#stato").val());
$("input").each(function(id,obj){
if (obj.type == 'checkbox') {
dati.append(obj.name,obj.checked);
} else {
dati.append(obj.id,obj.value);
}
});
dati.append('foto',$(".foto")[0].files[0]);
dati.append('libretto',$(".libretto")[0].files[0]);
$.ajax({
url: "/mezzi/api/salva_mezzo/",
type: "POST",
data: dati,
cache: false,
contentType: false,
processData: false,
}).done(function(data) {
if (data.res == 'ok') {
window.location = '/mezzi/' + data.id + '/';
} else {
if (data.errors) {
for (d in data.errors) {
noty_alert(d + ":" + data.errors[d]);
}
} else {
noty_alert('Errore Salvataggio Mezzo!');
}
$(".sk-wave").hide();
}
});
}

Wordpress get current page name or id within ajax request callback

I need to get current page id or name from ajax request callback. Initially at loading a page i made an ajax request. In its callback method i need to get the current page id or name. I used following code for ajax request.
$.ajax({
type: "POST",
url: my_site.home_url + '/wp-admin/admin-ajax.php',
data: {
action: "notes_select_page"
},
dataType: "html",
success: function (Response) {
if (Response == "OK") {
Notes.renderBoardList();
} else {
}
},
async: true
});
I took the request from action hook.
add_action('wp_ajax_nopriv_notes_select_page', 'Notes::select_page');add_action('wp_ajax_optimal_notes_select_page', 'Notes::select_page');
And the callback i used several code but doesn't work. Try 1.
public static function select_page(){
global $pagename;
die($pagename);
}
Try 2
public static function select_page(){
global $wp_query;
$pagename = get_query_var( 'pagename' );
if ( !$pagename) {
$post = $wp_query->get_queried_object();
$pagename = $post->post_name;
}
die($pagename);
}
Try 3
public static function select_page(){
global $post;
die($post->ID);
}
But unfortunately any of them doesn't work to get current page ID or name. Callback is working fine with other values.
Thanks in advance.
function get_current_page_id() {
var page_body = $('body.page');
var id = 0;
if(page_body) {
var classList = page_body.attr('class').split(/\s+/);
$.each(classList, function(index, item) {
if (item.indexOf('page-id') >= 0) {
var item_arr = item.split('-');
id = item_arr[item_arr.length -1];
return false;
}
});
}
return id;
}
You don't need ajax for this.
Add this function to your code.
You can now get the page id by using:
var id = get_current_page_id();
To retrieve the post details you have to send the data yourself
data:{
action: "notes_select_page",
post_id: current_post_id, //current_post_id should either parsed from DOM or you can write your ajax in PHP file
}
You can either use a hidden box for current post id and get in the Js file using class or id or write the ajax in you php file itself.
Then you can retrieve via POST
public static function select_page(){
$post_id = $_POST['post_id'];
}
I'm getting post ID from the default WordPress post editing form, like so :
var post_ID = jQuery('[name="post_ID"]').val()*1;
Tje *1 converts the ID into an integer, otherwise it's interpreted as a string.
First take page id by this function
either
<div id="current_page_id"> <?php get_the_ID(); ?> </div>
or
<body page-id="<?php get_the_ID(); ?>">
Now In jquery ajax take following
var page_id = $('current_page_id').html();
OR
var page_id = $('body').attr("page-id");
$.ajax({
type: "POST",
url: my_site.home_url + '/wp-admin/admin-ajax.php',
data: {
action: "pageid="+page_id,
},
dataType: "html",
success: function (Response) {
if (Response == "OK") {
Notes.renderBoardList();
} else {
}
},
async: true
});
There is a solution to solve the issue in Wordpress. Adding ajax code in wp_footer hook, where using php code current page id can be retrieved and pass as ajax value.
You can obtain alternatively by the hidden field the post/page id in the following manner. This code is inserted in the template file (and then the value will be send to your ajax action hook as indicated above):
<?php
echo '<input type="hidden" name="activepost" id="activepost"
value="'.get_the_ID().'" />'
;?>
Check out this for reference: https://developer.wordpress.org/reference/functions/get_the_id/

jQuery ajax form doesn't work

I tried many ways to create a simple jquery ajax form but don't know why it is not submitting and/or returning the notification.
Here is my code:
Javascript
...
<script type="text/javascript" src="assets/js/jquery1.11/jquery-1.11.0.min.js"></script>
...
$('#form_signup').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
HTML
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<a type="submit">Sign up!</a>
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
PHP
<?php
$our_mail = "our#email.com";
$subject = "Wohoo! A new signup!";
$email = $_POST['inputEmail1'];
$return = array();
$return['msg'] = 'Thank you!';
$return['error'] = false;
if(preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)){
$message = "Yesss!! We receive a new signup!
E-mail: $email
";
mail($our_mail, $subject, $message);
}
else {
$return['error'] = true;
$return['msg'] .= 'Something is wrong... snifff...';
}
return json_encode($return);
Solved:
There were three problems. And different users solve each of these problems.
In PHP, you must "echo" the return array instead of "return"
At first, you should use a submit button instead of an anchor in the form
In the input, you must set both "id" and "name"
If any of these users want, you can edit or add a new answer with these details, and the points are yours.
You need to do 3 things.
First, wrap your jQuery codes inside $(document).ready() function,
<script type="text/javascript">
$(document).ready(function()
{
$('#form_signup').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
});
</script>
Second, Add a submit button to your form. Also you are missing the name attribute for the email input field. That causes the error in the php file.
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<input type="submit" name="signup" value="Sign Up!"/>
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
Third, echo the results since you are using AJAX to submit the form. return will not have any effects.
<?php
$our_mail = "our#email.com";
$subject = "Wohoo! A new signup!";
$email = $_POST['inputEmail1'];
$return = array();
$return['msg'] = 'Thank you!';
$return['error'] = false;
if(preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)){
$message = "Yesss!! We receive a new signup!
E-mail: $email
";
mail($our_mail, $subject, $message);
}
else {
$return['error'] = true;
$return['msg'] .= 'Something is wrong... snifff...';
}
echo json_encode($return);exit;
I checked and it's working fine.
Hope this helps :)
The problem is in your form.
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<input type="submit" name="submit" value="Submit">
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
The php code needs to echo instead of return.
just like this:
echo json_encode($return);
Also, your form needs a submit button - type="submit" on an <a> tag doesn't trigger the browser's functionality for handling <form>s
Finally, you need to ensure that your special submit handler is loaded at just the right time -- which, if it is included at the bottom of the page, right before the footer, it should be just fine. However, you can ensure this by wrapping it in
$(document).ready(function(){
//[...]
});
doesn't your a type="submit" need to be an input instead? or a button
I am trying to call webmethod in a ajax using jquery in asp.net, but sometimes it works well and sometimes it doesn't.
Here is my ajax code :
$.ajax({
type: "POST",
url: "frmTest.aspx/fncSave",
data: "{}"
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "false",
cache: "false", //True or False
success: function (response)
result = response.d;
if (result != "") {
alert(response);
}
},
Error: function (x, e) {
alert("err");
return false;
}
});
Here My Server Side Code :
<WebMethod()>
Public Shared Function fncSave() As String
Dim sResult As Int16
Try
Dim obj As New ClsCommon()
sResult = obj.Save()
Catch ex As Exception
ex.Message.ToString()
End Try
Return sResult
End Function
$(this) in the "ajax" function is not the form.
So just try:
$('#form_signup').submit(function(event) {
event.preventDefault();
var $this = $(this);
$.ajax({
type: 'POST',
url: 'signup.php',
data: $this.serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
I admit i didn't check the rest of the code, im pretty sure thats the problem.
Of course if the problem still goes, just "f12" and check console and network for server request and headers, make sure all the params are there.
Hope that helped

Pass variable to PHP with JS

I have an HTML form which i populate from a database. On submit we load a page called "viewgame.php". Now what i want is here to run some scripts to populate some tables with data but how exactly can i pass the variable which i got from the form ex. $_POST['gameNo'] to the other php file though JavaScript?
Below is some of my code
JS function
function refreshGameinfo() {
var load = $.get('gameinfo_sc.php');
$(".gameinfo").html('Refreshing');
load.error(function() {
console.log("Mlkia kaneis");
$(".gameinfo").html('failed to load');
// do something here if request failed
});
load.success(function(res) {
console.log("Success");
$(".gameinfo").html(res);
});
load.done(function() {
console.log("Completed");
});
}
How can i pass the $POST_['gameNo'] to the gameinfo_sc.php file so that i can get the correct results?
Try this
var load = $.get('gameinfo_sc.php',{gameNo:"1212"});
In your php file you can access it using
$_GET['gameNo']
For post method use
var load = $.post('gameinfo_sc.php',{gameNo:"1212"});
In your php file you can access it using
$_POST['gameNo']
You are trying to post $POST_['gameNo'] to gameinfo_sc.php but $.get isn't the right method for post, its actually for http get. you can also do this by using $.post http://api.jquery.com/jquery.post/
function refreshGameinfo() {
$.ajax({
type: "POST",
url: "gameinfo_sc.php",
data: {gameNo: data},
cache: false,
success: function(html){
console.log( "Success" );
$(".gameinfo").html(res);
},
error:function(html){
console.log("Mlkia kaneis");
$(".gameinfo").html('failed to load');
}
});
}
try this
You can do it like this:
(in html layout):
<input type="hidden" id="gameNo" value="<?=$_POST['gameNo']?>" />
(in js file):
var gameNo = $('#gameNo').val();
var load = $.get('gameinfo_sc.php', {gameNo: gameNo});
....
UPDATE:
If your server doesn't support short open tags, you can write:
<input type="hidden" id="gameNo" value="<?php echo $_POST['gameNo'] ?>" />

Categories

Resources