Ajax submitting form doesn't reload page but doesn't post - javascript

Help, I am really not familiar with ajax and I wanted to submit a form without reloading the page. Using the codes below, it didn't reload but it certainly didn't post or didn't even call the ajax function.
<script type="text/javascript">
$(function() {
//this submits a form
$("#post_form").on("submit", function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "post.php",
data: $("#post_form").serialize(),
beforeSend: function() {
$('#input_process').html('Loading');
},
success: function(data) {
$('#input_process').html(data);
},
failure: function(){
$('#input_process').html('Failed');
}
})
})
})
</script>
And here is the html form codes
<div id="input_process"></div>
<div id="story_post_input">
<form name="post_form" id="post_form" action="" method="POST">
<input type="hidden" name="post_type" value="story" />
<input type="text" name="post_title"/>
<textarea name="userpost"></textarea>
<input type="submit" name="post_submit" value="post" id="post_submit_button"/>
</form>
</div>
<div id="shout_post_input">
<form name="post_form" id="post_form" action="" method="POST">
<input type="hidden" name="post_type" value="shoutout" />
<input type="text" name="userpost"/>
<input type="submit" name="post_submit" value="shout" id="post_submit_button"/>
</form>
</div>
<div id="image_post_input">
<form name="post_form" id="post_form" action="" method="post" enctype="multipart/form-data">
<input type="file" name="post_image">
<input type="hidden" name="post_type" value="image" />
<input type="text" name="userpost"/>
<input type="submit" name="post_submit" value="upload" id="post_submit_button"/>
</form>
</div>
And here is the post.php code
<?php
if(isset($_POST['userpost'])){
$post_type = $_POST['post_type'];
if($_POST['post_type']=="shoutout"){
$post = $_POST['userpost'];
$query = 'INSERT INTO tblpost (post_content, post_date, post_userID, poster, post_type) VALUES ("'.$post.'", now(), "'.$_SESSION["user_ID"].'", "'.$_SESSION["username"].'", "'.$post_type.'" )';
$result = mysql_query($query) or mysql_error();
$tmp_post_ID = mysql_insert_id();
$type = "post";
notify($type, $tmp_post_ID);
}
if($_POST['post_type']=="story"){
$post_title = $_POST['post_title'];
$post = $_POST['userpost'];
$query = 'INSERT INTO tblpost (post_content, post_date, post_userID, poster, post_type, post_title) VALUES ("'.$post.'", now(), "'.$_SESSION["user_ID"].'", "'.$_SESSION["username"].'", "'.$post_type.'", "'.$post_title.'" )';
$result = mysql_query($query) or mysql_error();
$tmp_post_ID = mysql_insert_id();
$type = "post";
notify($type, $tmp_post_ID);
}
if($_POST['post_type']=="image"){
$tmp_name = $_FILES['post_image']['tmp_name'];
$user_ID = $_SESSION['user_ID'];
$post = $_POST['userpost'];
$img_ID = upload_image($tmp_name,$user_ID);
$query = 'INSERT INTO tblpost (post_content, post_date, post_userID, poster, post_type, img_ID) VALUES ("'.$post.'", now(), "'.$_SESSION["user_ID"].'", "'.$_SESSION["username"].'", "'.$post_type.'", "'.$img_ID.'" )';
$result = mysql_query($query) or mysql_error();
$tmp_post_ID = mysql_insert_id();
$type = "image";
notify($type, $tmp_post_ID);
}
//header('location:'.curPageURL());
}
?>

when you pass data from ajax to php
data: {variable : variable}, //var variable = $("#post_form").serialize(); and check your variable before pass it
and get it in php
echo ($_POST['variable']);

Your code works perfectly. (Example)
Change your form (as KyleK suggested) to this:
<form name="post_form" id="post_form" action="" method="POST">
.....
So this narrows down your problem to only one viable option. You either aren't including the jQuery library (possibly a deprecated version), or the way you're testing it is wrong.
Go simple and try this:
$.ajax( {
type: "POST",
url: "post.php",
data: $("#post_form").serialize(),
success: function(data) {
console . log(data);
}
});
and in your PHP script, just simple do something like this:
echo 'uwotm8';
To ensure your ajax is running correctly.

