How to post a variable to a php file using ajax - php

I want to pass a variable to college.php where that variable can be used to fetch data.
I already tried get and post methods using form, but then using get the variable values are visible in address bar and using get form resubmission alert appears
this is what I used.
<form class="morestories"method="get" enctype="multipart/form-data" action="college.php">
<input type="hidden" name="collegename" value="<?php $collegename=$row['name']; echo $collegename; ?>">
<input class="morestoriesbutton" type="submit" name="collegeselectlink" value="More Stories" />
</form>
also the variables i am passing to college.php file, on refresh it should be used again to access data so any possible help

This is a example where I am passing name and password to a php function ,
you can refer this and apply it accordingly to your condition.
$(document).ready(function(){
//this is my button
$("#click").click(function(){
// getting username and password from my html
username = $("#name").val();
password = $("#pad").val();
if(username=="" || password==""){
alert("please check the details");
} else {
$.ajax({ url: 'reverse.php',
data: {username:username,password:password},
type: 'post',
success: function(output) {
alert(output);
}
});
}
});
});

Related

jQuery trigger previously defined onclick from link in new window

I am submitting a form using jquery onclick. On the PHP side, it checks to see if there is already an existing document by the same name. If true, a small form is returned in the response with 3 options, dependent on the record data. Those options are displayed in a message window. One of those selections needs to resubmit the previous form data, substituting the new name.
The problem is, the change name form does not exist when the page is loaded and thus does not recognize the ClickCheck class in the new form.
How can I resubmit this form with the new DocName?
The submit in the main form (actually this is one of four submits)
<a class="ClickCheck" id="Create" href="javascript:void(0)">Create Bill</a>
The jQuery:
$('.ClickCheck').click(function()
{
var ButtonID = $(this).attr('id');
$('#Clicked').val(ButtonID);
var Form = $('#TheForm');
if(ButtonID == "Save")
{
// Do save code
}
else
{
var FormData = Form.serialize();
$.ajax(
{
type: "POST",
url: "scripts/Ajax.php",
data: FormData,
success: function(response)
{
$('#MWContent').html(response);
$('#MessageWindow').show();
}
});
}
});
Then, in the response, I have:
<form id="ChangeName" name="ChangeName">
Use another name:
<input type="text" id="DocName" name="DocName" size="60" maxlength="60" value="" placeholder="Document Name" />
<a class="ClickCheck" id="NewName" href="javascript:void(0)">Go</a>
</form>
The idea is to have the "NewName" resubmit the form (with the new name, of course.) I can, of course, detect that in the click function.
You can attach the click() event to the document to make it global.
$(document).on('click', '.ClickCheck', function(e){
e.preventDefault() // <<<< Either this
// Do stuff
return false // <<<< Or this
})
http://api.jquery.com/on/
Also don't use href="javascript:void(0)", use return false or e.preventDefault() in the callback function.

Sending form ID to AJAX on button click

I have a question that's blowing my mind: how do I send a form ID stored in a PHP variable to my AJAX script so the right form gets updated on submit?
My form is a template that loads data from MySQL tables when $_REQUEST['id'] is set. So, my form could contain different data for different rows.
So, if (isset($_REQUEST["eid"]) && $_REQUEST["eid"] > 0) { ... fill the form ... }
The form ID is stored in a PHP variable like this $form_id = $_REQUEST["eid"];
I then want to use the button below to update the form if the user changes anything:
<button type="submit" id="update" class="form-save-button" onclick="update_form();">UPDATE</button>
and the following AJAX sends the data to update.php:
function update_form() {
var dataString = form.serialize() + '&page=update';
$.ajax({
url: 'obt_sp_submit.php', // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: dataString, // serialize form data
cache: 'false',
beforeSend: function() {
alert.fadeOut();
update.html('Updating...'); // change submit button text
},
success: function(response) {
var response_brought = response.indexOf("completed");
if(response_brought != -1)
{
$('#obt_sp').unbind('submit');
alert.html(response).fadeIn(); // fade in response data
$('#obt_sp')[0].reset.click(); // reset form
update.html('UPDATE'); // reset submit button text
}
else
{
$('#obt_sp').unbind('submit');
alert.html(response).fadeIn();
update.html('UPDATE'); // reset submit button text
}
},
error: function(e) {
console.log(e)
}
});
}
I'd like to add the form's id to the dataString like this:
var dataString = form.serialize() + '&id=form_id' + '&page=update';
but I have no idea how. Can someone please help?
The most practical way as stated above already is to harness the use of the input type="hidden" inside a form.
An example of such would be:
<form action="#" method="post" id=""myform">
<input type="hidden" name="eid" value="1">
<input type="submit" value="Edit">
</form>
Letting you run something similar to this with your jQuery:
$('#myform').on('submit', function(){
update_form();
return false;
});
Provided that you send what you need to correctly over the AJAX request (get the input from where you need it etc etc blah blah....)
You could alternatively include it in the data string which; I don't quite see why you would do.. but each to their own.
var dataString = form.serialize() + "&eid=SOME_EID_HERE&page=update";
Sounds like a job for a type=hidden form field:
<input type="hidden" name="eid" value="whatever">
You have to write the string dynamically with PHP:
var dataString = form.serialize() + "&id='<?php echo $REQUEST['eid'] ?>'+&page=update";
On the server you can write Php code on the document, and they will be shown as HTML/JS on the client.

