how use data in PHP from ajax form - php

My javascript code:
function _(selector){
return document.querySelector(selector);
}
function submitForm(){
var data = {
name: _("#name").value,
email: _("#email").value,
message: _("#message").value
}
var output = JSON.stringify(data)
var ajax = new XMLHttpRequest();
ajax.open( "POST", "/PATH" );
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
console.log('success')
} else {
console.log('fail')
}
}
console.log(output)
ajax.send(output);
}
When im trying do this with static data,it's work :
<?php
$name = "mateusz";
$to = "kaawkamateusz#gmail.com";
$subject = "kucharz";
$message = "message";
mail($to, $subject, $message);
?>
but, on example :
$name = $_POST["name"];
doesn't work.
Im trying use JSON but again, idk how get value from AJAX form in PHP.
Im never use PHP before, need help :)
EDIT
print_r show :
Array
(
[{"name":"asd","email":"asd#gmail_com","message":"12"}] =>
)

ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
You say you are sending URL encoded form data …
var output = JSON.stringify(data)
… but your data is JSON encoded.
To URL form encode it use URLSearchParams.
var data = {
name: "Example Name",
email: "example#example.com",
message: "This is a message"
}
var output = new URLSearchParams(data);
console.log(output.toString());
Note limited browser support. Consider using a polyfill.
Alternatively, set the correct content type for JSON and rewrite the PHP since JSON is not supported for $_POST.

Related

How to verify receipt of my Ajax string query by the server?

