This question already has an answer here:
How to handle multiple actions using a single html form
(1 answer)
Closed 9 years ago.
I've a form "dataEmp" where user has to enter username and password and "submit".I have successfully sent the form data to "checkLogin.php" file but what if i want to send that same form to another file, "logout.php". After doing some searching i found I've to use jquery ajax to do so. I'm not very familiar with ajax so if you give the full code, it'll be appreciated.
<form id="dataEmp" name="dataEmp" action="checkLogin.php" method="post">
.
. //user details
.
</form>
Here i am just giving your idea to make call with ajax on success page to where you wish to store data just call like below
$(document).ready(function() {
$('#loginform').submit(function(e) { // fetch data from form to submit to action.
e.preventDefault();
$.ajax({
type: "POST",
url: '/class/check_login.php',
data: $(this).serialize(),
success: function(data)
{
if (data === 'Login') {
window.location = '/user-success.php';
}
else {
alert('Invalid Credentials');
}
}
});
});
});
but you should have to write you php code in your way to handle this request in server side.
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am using AJAX to call a PHP file that does email validation and outputs simple text that gets returned to the AJAX Success. I am using the text returned to create variables to represent which error to display. I am having trouble using these variables, the form still submits. What could I be doing wrong?
My Code:
if (email != 0) {
// Run AJAX email validation and check to see if the email is already taken
$.ajax({
type: "POST",
url: "checkemail.php",
data: dataString,
success: function(data) {
if (data == 'invalid') {
var invalid= 1;
}
else if (data == 'taken') {
var taken= 1;
}
}
});
}
if (invalid == 1) {
alert('invalid email');
error= true;
}
if (taken == 1) {
alert('email taken');
error= true;
}
if (error == true) {
return false;
}
Is this AJAX call inside a click event? If so, you may want to use event.preventDefault() function to avoid triggering the form submission:
event.preventDefault();
Have a look to the example in the documentation
You should have two things in consideration:
1) if you're ajax call is triggered by a link or submit button , you MUST use preventDefault function
2) in your "checkmail.php" don't forget to call exit function in the end of call
This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 9 years ago.
i have made a form that will be send a input type file, in my server side i want to get $_FILES value so i used print_r($_FILES), but in my ajax response i don't get anything value, here my code..
<form id="my_form">
<input type="file" id="image_file" name="image_file"/>
</form>
$('#my_form').submit(function() {
var data = $('#my_form').serialize();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: data,
enctype: 'multipart/form-data',
success: function(response) {
alert(response);
},
});
return false;
});
and here my php code
<?php
$name = $_FILES['image_file']['name']; // get the name of the file
$type = $_FILES['image_file']['type']; // get the type of the file
$size = $_FILES['image_file']['size'];
echo $name;
//or
print_r($_FILES);
?>
please help me ...
thanks..
AjaxFileUpload
Maybe this plugin could help you fix the problem.
The way of this plugin doing is just like the way people did before ajax theory proposed which is using an iframe tag handle all the request without refreshing the page.
Without HTML5,I don't think we can use XMLHttpRequest to upload file.
First of all I'd like to ask that you don't suggest I turn to a jQuery plugin to solve my issue. I'm just not willing to make my app work with a plugin (and it prevents me from learning!)
I have a form with a bunch of fields that I'm passing to my backend via the use of jQuery's $.post() This is what I have as my jQuery function:
$.post(
"/item/edit",
$("#form").serialize(),
function(responseJSON) {
console.log(responseJSON);
},
"html"
);
This is how I opened my form:
<form action="http://localhost/item/edit" method="post" accept-charset="utf-8" class="form-horizontal" enctype="multipart/form-data">
This was auto generated by codeigniter's form_open() method (hence why action="" has a value. Though this shouldn't matter because I don't have a submit button at the end of the form)
Within my #form I have this as my file input: <input type="file" name="pImage" />
When the appropriate button is hit and the $.post() method is called, I have my backend just print the variables like so: print_r($_POST) and within the printed variables the 'pImage' element is missing. I thought that maybe files wouldn't come up as an element in the array so I went ahead and just tried to upload the file using this codeigniter function: $this->upload->do_upload('pImage'); and I get an error: "You did not select a file to upload."
Any idea as to how I can overcome this problem?
You cannot post an image using AJAX, i had to find out here as well PHP jQuery .ajax() file upload server side understanding
Your best bet is to mimic an ajax call using a hidden iframe, the form has to have enctype set to multipart/formdata
Files wont be sent to server side using AJAX
One of the best and simplest JQuery Ajax uploaders from PHP LETTER
all you need is include js in your header normally and Jquery code will be like below
$.ajaxFileUpload({
url:'http://localhost/speedncruise/index.php/snc/upload/do_upload',
secureuri:false,
fileElementId:'file_upload',
dataType: 'json',
data : {
'user_email' : $('#email').val()
},
success: function (data, status) {
// alert(status);
// $('#avatar_img').attr('src','data');
}
,
error: function (data, status, e) {
console.log(e);
}
});
wish this can help you
I can't do this with codeigniter and Ajax, I pass the image to base64 and in the controller I convert into a file again
//the input file type
<input id="imagen" name="imagen" class="tooltip" type="file" value="<?php if(isset($imagen)) echo $imagen; ?>">
//the js
$(document).on('change', '#imagen', function(event) {
readImage(this);
});
function readImage(input) {
var resultado='';
if ( input.files && input.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
//console.log(e.target.result);
subirImagen(e.target.result);
};
FR.readAsDataURL( input.files[0] );
}
}
function subirImagen(base64){
console.log('inicia subir imagen');
$.ajax({
url: 'controller/sube_imagen',
type: 'POST',
data: {
imagen: base64,
}
})
.done(function(d) {
console.log(d);
})
.fail(function(f) {
console.log(f);
})
.always(function(a) {
console.log("complete");
});
}
//and the part of de controller
public function sube_imagen(){
$imagen=$this->input->post('imagen');
list($extension,$imagen)=explode(';',$imagen);
list(,$extension)=explode('/', $extension);
list(,$imagen)=explode(',', $imagen);
$imagen = base64_decode($imagen);
$archivo='archivo.'.$extension;
file_put_contents('imagenes/'.$archivo, $imagen);
chmod('imagenes/'.$archivo, 0777); //I use Linux and the permissions are another theme
echo $archivo; //or you can make another thing
}
ps.: sorry for my english n_nU
Im currently new to PHP and JQuery after having using ASP.Net and C Sharp for the 2 years. I have this major problem in which i require some assistance in.
I have a HTML <input type="submit" id="btnWL" value="Add to Wishlist"> button. Basically when this button is pressed a table called 'wishlist' in the database is checked to see if the current product is already in a wishlist. If no the button will trigger a database save else it will return a JQuery alert pop up error message.
I having difficulty in passing 2 PHP variables: $_SESSION["username"] and $_GET["ProductId"] into this JQuery method:
<script type="text/javascript">
$(document).ready(function() {
$('#btnWL').live('click', function() {
$.post("addToWishlist.php");
});
});
</script>
As you can see this JQuery method must pass those values to an external PHP File which checks for an already exsisting record in the 'wishist' table with those details.
<?php
$WishlistDAL = new WishlistDAL();
$result = $WishlistDAL->get_ProductInWishlistById($_GET["ProductId"]);
if (isset($_POST["isPostBack"])) {
if (isset($_SESSION["username"])) {
if (isset($_GET["btnWL"])) {
//Check if ProductId is in Cart
if (mssql_num_rows($result)>0)
{
//Return an error
//Sumhow this has to trigger an alert box in the above JQuery method
}
else
{
//Write in Wishlist Table
$WishlistDAL->insert_ProductInWishlist($_GET["ProductId"], $_SESSION["username"]);
}
}
}
else
{
//Return Error
}
}
?>
Another problem I have is then displaying an alert box using the same JQuery method for any errors that where generated in the php file.
Any Ideas how I can implement this logic? Thanks in advance.
Your "$.post()" call isn't passing any parameters, and has no callback for interpreting the results:
$.post('addToWishlist.php', { username: something, password: something }, function (response) {
});
The "something" and "something" would probably come from your input fields, so:
$.post('addToWishlist.php', { username: $('#username').val(), password: $('#password').val() }, function (response) {
});
Now the callback function would interpret the response from the server:
$.post('addToWishlist.php', { username: $('#username').val(), password: $('#password').val() }, function (response) {
if (response === "FAIL") {
alert("fail");
}
else {
// ... whatever ...
}
});
Exactly what that does depends on your server code; that "FAIL" response is something I just made up as an example of course.
jQuery accepts an callback:
$(document).ready(function() {
$('#btnWL').live('click', function() {
$.post("addToWishlist.php", {'isPostBack':1}, function(res){
if (res.match(/err/i)){
alert(res);
}
});
});
});
Then, in the php, just (echo('Error adding record')) for this jquery to see there's an error string in the response and pop up the error message.
Other methods would be to use json, or http status codes and $.ajaxError(function(){ alert('error adding'); });.
from what i can tell so far is you'll only need to pass in the product id in and you can do this by appending your $.post call with the value; this will pass to your php script as a query string variable. i'm not sure which php script you posted, but if you're sending your data with jquery, it's using post and not get, so you may need to make an adjustment there and the session data should be available regardless, since it's the same session.
again this is without seeing all the code and since some of it isn't labeled, it's hard to determine. another thing, i like to use $.ajax for most actions like this, you have a lot more room to define and structure, as well as create one generic ajax function to call the methods and post data, as well as make a response callback. here's the documentation for you to look into $.ajax
i hope this helps.
I find this tutorial in 9lessons.com : http://www.9lessons.info/2011/01/gravity-registration-form-with-jquery.html
It's about a registration form with validation.
I want to send data to DB.
// Submit button action
$('#submit').click(function()
{
var email=$("#email").val();
var username=$("#username").val();
var password=$("#password").val();
if(ck_email.test(email) && ck_username.test(username) && ck_password.test(password) )
{
$("#form").show().html("<h1>Thank you!</h1>");
///// if OK
///// Show thanks
//// else
//// Error, try again
}
return false;
});
How can I do ?? I searched in internet in jQuery tutorial and I find much codes ...
This tutorial will walk you the entire process:
http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
It implements jQuery.post and calls a PHP script that will allow you to process the data.
You will need to use Ajax to submit the data to a backend script (such as PHP) to do the actual database interaction. I'd recommend using POST:
http://api.jquery.com/jQuery.post/
you can use jquery post method
$.post("test.php", $("#testform").serialize());
or for more detail visit this link
jquery form post method
Finally I inserted data form to database... I have a problem.. I forgot to verify if email is available or not !
I added this lines from an other tutorial in email verification to test if email exist in DB or not.
First I send email to check_availability.php
if mail exist an error message appear else, the password fiel must appear ...
Like you see in picture, I verify the existence of an email adress and availibality and unavailability message appear but not correctly ...
$('#email').keyup(function()
{
var email=$(this).val();
if (!ck_email.test(email))
{
$(this).next().show().html("Enter valid email");
}
else
{
//$(this).next().hide();
//$("li").next("li.password").slideDown({duration: 'slow',easing: 'easeOutElastic'});
$.ajax
({
type: "POST",
url: "user_availability.php",
data: "email="+ email,
success: function(msg)
{
$("#status").ajaxComplete(function(event, request, settings)
{
if(msg == 'OK')
{
/*$("#email").removeClass('object_error'); // if necessary
$("#email").addClass("object_ok");
$(this).html(' <img align="absmiddle" src="accepted.png" /> ');*/
//////////////////
$(this).next().hide();
$("li").next("li.password").slideDown({duration: 'slow',easing: 'easeOutElastic'});
//////////////
}
else
{
$("#email").removeClass('object_ok'); // if necessary
$("#email").addClass("object_error");
$(this).html(msg);
}
});
}
});
}
});
The tow first comment lines are the default ines used to show the next field //$("li").next("li.password").slid ...
Like you see I add them in Ok test section ....