How to extract information from array of Input element in PHP? - php

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

Related

How I can send data form?

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.

Bringing back several variables into ajax form POST success as jQuery variables

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

Using jQuery to fetch variable from my database

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);

How to send external form POST data through AJAX

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);
}
});
});
});

Send javascript array to php using json

This question might be repetitive but i got confused reading all posts relating to this.(sincere apologies!) Basically, I want to send a javascript array to a php file and inturn write the array to a text file . I learnt the best way to go about it is using JSON and AJAX. My code is displays "success" for the ajax part, and also creates a file (php code),but an empty text file.
$('#tabletomodify').on('change','.street',
function (event)
{
event.preventDefault();
var row=( $(this).closest('tr').prop('rowIndex') );
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
var ideSelected= this.id;
var values = [valueSelected];
for ($i=3;$i<row;$i++)
{
var dv="selectstate"+$i;
var dv1=document.getElementById(dv).value;
var sl="selectstreet"+$i;
var sl1=document.getElementById(sl).value;
var po="selectbuilding"+$i;
var po1=document.getElementById(po).value;
var concat=dv1+sl1+po1;
values.push(concat);
}
JSON = JSON.stringify(values);
$.ajax({
url: "get_buildings.php",
type: 'POST',
data: JSON ,
success: function(){
alert("Success!")
}
});
PHP Code:-
<?php
$json = $_POST['JSON'];
$p = json_decode(JSON);
$file = fopen('test.txt','w+');
fwrite($file, $p);
fclose($file);
echo 'success?';
?>
Two flaws:
a) You're not sending your data correctly - it's lacking a field name:
data: {data: JSON}
^^^^---this will be the key in PHP's $_POSt
b) You're using invalid constants in PHP and not even decoding what MIGHT have been the passed in data. You should have:
$p = json_decode($_POST['data']);
^^^^--matching what you have in the `data` field in Javascript.

Categories