Show PHP file inside a DIV with jQuery - javascript

I have 3 files
register.php
reg.js
reg.php
When I hit the submit button in register.php (looks like this)
<div id="phpcontenthere"></div>
<form action="reg.php" method="post" id="myForm">
<input type='submit' id='submit' value='Sth'>
</form>
<script type="text/javascript" src="reg.js"></script>
It shows the error messages of reg.php but in another window.
I want those error messages to be shown inside the register.php.
And the reg.js looks like this:
$("#submit").click( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info) {
$("#phpcontenthere").empty();
$("#phpcontenthere").html(info);
});
$("myForm").submit( function () {
return false;
});
});
Maybe this solution i want to create is not good, or it's good but i missed something I don't know, but I would be really happy if anyone could help me,
Thanks in advance!
Tibor

I'll teach you the logic, with sample code as I don't want to spoon-feed you.
Firstly, create an array called 'errors':
$errors = array();
Then while you have your checks, just inflate your array.
if(something) {
$errors[] = "Error description";
}
Then once all your errors are inflated, you check for the length, and if it is greater than 0 errors, then return the array.
if(count($errors) > 0) {
return $errors;
}
And then, you can display the array with the for loop.
$c = count($errors);
for($i=0; $i < $c; $i++) {
echo $errors[$i];
}

You have a few problems.
First, $("myform") should be $("#myform") -- you forgot the # so it wasn't matching the ID.
Second, you shouldn't define a handler for submit inside the click handler; event handlers should almost always be defined at the toplevel.
You should just put return false in the click handler. Or better, put all that code in the form's submit handler (clicking on the submit button submits the form).
$("#myForm").submit( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info) {
$("#phpcontenthere").html(info);
});
});
return false;
});
It's also not necessary to call .empty() before calling .html(), since the latter completely replaces what's there.

From what I see, you are still submitting the form (the piece of code that returns false when trying to submit is inside the click listener). Maybe that's why it is ignoring the return false, and indeed submitting the form (instead of posting it with ajax)
So you should try a javascript code like this:
$("#submit").click( function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info) {
$("#phpcontenthere").empty();
$("#phpcontenthere").html(info);
}
);
});
$("#myForm").submit( function () {
return false;
});

Related

I am submitting form using javascript but I am not able to get values in php page

I am using this code to submit my form
$('.login-form input').keypress(function (e) {
if (e.which == 13) {
if ($('.login-form').validate().form()) {
//$( "#login-form input" ).submit();
// window.location.href = "check.php";
$.post("check.php", $("#login-form input").serialize(), function(data) {
window.location.href = "check.php";
});
}
return false;
}
});
I am not able to get values in check.php. kindly help me. I know its a basic thing but I am not able to do this. Thanks in advance
Here is my php code
<?php
session_start();
include_once("Includes/db_connection.php");
include_once("participant/welcome.php");
include_once("admin/admin_login.php");
include_once("staff/staff_login.php");
include_once("lecturer/lecturer_login.php");
include("Includes/location.php");
//include("Includes/lecturer_data_dropdown.php");
$username=$_POST["username"];
$password=$_POST["password"];
echo $username;
if($_POST["user_type"]=="participant")
{
participant($password);
}
elseif($_POST["user_type"]=="admin")
{
admin($username, $password);
}
elseif($_POST["user_type"]=="staff")
{
staff($username, $password);
}
elseif($_POST["user_type"]=="lecturer")
{
lecturer($username, $password);
}
?>
Here i just need usertype, username and password to make login decisions
I notice you're referencing $('.login-form') in one section of your code and $('#login-form') in another. If your form is in fact using a class instead of an ID, the .serialize() method will return an empty array. Update it to $('.login-form input') (note the period instead of the hash).
More info on jQuery selectors: https://api.jquery.com/category/selectors/
Try this i've tried and its working just fine:
var var_username=$("Id of input box for username").val();
var var_password= $("Id of input box for password").val();
$.post(URL,
{
username: var_username,
password: var_password
},
success:function(data)
{
//your message here..
}
);

Ajax, add to database and update div content