Change to this...
$(document).on("submit","#post_form", function (e) {...
Or..
$("#post_submit_button").click(function(e){
e.preventDefault();
//rest of code
});
And remove this from your form
onsubmit="return false;"
EDIT **
Based on your updated post
The reason its not working is because you are using multiple forms with one #ID. Which is illegal
<form name="post_form" id="post_form" action="" method="POST">
<input type="hidden" name="post_type" value="story" />
<input type="text" name="post_title"/>
<textarea name="userpost"></textarea>
<input type="submit" name="post_submit" value="post" id="post_submit_button"/>
</form>
<form name="post_form" id="post_form" action="" method="POST">
<input type="hidden" name="post_type" value="shoutout" />
<input type="text" name="userpost"/>
<input type="submit" name="post_submit" value="shout" id="post_submit_button"/>
</form>
<form name="post_form" id="post_form" action="" method="post" enctype="multipart/form-data">
<input type="file" name="post_image">
<input type="hidden" name="post_type" value="image" />
<input type="text" name="userpost"/>
<input type="submit" name="post_submit" value="upload" id="post_submit_button"/>
</form>
Just put all the inputs into ONE form and it will work
So based on this info. Heres how I would do it.
Give all your submit buttons a class...
<input class='form_submit_button' type="submit" value="upload" />
Then in your Jquery
$('.form_submit_button').click(function(e){
e.preventDefault();
var form = $(this).parent().serialize();
$.ajax({
type: "POST",
url: "post.php",
data: form,
success:function(data){
//success stuff
});
});

It seems you need to change your form codes, there are missing double quotes after POST, and no need to add the onsubmit attribute because you already handle that on jQuery.
<form name="post_form" id="post_form" action="" method="POST">
<input type="hidden" name="post_type" value="post" />
<input type="text" name="userpost"/>
<input type="submit" name="post_submit" value="post" id="post_submit_button"/>
</form>
let me know how you go

Related

how to send form element values directly to php page using javascript

What I am trying here is when you click on submit button I am calling one javascript function which takes all the form element values and passes it to the php page without storing them inside the variable and then send those variables.
Example of my form:
<form enctype="multipart/form-data" method="post" name="fileinfo">
<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" />
<br />
<label>Custom file label:</label>
<input type="text" name="filelabel" size="12" maxlength="32" />
<br />
<label>File to stash:</label>
<input type="text" name="email" required />
<input type="button" onsubmit="sendvalues()" value="Stash the file!" />
</form>
Now on javascript, I want to send userid and email fields to directly go to php page without first retrieving them into a variable and then send that variable via ajax.
function sendValues() {
var formElement = document.querySelector("form");
console.log(formElement);
var formData = new FormData(formElement);
var request = new XMLHttpRequest();
request.open("POST", "<?php echo VIEW_HOST_PATH;?>process_data.php");
formData.append("process_type", 'process_data');
request.send(formData); //want to send all form userid, email directly to php page
request.onreadystatechange = (e) => {
console.log(request.responseText)
}
}
Is this possible to send user_id and email values to php page directly? So, for example, form element which contains emailed and user info and any other forms element and they all send to php page via ajax but most important without storing this element values in javascript variables.
thanks
In your form you should specify property "action". That action would be your php file that will handle your submit action. Also you could add to this form id selector.
<form id="file-info" enctype="multipart/form-data" action="/process_data.php" method="post" name="fileinfo">
And now in your function sendValues() you could submit form like this:
function sendValues() {
document.getElementById("file-info").submit();
}
or you do not even need this function if you set your input button type to submit:
<input type="submit" name="submit" />
And then in your php file you can use your variables like:
if (isset( $_POST['submit']))
{
$userId = $_POST['userid'];
$email = $_POST['email'];
}
Try this one then
HTML CODE
<form enctype="multipart/form-data" method="post" class='submit_form' name="fileinfo">
<label>Your user name:</label>
<input type="text" name="name" id='name' placeholder="name" required /><br />
<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus name="userid" id='userid' placeholder="email" required size="32" maxlength="64" /><br />
<label>Custom file label:</label>
<input type="text" name="filelabel" size="12" maxlength="32" /><br />
<label>File to stash:</label>
<input type="text" name="email" required />
<input type="button" value="Stash the file!" class='submit' />
JQUERY CODE on the same page (include jquery)
$('body').on('click', '.submit', function(e) {
e.preventDefault();
$.ajax({
'url': 'mpay.php',
'type': 'POST',
'data': $('.submit_form').serialize(),
success: function(response) {
console.log(response);
}
});
});
PHP CODE The file name is mpay.php
$arr = [
'name' => $_POST['name'],
'email' => $_POST['email'],
];
echo "<pre>;
print_r($arr);
echo "</pre>";
Hope this helps.

How to submit a form with multiple fields having a same name attribute using ajax?

I have a HTML form
<html>
<head></head>
<form>
<input type="text" name="question[]" />
<input type="text" name="question[]" />
<input type="file" name="image" />
<input type="submit" name="save" />
</form>
</html>
Now to submit form with ajax
I have ajax code but its not working. It's get only one value.
$("#submit").click(function() {
var que_id = $("input[type='text'][name='question[]']").val();
$.ajax({
type: "POST",
url: "action.php",
data: {"que_id": que_id},
success: function(result) {
$("#question_wrap").html(result);
}
});
});
How do I do it?
Send form data to php file using ajax
add enctype to your form
<form id="questionForm" action="" method="post" enctype="multipart/form-data">
<input type="text" name="question[]" />
<input type="text" name="question[]" />
<input type="file" name="image" />
<input type="submit" name="save" />
</form>
Pass form data to php file using serialize
$.ajax({
url: 'action.php',
data: $("#questionForm").serialize(),
method: "post",
success: function (result) {
$("#question_wrap").html(result);
}
});
access form values in PHP file using the field name
<?php
foreach($_POST['question'] as $key => $value){
// your logic
}
$filedata= $_FILES['image'];
?>

Radio function in jQuery POST input

Pressing the button Index.php page, through sending the data to the script Resultx.php page, which responds with an asynchronous call on the same page Index.php.
index.php
<script>
$(document).ready(function() {
$("#input_form").submit(function(){
var fett = $("#fett").val();
$.ajax({
url: 'resultx.php',
type: "POST",
data: "fett="+fett,
dataType: "html",
success: function(data) {
$("div#resultx").html(data);
}
});
return false;
});
});
</script>
<form name="testa" id="input_form" action="" method="post" class="form-shorten" onsubmit="return checkForm(this);">
<input type="text" name="fett" class="form-control input-lg" id="fett" required><br/>
<button name="invio" type="submit" class="btn" value="Send" onclick="loadDoc()"><span class="glyphicon glyphicon-fire"></span> Send</button>
</form>
I wanted to add options with the "radio function" which may send along with the variable fett, also the variable taskOption to Resultx.php page.
<p><label class="radio-inline select">
<input class="radio-inline select" type="radio" name="taskOption" id="taskOption1" value="taskOption1"> option1</label>
<label class="radio-inline select">
<input class="radio-inline select" type="radio" name="taskOption" id="taskOption2" value="taskOption2"> option2</label></p>
Resultx.php
<?php
$fett = $_POST["fett"]; // ok
$taskOptionOK = $_POST["taskOption"]; // This is what I need
echo "$fett ";
echo "$taskOptionOK ";
?>
I know this is trivial but to me jQuery is kryptonite.
To get the value of a checked checkbox/radio you can try this:
var taskOption = $('input[name=taskOption]:checked').val();

I trying some ajax script without success, when I submit the form I take success alert but nothing send to the Database

I trying some ajax script without success, when I submit the form I take success alert but nothing send to the Database.
My HTML form:
<form action="account_info.php" enctype="multipart/form-data" method="post">
<input id="email" name="email" type="text" value="Save"/>
<input id="username" name="username" type="text" value="Save"/>
<input type="submit" name="Submit" value="Save"/>
</form>
My PHP code:
$error='';
$info='';
if(isset($_POST['Submit'])) {
require_once "classes/fields_process.php";
require_once "classes/blocked_emails.php";
if(!$usr->edit_info($crt_usr)) {
$usr_info=$usr->getTmp();
$error=$usr->getError();
} else {
$info=$usr->getInfo();
$usr_info = $usr->getUser($crt_usr);
}
} else $usr_info = $usr->getUser($crt_usr);
$smarty->assign("tmp",$usr_info);
$smarty->assign("error",$error);
$smarty->assign("info",$info);
Add an ID to the form : "accountForm"
<form action="account_info.php" enctype="multipart/form-data" method="post" **id="accountForm"**>
<input id="email" name="email" type="text" value="Save"/>
<input id="username" name="username" type="text" value="Save"/>
<input type="submit" name="Submit" value="Save"/>
</form>
The javascript:
$.customPOST = function(data,callback){
$.post('account_info.php',data,callback,'json');
}
$('#accountForm').submit(function(){
$.customPOST($(this).serialize(),function(r){
//the response from the server in JSON format
//an array, example in the PHP script we return
//an array that contains : 'success' => true
if(r.sucess){
alert('Operation OK');
}
});
return false;
});
BUT in your PHP you need to echo the response in JSON format :
echo json_encode(array('success' => true));
Ok i resolve the problem.
<form name="accountform" id="accountform" method="post" action="account.php">
<input id="email" name="email" type="text" value="Save"/>
<input id="username" name="username" type="text" value="Save"/>
<input type="submit" name="Submit" value="Save"/>
</form>
{literal}<script>
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#accountform').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
</script>{/literal}

How to manage two forms with one javascript function?

I am learning javascript but I still do not get to the book's chapter that could answers my question, so I will be very grateful if somebody can put me in the right track.
Here is the situation:
I am using jquery to submit a form. However I need to put two forms (of the same kind but referring to different object) and I want to use the same jquery function to submit the one I choose.
This is the jquery function:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$(".submit").click(function(){
var name = $("#student").val();
var mark = $("#mark").val();
var dataString = 'student='+ student + '&mark=' + mark;
$.ajax
({
type: "POST",
url: "records.php",
data: dataString,
success: function()
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
return false;
});
});
</script>
These are the forms I would like to pass to the above function depending on the one I click.
<form method="post" name="form">
<input type="hidden" id="student" name="student" value="Mandy" >
Mark: <input size="2" id="mark" name="mark" value="1" type="text">
<input type="submit" value="Submit" class="submit"/>
</form>
<form method="post" name="form">
<input type="hidden" id="student" name="student" value="Fred" >
Mark: <input size="2" id="mark" name="mark" value="1" type="text">
<input type="submit" value="Submit" class="submit"/>
</form>
Thanks
Well, first thing's first - you're going to get nowhere with the same id's on the page. Change the id's on student and mark to classes (which do not have to be unique):
<form method="post" name="form">
<input type="hidden" class="student" name="student" value="Mandy" >
Mark: <input size="2" class="mark" name="mark" value="1" type="text">
<input type="submit" value="Submit" class="submit"/>
</form>
<form method="post" name="form">
<input type="hidden" class="student" name="student" value="Fred" >
Mark: <input size="2" class="mark" name="mark" value="1" type="text">
<input type="submit" value="Submit" class="submit"/>
</form>
Then the jQuery is pretty simple - find the nearest form and seek out the student and mark by class (scoped to the form):
$(".submit").click(function(){
var $form = $(this).closest('form');
var student = $(".student", $form).val();
var mark = $(".mark", $form).val();
var dataString = 'student='+ student + '&mark=' + mark;
$.ajax
({
type: "POST",
url: "records.php",
data: dataString,
success: function()
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
return false;
});
Live example: http://jsfiddle.net/6Lc8R/

Categories