I'm having a problem when I'm trying to serialize data form.
Here is the code. I have a page1.php that contains the form. And when the form has been sent, through AJAX, I retrieve the form data and then send it to page2.php.
The problem appears, when it's trying to serialize the file field.
page1.php (containing the form)
$(document).ready(function(){
$("#enviar").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "processar_updateUser.php",
data: $("form").serialize(),
success: function(data){
alert(data);
}
});
return false;
});
});
page2.php (processing the form data)
<?php
$personal_name = addslashes(htmlentities($_POST['personalname']));
$name = addslashes(htmlentities($_POST['name']));
$surname = addslashes(htmlentities($_POST['surname']));
$concatnom = $name.".".$surname;
$password = addslashes(htmlentities($_POST['password']));
$adegree = addslashes(htmlentities($_POST['adegree']));
$initials = addslashes(htmlentities($_POST['initials']));
$n = substr($name,0,1);
$c = substr($surname,0,1);
$initials = $n.$c;
$email = addslashes(htmlentities($_POST['email']));// que sigui cadena+#"+cadena+.+cadena
$telephone = addslashes(htmlentities($_POST['telephone'])); //numero y nomes 9
$signature = addslashes(htmlentities($_FILES['signature']['name']));//i have used $_POST, but dind't work
?>
Try this (Replaces JQuery selectors according to your html):
var formData = new FormData();
formData.append('personalname', $("#personalname").val());
formData.append('name', $("#name").val());
formData.append('surname', $("#surname").val());
formData.append('password', $("#password").val());
formData.append('adegree', $("#adegree").val());
formData.append('initials', $("#initials").val());
formData.append('email', $("#email").val());
formData.append('telephone', $("#telephone").val());
formData.append('signature', $('#signature')[0].files[0]);
$(document).ready(function(){
$("#enviar").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "processar_updateUser.php",
data: formData,
success: function(data){
alert(data);
}
});
return false;
});
});
This can be tedious, but it is how I managed to send images to the backend
The method $('#signature') will return a JQuery input object.
This: $('#signature')[0] returns the HTML input tag.
This: $('#signature')[0].files return a JQuery object that contains all files you have selected.
And finally, this: $('#signature')[0].files[0] will return the first file in the JQuery object...
I'm assuming you accept just one file... If not, you must append to formData every file stored in $('#signature')[0].files
Hope this help.
Regards
I had the same problem some time ago. I used this plugin jQuery Form Plugin for mixed forms - data plus files,or in other case this one blueimp but this one only for file upload.
I use them a lot and they work like a charm and are easy to integrate.
Hope this will help.
Related
I am very new to ajax.
What I am trying to do here is bringing back some variables from a PHP file that I've wrote mainly to process a HTML form data into MySql db table.
After some research I concluded that I need to use json (first time) and I must add the part dataType:'json' to my ajax.
My problem is that after adding this part, I am no more able to submitting the form!
Can anyone please let me know what am I doing wrong here?
I just need to process the PHP code and return the three mentioned variables into a jquery variable so I can do some stuff with them.
Thank you in advance.
AJAX:
var form = $('#contact-form');
var formMessages = $('#form-messages');
form.submit(function(event) {
event.preventDefault();
var formData = form.serialize();
$.ajax({
type: 'POST',
url: form.attr('action'),
data: formData,
dataType: 'json', //after adding this part, can't anymore submit the form
success: function(data){
var message_status = data.message_status;
var duplicate = data.duplicate;
var number = data.ref_number;
//Do other stuff here
alert(number+duplicate+number);
}
})
});
PHP:
//other code here
$arr = array(
'message_status'=>$message_status,
'duplicate'=>$duplicate,
'ref_number'=>$ref_number
);
echo json_encode($arr);
The way you have specified the form method is incorrect.
change
type: 'POST',
to
method: 'POST',
And give that a try. Can you log your response and post it here ? Also, check your console for any errors.
If your dataType is json, you have to send Json object. However, form.serialize() gives you Url encoded data. (ampersand separated).
You have to prepare data as json object :
Here is the extension function you can add:
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
Credit goes to : Difference between serialize and serializeObject jquery
I have done some reading and I think i need to use json for this. I have never used this before. I am trying to accomplish this, but in jQuery
$email_exist_check = mysqli_query($connect, "SELECT * FROM accounts WHERE email='$desired_email'") or die(mysql_error());
$email_exist = mysqli_num_rows($email_exist_check);
if ($email_exist == 0) {
//stop and make user write something else
} else {
//keep going
}
I am switching my website over from php to jQuery, which is also very new to me but seems so much better. Here is a piece of my jQuery. I am validating a form. The form works and submits, but now i want to see if the email exists in my database before submission. How would i do this?
if (email == "") {
$("#error5").css("display", "inline");
$("#email").focus();
return false;
}
// Im guessing the new code would go here
var dataString = $("#acc_form").serialize();
var action = $("#acc_form").attr('action');
$.ajax({
type: "POST",
url: action,
data: dataString,
success: window.location.assign("cashcheck_order.php")
});
This is a basic ajax call using jquery
var thing1; //thing 1 to use in js
var thing2; //thing 2 to use
var form = ("#acc_form"); //localize the form to a variable. you don't need to keep looking it up
var dataString = form.serialize();
var action = form.attr('action');
$.ajax({
url: action,
data: dataString,
type: "post",
success: function(data){
var responseData = $.parseJSON(data); //json native decoding if available, otherwise will do it with jquery
thing1 = responseData["thing1"];
thing2 = responseData["thing2"];
},
error: function(data){
console.log("error", data);
}
});
On the php side, to bring the vars in you use
$input1 = isset($_GET["name_of_input1"]) ? $_GET["name_of_input1"] : "";
if this is set, set this value, else set blank.
you can use $_POST, $_REQUEST if you prefer.
do not forget to sanitize your inputs.
Now to send it back to the js file
$dataToReturn = [
"thing1"=>"I'm thing 1",
"thing2"=>"I'm thing 2"
];
//sending back data
echo json_encode($dataToReturn);
I'm learning AJAX by reading some online tutorials, so please understand I am very new to AJAX and programming in general. I have managed to do the following with 3 selectboxes:
populates selectbox 2 based on selection from selectbox 1
populates selectbox 3 based on selection from selectbox 2
Everything is working perfectly
Here is my code:
$(document).ready(function()
{
$(".sport").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_sport.php",
dataType : 'html',
data: dataString,
cache: false,
success: function(html)
{
$(".tournament").html(html);
}
});
});
$(".tournament").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_round.php",
data: dataString,
cache: false,
success: function(html)
{
$(".round").html(html);
}
});
});
});
</script>
Here is an Example
What I want to do
I would like to send the value of the 3 selectboxes to 3 php variables without the form reloading.
My Problem
When the user clicks submit:
The form reloads (which I dont want)
The selectbox values does not get send to my php variables
my code to get the values after submit is clicked is as follows:
if(isset($_POST['submit'])){
$a = $_POST['sport'];
$b = $_POST['tournament'];
:
}
However my code is flawed as I mentioned above.
If any one can help me to explain how to send my form data to the 3 php variables without the form reloading it will be greatly appreciated
If you don't want to submit your form when you click the button, you need to set that input as button and not submit. You can, also, attach the submit event handler to the form and prevent it to submit:
$("form").on("submit", function(e){
e.preventDefault(); //This is one option
return false; //This is another option (and return true if you want to submit it).
});
So, being said this, you could probably do something like:
$("form").on("submit", function(e) {
var formData = $(this).serialize();
e.preventDefault();
$.ajax({
url: 'yoururl',
data: formData,
type: 'post', //Based on what you have in your backend side
success: function(data) {
//Whatever you want to do once the server returns a success response
}
});
});
In your backend:
if (isset($_POST["sport"])) {
//Do something with sport
}
if (isset($_POST["tournament"])) {
//Do something with torunament
}
echo "Successfull response!"; //You have to "write" something in your response and that is what the frontend is going to receive.
Hope this helps!
Try using the javascript function preventDefault().
See this SO question.
Use a <button>Submit</button> element instead of <input type="submit"/> since the submit automatically submits the form.
Edit: And you would have to use on.('click') instead of looking for submit event in your jQuery.
I have a web form, simple HTML / PHP that works by itself but when it is passed onto the template page via the below AJAX call -- the post data is missing on submission. This HAS got to be a param I'm missing below.
$(document).ready(function() {
$('#toggle3').click(function(){
var tog = $('.toggle');
$.ajax({
type: 'POST',
url: '/mysimplewebform.php',
success: function (fields){
tog.html(fields);
tog.slideToggle(1000);
}
});
});
});
The request is sent. And upon submission I receive email, everything but the selected post data via form is sent. Below is the PHP.
<?php
$backwheel = $_POST['backwheel'];
$frontwheel = $_POST['frontwheel'];
$form_message = "backwheel:".$backwheel." frontwheel:".$frontwheel." \nMessage: ". " You just recieved a new custom order via your Customizer!"."\nFullCustomURL: ".$_SERVER['HTTP_REFERER'];
mail("email#gmail.com", "Your Website Something", $form_message, "From: Capn Ron (New Order!)" );
if (isset($_POST['submit']))
{
echo "<script>
alert('Thanks for your Order!');
window.location.href='http://www.website.com';
</script>";
}
?>
You're not missing a param. From your code, #toggle3 appears to be button since the click event is bound to it. So, if you try to serialize it, it will certainly return nothing. You have to serialize the surrounding form which is easily achieved by using jQuery's closest() function; i.e.:
$(document).ready(function() {
$('#toggle3').click(function(){
var tog = $('.toggle');
$.ajax({
type: 'POST',
url: '/mysimplewebform.php',
data: $(this).closest('form').serialize(),
success: function (fields){
tog.html(fields);
tog.slideToggle(1000);
}
});
});
});
I trying to use contact form using J Query ,PHP AJAX but here in the below code the form information is gathered and send it to the server using for LOOP and Array of inouts of ofrm is created . i am new to this kind of coding please help me to extract this value in PHP so that i can use this element to add in to my database or send mail contain form inputs .
function signUpClick(){
var form = $("#form_main")[0];
var objData = {};
for(var i=0;i<form.length;i++){
var input = form[i];
objData[input.name] = "";
if(input.className == "writable")
objData[input.name] = input.value;
}
$("#loader").show();
$("#error_message").hide();
//send contact form using ajax
$.ajax({
url: "contact.php",
global: false,
type: "POST",
data:objData,
success: function(response){
$("#loader").hide();
if(response == "__ok__")
showSentMessage();
else
showErrorMessage(response);
},
error:function(){
$("#loader").hide();
showErrorMessage("Can't get the contact form");
}
});
}
On the PHP side you can manage the information as an array:
$objData = json_decode(file_get_contents('php://input'));
$objData will be the PHP array equivalent to the $objData on Javascript