Change Password PHP/Ajax/JQuery

I'm trying to create a form for changing a users password. No errors are being generated in the console but nothing is being updated. The validation side is also working so it must be down to the Ajax part?
Disclaimer: I know I shouldn't be using mysql in PHP, but I'm trying to get the basics down and will learn mysqli at a later date :)
Also, config.php is used in multiple other functions so I know config.php is fine.
Any idea what is going wrong?
HTML:
<fieldset>
<form method="post" name="password-form" id="form-password">
<label>Password:</label> <br>
<input type="password" name="password" id="password" value="" size="32" />
<br>
<br>
<label>Re-Enter Password:</label> <br>
<input type="password" name="password-check" id="password-check" value="" size="32" />
<br>
<br>
<input type="submit" value="Submit" id="passsubmit">
</form>
</fieldset>
JQuery:
$(function(){
$("#passsubmit").click(function(){
$(".error").hide();
var hasError = false;
var newpass = $("#password").val();
var checkVal = $("#password-check").val();
if (newpass == '') {
$("#password").after('<span class="error">Please enter a password.</span>');
hasError = true;
} else if (checkVal == '') {
$("#password-check").after('<span class="error">Please re-enter your password.</span>');
hasError = true;
} else if (newpass != checkVal ) {
$("#password-check").after('<span class="error">Passwords do not match.</span>');
hasError = true;
}
if(hasError == true) {return false;}
if(hasError == false) {
$.ajax({
type: "POST",
url: "resource/changepassword.php",
data: {newpass:newpass},
success: function(){}
});
};
});
});
PHP:
<?php
session_start();
include('config.php');
$user_check=$_SESSION['login_user'];
$newpass=$_POST['newpass'];
$sql_rec = "select UserID from useradmin where username='$user_check' ";
$rs_rec = mysql_query($sql_rec);
$data_rec = mysql_fetch_object($rs_rec);
$userID = $data_rec->UserID;
$updatesql="UPDATE useradmin SET passcode='$newpass' WHERE UserID=$userID";
mysql_query($updatesql, $bd) or die(mysql_error());
?>
$bd is my MySQL connection details from config.php.
UPDATE:
I've added <div id="passsubmit2">123</div> to my page and changed the jquery to:
$(function(){
$("#passsubmit2").click(function(){
And it works perfectly, so it's only when using the form button that it doesn't work?
Figured it out eventually.
I needed to add event.preventDefault(); to prevent the normal form submit from firing.
Since you are sending form data to your server through an Ajax request, you dont need that input of submit type at first place, because this will try to submit the form on click and you will have to write additional code for stopping the default functionality of that submit button. So replace that submit button with simple html button or a link.
change your data inside ajax to
if(hasError == false) {
$.ajax({
type: "POST",
url: "resource/changepassword.php",
data: {
newpass : newpass,
},
success: function(){}
});
};
because you are not sent the data to server and info variable not declared
Make sure to pass all the required data to the PHP server. Right now, from what I can see, you are passing an empty variable.
info={
newpass : newpass,
checkVal: checkVal
};
$.ajax({
type: "POST",
url: "resource/changepassword.php",
data: info,
success: function(response){
console.log(response);
}
});
On the PHP side:
<?php
$newPassword=$_POST['newpass '];
EDIT: Going a bit further with this, you really want to store a user ID (unique numeric ID) in the session rather then the username. Referencing through-out your mysql DB using the username as a unique value is a very poor idea (trust me, I made the same mistake).
Also, you should require users to enter their old password whenever changing a current password (what if they left the website up on their computer).

ajax validation for multiple forms on page, all have same class

basically i am making a CMS and want to have in post editing.
How it works atm is that the blog post is echoed out (PHP) and there is a hidden ckeditor which when an edit button is clicked gets displayed. The edit button is then replaced with a save button.
This all works fine and good however the issue comes when saving the blog post.
the php works fine, and the ajax validation also works fine but ONLY when there is 1 blog post.
When there is more than 1 post the errors come. The issue is that it seems to be that the save post button is sending all of the data from every blog post. I checked it with the firebug net and saw that all data is being sent.
I just need a way of making it so that the save button in the form, only affects the data inside of that form. At the moment the error / success message is displayed by all of them.
Here is the post echoed out:
<div class="blogtest">
<form action="process/updatepost.php" class="updatepost" method="post">
<input type="button" class='.$editenabled.' value="Edit">
<input type="submit" class="saveupdatebutton" value="Save">
<input type="hidden" class="postid" name="postid" value="'.$postID.'">
<div class="text">
<div class="buildtext">'.$text.'</div>
<div class="editor"><textarea name="ckeditor" class="ckeditor">'.$text.'</textarea></div>
</div>
</form>
</div>
This is the javascript:
$(document).ready(function(){
$(".updatepost").submit(function(){
$(".error").remove();
$(".success").remove();
// If there is anything wrong with
// validation we set the check to false
var check = true;
// Get the value of the blog update post
var blogpost = $('.ckeditor').val();
// Validation
if (blogpost == '') {
check = false;
$('.ckeditor').after('<div class="error">Text Is Required</div>');
}
// ... goes after Validation
if (check == true) {
$.ajax({
type: "POST",
url: "process/updatepost.php",
data: $(".updatepost").serialize(),
dataType: "json",
success: function(response){
if (response.databaseSuccess)
$('.ckeditor').after('<div class="success">Post Updated</div>');
else
$('.ckeditor').after('<div class="error">Something went wrong!</div>');
}
});
}
return false;
});
});
Thanks for reading. Hope you can help.
You just need to limit the validation logic to the form that's actually being submitted. Right now $('.ckeditor').after('<div class="error">Text Is Required</div>'); is modifying all items that match the ckeditor class name. See below -- I've added a variable called $targetForm which grabs the form being submitted and modified the code appropriately to only reference the children of that form.
$(document).ready( function() {
$(".updatepost").submit(function() {
var $targetForm = $(this);
$targetForm.find(".error").remove();
$targetForm.find(".success").remove();
// If there is anything wrong with
// validation we set the check to false
var check = true;
// Get the value of the blog update post
var $ckEditor = $targetForm.find('.ckeditor'),
blogpost = $ckeditor.val();
// Validation
if (blogpost == '') {
check = false;
$ckeditor.after('<div class="error">Text Is Required</div>');
}
// ... goes after Validation
if (check == true) {
$.ajax({
type: "POST",
url: "process/updatepost.php",
data: $targetForm.serialize(),
dataType: "json",
success: function(response){
if (response.databaseSuccess)
$ckeditor.after('<div class="success">Post Updated</div>');
else
$ckeditor.after('<div class="error">Something went wrong!</div>');
}
});
}
return false;
});
});

Ajax form , PHP process and return errors if there's any , if not success

I found a tutorial here : http://tutorialzine.com/2009/08/creating-a-facebook-like-registration-form-with-jquery/ (please take a look)
It's a nice tutorial, I followed everything there and remove extra stuff I don't want , like the functions.php with generate_function option as I am not in need of birthday etc. stuff.
All I want is a NAME(usrname) , EMAIL(email) , Password(password) , when the user click on "REGISTER" button (which is the form submit button), the script I got from the tutorial will send the data over to "regprocess.php" which contains validation check codes like checking if the submitted form data is empty.
But when I click REGISTER , the data is not sent back (the error message) from the "regprocess.php" nor the success message.
When i check with my firebug , the JSON response is showing the full php code like the one below(scroll down).
Here's my code :
HTML-
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript" src="register.js"></script>
<form id="regForm" action="regprocess.php" method="post">
<label for="usrname">Name:</label>
<input id="usrname" name="usrname" type="text" value="" class="nor">
<label for="email">Email:</label>
<input id="email" name="email" type="text" value="" class="nor">
<label for="password">Password:</label>
<input id="password" name="password" type="password" value="" class="nor">
<table><tr><td style="width:290px;"><div id="error"> </div></td><td><input name="register" type="submit" value="Register" id="regbtn"><center><img id="loading" src="images/load.gif" alt="Registering..." /></center></td></tr></table>
</form>
Okay the Ajax script is in "register.js" above.
Ajax script(register.js)-
$(document).ready(function(){
$('#regForm').submit(function(e) {
register();
e.preventDefault();
});
});
function register()
{
hideshow('loading',1);
hideshow('regbtn',0);
error(0);
$.ajax({
type: "POST",
url: "regprocess.php",
data: $('#regForm').serialize(),
dataType: "json",
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
hideshow('loading',0);
hideshow('regbtn',1);
}
});
}
function hideshow(el,act)
{
if(act) $('#'+el).css('visibility','visible');
else $('#'+el).css('visibility','hidden');
}
function error(act,txt)
{
hideshow('error',act);
if(txt) $('#error').html(txt);
}
CSS:
Regbtn is the submit button , it's visibility is set to visible
loading is set to hidden
error is set to hidden
When a user click on Regbtn , loading visibility will become visible while Regbtn hides(visibility:hidden).
It's done in the Ajax script(register.js).
Okay now the php:
PHP(regprocess.php)-
if(empty($_POST['usrname']) || empty($_POST['email']) || empty($_POST['password']))
{
die('{status:0,"txt":"Fill in All Fields"}');
}
if(!(preg_match("/^[\.A-z0-9_\-\+]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $_POST['email'])))
die('{status:0,"txt":"Please Provide a Valid Email"}');
echo '{status:1,txt:"registered.html"}';
This checks whether the username , email and password data is empty , if yes , returns a message which will be displayed in the Error(#error in html) , it also checks whether email provided is valid.
If everything else is right , user will be directed to registered.html
But i think the script can't get the error message back from the php.
I hope someone can help me. Thanks.
Have a nice day.
hmm not too much of an answer but what I do on my forms is a I submit via ajax and put the result from the php page in the parent of the form.
below is the plugin in code. it works when the form is a child of a div by default.
(function($){
$.fn.extend({
//pass the options variable to the function
ajaxForm: function(options)
{
//Set the default values, use comma to separate the settings, example:
var defaults =
{
target: 'div'
}
var options = $.extend(defaults, options);
return this.each(function()
{
var o=options
$(this).submit(function(event)
{
event.preventDefault();//stop from submiting
//set needed variables
var $form = $(this)
var $div = $form.parent(o.target)
$url = $form.attr("action");
//submit via post and put results in div
$.post( $url, $form.serialize() , function(data)
{ $div.html(data) })
})
});
}
});
})(jQuery);
note this will run for every form so change it as you would wish.
whatever you want to display just echo on the php page. also this is made for post and the php page will access anything just like any other form being with post.
also it wouldn't be hard to modify if you felt necessary to send as json instead.
You need to put php tags around the php code, like this:
<?php
if(empty($_POST['usrname']) || empty($_POST['email']) || empty($_POST['password']))
{
die('{status:0,"txt":"Fill in All Fields"}');
}
if(!(preg_match("/^[\.A-z0-9_\-\+]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $_POST['email'])))
die('{status:0,"txt":"Please Provide a Valid Email"}');
echo '{status:1,txt:"registered.html"}';
?>

Categories