I am using Javascript to send form data to a php via Ajax for validation and mailing. The query string which I named formString looks like this 'name= John Smith'. I have one input field only for testing purpose. The Ajax communication between my client page and the server is fine and I checked it successfully with the scripts shown below.
The problem is that I am not able to capture the formString query at the server-side. I am providing below the method I am used to capture the data unsuccessfully. The echo json_encode($name) is returning nothing to the html server.
I tried the query with several input fields values serialized and did not work. I tried to submit the query string a simple string including only the first name 'John', but it did not work either.
processForm()
var name = document.getElementById("fullName").value;
var formString = name;
var name = document.getElementById("fullName").value;
var formString = name;
var xhr = new XMLHttpRequest();
xhr.open('POST', formfile.php, true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function () {
if(xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
xhr.send(formString);
button.addEventListener("click", function(event) {
event.preventDefault();
processForm();
PHP snippet:
header('Content-Type: application/json');
function is_ajax_request(){
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
}
if(is_ajax_request()) {
$Ajax_results = array (
'Testing Text' => 'Hello World',
'Your Ajax submittal succeeded.
);
echo json_encode($Ajax_results);
} else {
$None_Ajax_results = array (
'errors' => 'None Ajax - short'
'Your Ajax submittal failed. Errors.'
);
echo "Form is Non Ajax Submitted";
echo json_encode($None_Ajax_error);
exit;
}
Define and set variables:
global $name;
$errors = null;
if (isset($_POST['name'])) { $name = $_POST['name']; }
else { $name = ''; }
echo '$name';
echo json_encode($name);
If I am reading your question correctly and assuming you have proper heartbeat between Ajax and the server as you state you do, taking a quick look at your code as provided you are not properly formatting your "formString". In order for your formString to properly show up in the $_POST['name'] it should be:
var formString = "name="+name
This is because the the post string being sent ("formString" in your case) should have the format:
field1=val1&field2=val2& ... fieldN=valN
where the name of each field is stated, followed by '=' and the value of the field. Multiple fields are separated by the'&' character. Which in PHP which will translate to
$_POST = {field1=>val1, field2=>val2, ... fieldN=>valnN}
on the server side. This is of course not literal code above but an example of the standard API. Take a closer look at how to format Post strings for HTML GET/POST

jQuery Ajax sending empty data

I'm doing a code that send a data to a php file and send it back again and print it as a response however when i send the data it is sent as an empty data i did not know what is the problem this is the code that i tried:
var resource = $('#resource').val().replace(/[\n\r](?!\w)/gi, "").split("\n");
function doRequest(index) {
// alert(resource[0]); The data here is ok and it is not empty whenever the data is sent the response is empty !
$.ajax({
url:'curl_check.php?email='+resource[0],
async:true,
success: function(data){
alert(data);
if (resource.length != 1) {
removeResourceLine();
doRequest(index+1);
}
}
});
}
doRequest(0);
since you're not sending the data using the data property of the ajax call object like so:
$.ajax({
...
data : { email : resource[0] }
...
});
you are sending it as part of the URL, so it should be picked up as a GET variable. in php, this looks like:
$email = isset($_GET['email']) ? $_GET['email'] : false;
that said, i'd suggest using the ajax data property and specifying the type property and setting it to GET or POST. you could also use $.ajaxSetup
Ok I am not sure what is wrong with what you are doing but I am going to give you code I use to send data to php and get a response. I am going to do it with json because it is awesome. I hope it helps:
var resource = $('#resource').val().replace(/[\n\r](?!\w)/gi,"").split("\n");
function doRequest(index) {
$.post("curl_check.php", {
email: resource[0]
}, function(data, result, xhr){
if(result == 'success') {
console.log(data.success);
} else {
console.log('post failed');
}
}, "json");
}
The php code:
$json = array();
$email = $_POST['email']; //Please escape any input you receive
//Do what you have to do
$json['success'] = 'YAY IT WORKED';
die(json_encode($json));

Pass jquery var to php via ajax?

I have a form that is using php to email myself with enquiries. I have some jquery that is filling in details into a div,
How can I pass the Jquery var to PHP via ajax? (I've read that that is the best way?)
Here's how's it's emailing me with php:
<? if(isset($_POST['submit'])) {
$to = "rob#domain.com";
$header = 'From: rob#domain.com';
$subject = "Quotation";
$enquiry_first_name = $_POST['enquiryfirstname'];
$enquiry_last_name = $_POST['enquirylastname'];
$enquiry_title = $_POST['enquirytitle'];
$enquiry_organisation = $_POST['enquiryorganisation'];
$enquiry_address = $_POST['enquiryaddress'];
$enquiry_country = $_POST['enquirycountry'];
$enquiry_email_address = $_POST['enquiryemailaddress'];
$enquiry_telephone = $_POST['enquirytelephone'];
$enquiry_additional_comments = $_POST['enquiryadditionalcomments'];
$body = "You have an quote request from the website:
Name: $enquiry_title $enquiry_first_name $enquiry_last_name
Type of organisation: $enquiry_organisation
Address: $enquiry_address, $enquiry_country
E-Mail: $enquiry_email_address
Tel: $enquiry_telephone
Comments: $enquiry_additional_comments
Kind regards";
mail($to, $subject, $body, $header);
echo "Thank you for your enquiry.";
} ?>
Here's the jquery that is outputting data into a div:
function makeSummary() {
var summary = [];
$steps.not(":last").each(function (i, step) {
$step = $(step);
summary.push('<p><b>' + $step.data('name') + '</b></p>');
var $ch = $step.find('input[type="checkbox"]:checked');
if (!$ch.length) {
summary.push('<p>No items selected</p>');
} else {
$ch.each(function (i, ch) {
summary.push('<p>' + $(ch).val() + '</p>');
});
}
});
return summary.join('');
}
1) Make a hidden input field.
2) Pass the jQuery var content to the hidden input field
$('.selector').change(function(){
//replace the value here.
});
3) Get it in php with $_POST['hiddenname']
E: Here is an example: http://jsfiddle.net/yLuNu/4/
It's using a dropdown to store a value in a hidden field. You can use any output and store it inside of the hidden field.
E2: Since I didn't really get what you want to pass to the hiddenfield: If you have a function and only want the output to save inside the hiddenfield:
What exactly do you want to pass to your script? I saw a checkbox so I thought you wanna use the change func. In case you only want to return the output of a function
$('input#hiddenfield').val($VAR)
while var is the output of your function. Just add this at the end of your existing func..
Just use AJAX and render a hidden input to your form, before submitting it.
Javascript:
$.ajax({
url:'/my/url',
type: 'POST',
dataType: 'json',
data: {
"some-var": "some-value"
},
context: $('form#my-form'), // now use $(this) inside event functions
complete: function(jqXHR, textStatus) {
console.log(jqXHR.responseText);
//this function gets called every time (not only on success or error)
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR.responseText);
//do something if call fails!
},
success: function(data, textStatus, jqXHR) {
if(data && data.value) {
if($(this).find("#my-field").length) {
$(this).find("#my-field").val(data.value);
}
else {
$hidden = $("<input>")
.attr("type", "hidden")
.attr("name", "my-field")
.val(data.value);
$(this).append($hidden);
}
//submit form
$(this).submit();
}
}
});
And you AJAX processing PHP File qould look like this.
PHP:
<?php
$data = array(
"value" => "default"
);
if($_POST["some-var"]=="some-value") {
$data = array(
"value" => "something"
);
}
echo json_encode($data);
?>
Just to give you an idea how to solve this!
You will need to do some validation and filtering by yourself!

Why is this ajax call to the correct php script not returning anything?

I have this AJAX:
function sendMail () {
$.post('php/sendMail.php', function(result){
alert(result);
})
}
$('#submitContact').click(function(){
sendMail();
})
and this PHP:
<?php
$trimmed = array_map('trim', $_POST);
$message = $trimmed['message'];
$email = $trimmed['email'];
$name = $trimmed['name'];
if (empty($message)) {
$message = FALSE;
}
if (empty($email)) {
$message = FALSE;
}
if (empty($name)) {
$message = FALSE;
}
if ($message && $email && $name){
$body = "From: $name.\n \n $message";
mail(/*some email*/, 'Website Contact Form Submission', $body, "From: $email");
echo ('success');
}
echo($message.' '.$email.' '.$name);
?>
All the html elements defined exist. When I run it all that returns is a blank alert box (meaning that the PHP script did not print out success). Any idea why it is not sending the mail?
You don't appear to be sending any data with your POST.
If you're trying to submit a form, try this:
$.post('php/sendMail.php',$('form').serialize(), function(result){
alert(result);
})
Edit: As Tomalak rightly points out in the comments, you'll need to specify which form you are serializing. I'd normally give the form an id and use that:- $('#myform').serialize()
You're not sending any data to that URL.
The reason you are seeing an empty alert box is because $email and $name is empty because you didn't pass any $_POST variable.
And $message = FALSE is blank when you echo it.
Try changing this line
echo($message.' '.$email.' '.$name);
To
var_dump($message.' '.$email.' '.$name);
And you'll see the value of $message.' '.$email.' '.$name.
Any idea why it is not sending the mail?
Put simply, you didn't ask it to.
The syntax for $.post is:
jQuery.post( url, [data,] [success(data, textStatus, jqXHR),] [dataType] )
The way jQuery works, you may skip the data argument and still provide the following ones, but in this case you're simply not passing any data for your PHP script to work with.
Assuming that #submitContact is a button in the form that you want to submit, you should serialise that form's contents and send that as the POST data:
function sendMail($form) {
$.post('php/sendMail.php', $form.serialize(), function(result) {
alert(result);
});
}
var $btn = $('#submitContact');
var $frm = $btn.parents('form');
$btn.click(function() {
sendMail($frm);
});
The documentation is your friend. Use it.
(Note: The $ at the start of some of my variables is deliberate; it's a personal choice that jQuery objects have names starting with $ in my code.)

JSON PHP Javascript - Simple Working Example

HI,
I am using the following code
request.js
var request;
function runAjax(JSONstring)
{
// function returns "AJAX" object, depending on web browser
// this is not native JS function!
request = new XMLHttpRequest();
request.open("GET", "request.php?json="+JSONstring, true);
request.onreadystatechange = sendData;
alert('called');
request.send(null);
}
function sendData()
{
// if request object received response
if(request.readyState == 4)
{
// parser.php response
var JSONtext = request.responseText;
// convert received string to JavaScript object
try
{
//var JSONobject = eval('(' + JSONtext + ')');
var JSONobject = JSON.parse(JSONtext);
}
catch(e)
{
var err="Error: "+e.description;
alert(err);
}
alert('1');
// notice how variables are used
try {
var msg = "Number of errors: "+JSONobject.errorsNum+ "\n- "+JSONobject.error[0]+ "\n- "+JSONobject.error[1];
alert(msg);
}
catch(ee)
{
var errr="Error: "+ee.description;
alert(errr);
}
}
}
The php function I have used here is request.php
<?php
// decode JSON string to PHP object
$decoded = json_decode($_GET['json']);
// do something with data here
echo "Decoded string - ". $decoded;
// create response object
$json = array();
$json['errorsNum'] = 2;
$json['error'] = array();
$json['error'][] = 'Wrong email!';
$json['error'][] = 'Wrong hobby!';
// encode array $json to JSON string
$encoded = json_encode($json);
// send response back to index.html
// and end script execution
die($encoded);
?>
I'm calling this JavaScript function from a HTML page request.html
<html>
<head>
<script src="request.js">
</script>
</head>
<body>
call<br>
</body>
</html>
The problem here is I was getting Syntax Error at the line:24
var JSONobject = JSON.parse(JSONtext);
if I was using
var JSONobject = eval('(' + JSONtext + ')');
I was getting " ) Expected Error "
After that I deleted browser cache. Restarted the browser, now the code seems working very fine.
You should verify JSON format, then look up there - http://ru.wikipedia.org/wiki/JSON. You can get an idea.

Categories