Okay, so I am trying to use ajax. I've tried several ways of doing this but nothing is working for me. I believe the main problem I have is that ajax won't add to my database, the rest is managable for me.
Here is the relevant ajax-code:
$(document).ready(function(){
console.log($("going to attach submit to:","form[name='threadForm']"));
$("form[name='threadForm']").on("submit",function(e){
e.preventDefault();
var message = $("#message").val();
//assumming validate_post returns true of false(y)
if(!validatepost(message)){
console.log("invalid, do not post");
return;
}
console.log("submitting threadForm");
update_post(message);
});
});
function update_post(message){
var dataString = "message=" + message;
alert(dataString);
$.ajax({
url: 'post_process.php',
async: true,
data: dataString ,
type: 'post',
success: function() {
posts();
}
});
}
function posts(){
console.log("getting url:",sessionStorage.page);
$.get(sessionStorage.page,function(data){
$("#threads").html(data);
});
}
function validatepost(text){
$(document).ready(function(){
var y = $.trim(text);
if (y==null || y=="") {
alert("String is empty");
return false;
} else {
return true;
}
});
}
Here is the post_process.php:
<?php
// Contains sessionStart and the db-connection
require_once "include/bootstrap.php";
$message = $con->real_escape_string($_POST["message"]);
if (validateEmpty($message)){
send();
}
function send(){
global $con, $message;
$con->create_post($_SESSION['username'], $_SESSION['category'], $_SESSION("subject"), $message);
}
//header("Location: index.php");
?>
And lastly, here is the html-form:
<div id="post_div">
<form name="threadForm" method="POST" action="">
<label for="message">Meddelande</label><br>
<textarea id="message" name="message" id="message" maxlength="500">
</textarea><br>
<input type="submit" value="Skicka!" name="post_btn" id="post_btn"><br>
</form>
create_post is a function I've written, it and everything else worked fine until I introduced ajax.
As it is now, none of the console.log:S are getting reached.
Ajax works when jumping between pages on the website but the code above literally does nothing right now. And also, it works if I put post_process.php as the form action and don't comment out the header in post_process-php.
I apologize for forgetting some info. I am tired and just want this to work.
I would first test the update_post by removing the button.submit.onclick and making the form.onsubmit=return update_post. If that is successful place the validate_post in the update_post as a condition, if( !validate_post(this) ){ return false;}
If it's not successful then the problem is in the php.
You also call posts() to do what looks like what $.get would do. You could simply call $.get in the ajax return. I'm not clear what you are trying to accomplish in the "posts" function.
First you can just submit the form to PHP and see if PHP does what it's supposed to do. If so then try to submit using JavaScript:
$("form[name='threadForm']").on("submit",function(e){
e.preventDefault();
//assumming validate_post returns true of false(y)
if(!validate_post()){
console.log("invalid, do not post");
return;
}
console.log("submitting threadForm");
update_post();
});
Press F12 in Chrome or firefox with the firebug plugin installed and see if there are any errors. The POST should show in the console as well so you can inspect what's posted. Note that console.log causes an error in IE when you don't have the console opened (press F12 to open), you should remove the logs if you want to support IE.
Your function posts could use jQuery as well as it makes the code shorter:
function posts(){
console.log("getting url:",sessionStorage.page);
$.get(sessionStorage.page,function(data){
$("#threads").html(data);
});
}
UPDATE
Can you console log if the form is found when you attach the event listener to it?
console.log($("going to attach submit to:","form[name='threadForm']"));
$("form[name='threadForm']").on("submit",function(e){
....
Then set the action of the form to google.com or something to see if the form gets submitted (it should not if the code works). Then check out the console to see the xhr request and see if there are any errors in the request/responses.
Looking at your code it seems you got the post ajax request wrong.
function update_post(message){
console.log(message);
$.ajax({
url: 'post_process.php',
async: true,
//data could be a string but I guess it has to
// be a valid POST or GET string (escape message)
// easier to just let jQuery handle this one
data: {message:message} ,
type: 'post',
success: function() {
posts();
}
});
UPDATE
Something is wrong with your binding to the submit event. Here is an example how it can be done:
<!DOCTYPE html>
<html>
<head>
<script src="the jquery library"></script>
</head>
<body>
<form name="threadForm" method="POST" action="http://www.google.com">
<label for="message">Meddelande</label><br>
<textarea id="message" name="message" id="message" maxlength="500">
</textarea><br>
<input type="submit" value="Skicka!" name="post_btn" id="post_btn"><br>
</form>
<script>
$("form[name='threadForm']").on("submit",function(e){
e.preventDefault();
console.log("message is:",$("#message").val());
});
</script>
</body>
</html>
Even with message having 2 id properties (you should remove one) it works fine, the form is not submitted. Maybe your html is invalid or you are not attaching the event handler but looking at your updated question I think you got how to use document.ready wrong, in my example I don't need to use document.ready because the script accesses the form after the html is loaded, if the script was before the html code that defines the form you should use document ready.

Form submit without going to the target page

I have question regarding form submit. I have this simple form on processFabrication.php to submit all the variables then process it to the database in another page called processExceededQty.php
Co, in processFabrication.php, I have
echo "<form action='processExceededQty.php' method='post'>";
When I click submit it goes to the processExceededQty.php.
What I am aiming to do is,
When user click submit, display confirmation yes/no with popup
After user click yes with the confirmation window, stay in processFabrication.php but methods in processExceededQty.php is still executed.
When user click no on the popup, go back and don't do form action
Any help would be greatly appreciated.
Something like this in your javascript:
function doSubmit(){
if (confirm('Are you sure you want to submit?')) {
// yes
return true;
} else {
// Do nothing!
return false
}
}
add the onsubmit to your form in html:
<form action='processExceededQty.php' method='post' onsubmit='doSumit()'>
Addition to #N0M3 answer.
Include below script in your <head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
and slight change in your function
function doSubmit(){
if (confirm('Are you sure you want to submit?')) {
// yes
$(this).submit(function(e){
e.preventDefault();
});
jQuery.ajax({
url : 'processExceededQty.php',
data : {'username':username}, // where first 'username' is your field name, and second one is your field's value
method: 'post',
success: function(data) {
// data is variable which has return data from `processExceededQty.php`
// do whatever you want with data
}
});
} else {
// Do nothing!
return false;
}
}
Use function on the "onsubmit" of the form like below,
<form action='processExceededQty.php' method='post' onsubmit='reutrn show_pop_up()'>
And on script you ca write following
<script>
function show_pop_up()
{
// show pop up
if(op_up_return =="Yes")
return true;
else
return false;
}
</script>
Hope this will help.

CodeIgniter Javascript form submission

I would first want to say that I am very new to javascript and jQuery.
Its a very silly and simple problem I suppose, and I am aware there are plenty of questions on this, and I did try all of them. Though I cant seem to solve my problem.
I have an input field and a submit button. On clicking submit I would like to save the content of the input filed into the database, and continue to remain in the same page with content on page as is.
My Javascript code is as follows:
<script type="text/javascript">
$(document).ready(function()
{
$('#submit').submit(function(e)
{
e.preventDefault();
var msg = $('#uname').val();
$.post("c_test/test_submit", {uname: msg}, function(r) {
console.log(r);
});
});
});
</script>
And my html code as follows ( I use codeigniter):
$this->load->helper('form');
echo form_open();
$data =array ('name'=>'uname','id'=>'uname');
echo form_input($data) . '<br />';
$data=array('name'=>'submit','id'=>'submit','value'=>'Submit');
echo form_submit($data);
echo form_close();
I would be very grateful if anyone could point out my stupidity. Thanks!
You are using
$('#submit').submit(function(e){ ... });
In this case submit is the button/input's id and it has no such an event like submit, instead you can use click event, like
$('#submit').click(function(e){ ... });
or
$('#submit').on('click', function(e){ ... });
Otherwise, you can change the following line
echo form_open();
to
echo form_open('c_test/test_submit', array('id' => 'myform'));
and instead of
$('#submit').click(function(e){ ... });
you can use
$('#myform').submit(function(e){
e.preventDefault();
var msg = $('#uname').val();
var url=$(this).attr('action');
$.post(url, {uname: msg}, function(r) {
console.log(r);
});
});
or
$('#myform').on('submit', function(e){
e.preventDefault();
var msg = $('#uname').val();
var url=$(this).attr('action');
$.post(url, {uname: msg}, function(r) {
console.log(r);
});
});
It seems like the element with an id of "submit" is the submit button for the form - <input type="submit">. However, the submit event is fired by the form, not the submit button, so your bound event handler won't fire.
Either move the "submit" id onto the form, or change the selector when binding the submit event handler:
$('form').submit(function(e) {
// handle submit event from the form
});
You have to do it like this:
<?php
$this->load->helper('form');
echo form_open('', array( 'id' => 'myform'));
..
and:
$('#myform').submit(function(e)
{
e.preventDefault();
var msg = $('#uname').val();
$.post("c_test/test_submit", {uname: msg}, function(r) {
console.log(r);
});
return false;
});
The submit event always goes to the form and not to the form button.
perhaps like this:
$data=array('name'=>'submit','id'=>'submit','value'=>'Submit','onsubmit'=>'return false;');
This will stop the form from posting which will in turn stop the page from refreshing. However, it will require that you submit the form via ajax.

Help submitting a form to a JQuery script using a javascript submit() function

I attempted to ask this question last week without a resolution. I am still unable to get this to work. What I would like to do is submit data entered through a WYSIWYG javascript editor to a JQuery script I have that will first tell the user if they are trying to submit an empty textbox The last thing I need it to do is tell the user if their data was entered successfully or not.
I am having a problem inside the JQuery script as nothing is being executed when I click the save button.
This editor uses javascript submit() that is tied to a small save icon on the editor. When the user presses the button on the editor, it fires the function I have in the form tag. That's about as far as I was able to get.
I think there is an issue with the form tag attributes because when I click anywhere on the editor, the editor jumps down off the bottom of the screen. I believe it has something to do with the onclick event I have in the form tag.
The first part of the JQuery script is supposed to handle form validation for the textarea. If that's going to be really difficult to get working, I'd be willing to let it go and just handle everything server side but I just need to get the data POSTed to the JQuery script so that I can send it to my php script.
Thanks for the help guys.
<form name="rpt" class="rpt" id="rpt" action="" onclick="doSave(); return false;">
function doSave()
{
$(function()
{
$('.error').hide();
$(".rpt").click(function()
{
$('.error').hide();
var textArea = $('#report');
if (textArea.val() == "")
{
textArea.show();
textArea.focus();
return false;
}
else
{
return true;
}
var dataString = '&report='+ report;
alert (dataString);return false;
$.ajax({
type: "POST",
url: "body.php?action=customer",
data: dataString,
dataType: 'json',
success: function(data){
$('#cust input[type=text]').val('');
var div = $('<div>').attr('id', 'message').html(data.message);
if(data.success == 0) {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-error');
} else {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-success');
}
$('body').append(div);
}
});
return false;
});
});
}
There are a few things you need to change. Firstly this:
<form name="rpt" class="rpt" id="rpt" action="" onclick="doSave(); return false;">
isn't the jQuery way. Plus its not the click() event you want. Do this:
<form name="rpt" class="rpt" id="rpt" action="">
<script type="text/javascript">
$(function() {
$("#rpt").submit(do_save);
});
</script>
The construction:
$(function() {
..
});
means "when the document is ready, execute this code". It is shorthand for and exactly equivalent to the slightly longer:
$(document).ready(function() {
..
});
This code:
$("#rpt").submit(doSave);
means "find the element with id 'rpt' and attach an event handler to it such that when the 'submit' event is executed on it, call the do_save() function".
And change doSave() to:
function doSave() {
$('.error').hide();
$(".rpt").click(function() {
$('.error').hide();
var textArea = $('#report');
if (textArea.val() == "") {
textArea.show();
textArea.focus();
return false;
} else {
return true;
}
var dataString = '&report='+ report;
alert (dataString);return false;
$.ajax({
type: "POST",
url: "body.php?action=customer",
data: dataString,
dataType: 'json',
success: function(data){
$('#cust input[type=text]').val('');
var div = $('<div>').attr('id', 'message').html(data.message);
if (data.success == 0) {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-error');
} else {
$('#cust input[type=text]').val('');
$(div).addClass('ajax-success');
}
$('body').append(div);
}
});
});
return false;
}
Note: return false is in the correct place now so it actually prevents the form submitting back to the server. action="" just means the form will submit back to its current location so you have to prevent that.
function X() {
$(function() {
//... things you want to do at startup
});
};
Doesn't do what you want. Nothing is ever executed, because you never tell it to be executed.
You might want to try something like:
<script type="text/javascript">
jQuery(function($) {
//... things you want to do at startup
});
</script>
Also, you want the onsubmit event of the form. You can use
$('#theform').submit(function() {
//... perform the ajax save
});
In addition, you may want to look into the Form plugin.

Categories