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
Related
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.
I have a form on my website and if it fails validation (It is set to only accept some email TLDs) I want to save the email address into a .txt file.
To do this I want to include an AJAX call to pass the email address as a variable and call a PHP function, which writes the email address to a file.
It doesn't work and I can't understand why. I've hooked my function to the built in Wordpress AJAX handler. Any thoughts much appreciated.
---- EDIT: This now works -----
PHP
function text_ajax_process_request() {
// first check if data is being sent and that it is the data we want
if ( isset( $_POST["post_var"] ) ) {
// now set our response var equal to that of the POST var (this will need to be sanitized based on what you're doing with with it)
$response = $_POST["post_var"];
file_put_contents('/home/benefacto/public_html/dev3/' . "login-error.txt", $response . ', ', FILE_APPEND | LOCK_EX);
echo $response;
die();
}
}
add_action('wp_ajax_nopriv_test_response', 'text_ajax_process_request');
add_action('wp_ajax_test_response', 'text_ajax_process_request');
This is the jQuery Function
function newbie(email) {
var data = {
action: 'test_response',
post_var: email
};
// This is a shortened version of: https://api.jquery.com/jquery.post/
jQuery.post("<?php echo admin_url('admin-ajax.php'); ?>", data,
function(response) {
alert(response);
});
return false;
}
And this is the jQuery used to call it
jQuery(document).ready(function(){
var email = 'enter email here';
newbie(email);
});
I'm trying to build an array of data that will then be ajax using post to php - below is my code:
$('#mainBodySaveSubmitButtonProfilePhotoIMG').click(function() {
var profilePhotoArray = [];
$('.mainUnapprovedProfilePhotoWrapperDIV').each(function() {
var action = '';
alert( this.id );
if($('.mainUnapprovedProfilePhotoAttractiveIMG', this).is(':visible')) {
alert('attractive...');
action = 'attractive';
}
else if($('.mainUnapprovedProfilePhotoDeleteIMG', this).is(':visible')) {
alert('delete...');
action = 'delete';
}else{
alert('normal...');
action = 'normal';
}
profilePhotoArray[this.id+'_'+this.id] = action;
});
alert(profilePhotoArray.length);
for (i=0;i<profilePhotoArray.length;i++) {
console.log("Key is "+i+" and Value is "+array[i]);
}
$.post('scripts/ajax/ajax_approval_functions.php', {
'approvalProfilePhotos': '1',
'approvalProfilePhotosData': profilePhotoArray},
function(data) {
alert(data);
});
});
The if, else if, else section works fine as I can see the alerts.
When I try to alert the array length 'profilePhotoArray' it says 0 so I'm not populating the array correctly. Do I need to use .push()? I thought this format was ok?
Also do I need to do anything to the array before sending to php via ajax?
thankyou
** edit - I'm adding "profilePhotoArray[this.id+'_'+this.id] = action;" this.id twice just to prove this words as I will pass a second variable like this... am I better to use JSON for this?
Javascript arrays use numerical index, therefore your storage is failing. Use a javascript Object to store string based keys.
var lang=new Object();
lang["foo"]="Foo";
lang["bar"]="Bar";
How can I go about accomplishing the following behavior.
upon getting an input from a knockout.js form send the variable to a page to be handled. The page uses PHP
The PHP page receives the input from the knockout.js form and runs some calculations and then returns the result
The variable is then received back on the original page and is then displayed via knockout
For example, say I have the following
//knockout_form.js
self.addItem = function() {
var itemNum = self.newItem; //variable received from knockout form
var returnedVariable = ???? **send itemNum to processing.php which will then return it**
self.itemNumbers.push(new ItemEntry(retunredVariable, "$20.00")); //
}
I know that jQuery/Ajax can be used to post to processing.php, but how do I return the calculated data from processing.php back to the javascript page?
edit below. The data appears to be sent to processing.php (shows up in the network tab) but the alert isn't showing.
// Operations
self.addItem = function() {
var itemNum = self.newItem;
$.getJSON("processing.php?itemNum=" + itemNum),function(data) {
alert(data); //this does not appear
self.itemNumbers.push(new ItemEntry(data.result, "$20.00"));
}
}
Here's the php
//$result = $_GET['itemNum'];
$result = "test"; //set it just to be sure it's working
echo json_encode(array("result" => $result));
Knockout doesn't have any special way of doing ajax calls itself, typically you would use jQuery. See http://knockoutjs.com/documentation/json-data.html.
So something like:
self.addItem = function() {
var itemNum = self.newItem;
$.getJSON("processing.php?itemNum=" + itemNum,function(data) {
self.itemNumbers.push(new ItemEntry(data.result, "$20.00"));
});
}
This assume that your PHP script is outputting valid JSON. Something like:
<?php
$result = doCalculations($_GET['itemNum']);
echo json_encode(array("result" => $result));
?>
This is untested, but you get the idea.
When process.php responds to an Ajax request made by form.html it replies with "false" or "true [hash value]" (where hash value is the output of a hashing function). In form.html I want to call a different function for the two possible responses but how do I parse the response? For example must I call
var responses = xmlhttp.responseText.split(" ")
Assuming the hashing function never outputs "false" I could use
if(xmlhttp.responseText != "false")
Both these ways seem kind of hacky and inefficent, is there a better way?
You could do the following in your PHP Code:
$returnValue['ValueA'] = "a value";
$returnValue['ValueB'] = "another value";
echo json_encode($returnValue);
in your JavaScript Code (JQuery is used here):
$.ajax({
type: "GET",
dataType: "json",
url: "./myphpfile.php",
data: "parameter=parametervalue",
success: function(data){
printresult(data);
}
});
function printresult(data)
{
alert(data['ValueA']);
alert(data['ValueB']);
}
Is this helping you?
I've had a similar situation, here is my solution using basic Javascript.
First on the PHP side, I can have one of four outcomes (PASS or FAIL on an INSert or UPDate), so my response to AJAX carries those outcomes upfront:
[...]
$echoStr = 'PASS/INS/Adding ID Succeeded.'; // INSert successful
[...]
$echoStr = 'FAIL/INS/Adding ID Failed'; // INSert failed
[...]
$echoStr = 'PASS/UPD/Updating D Succeeded.'; // UPDate successful
[...]
$echoStr = 'FAIL/UPD/Updating ID Failed'; // UPDate failed
[...]
echo $echoStr; return; // Reply to AJAX request.
On the Javascript side (ajax1 is my AJAX obj), I split the response string into three components and process accordingly:
[...]
ajax1.onreadystatechange = function() {
if (ajax1.readyState == 4 && ajax1.status == 200) {
response = ajax1.responseText; // PASS or FAIL, INS or UPD, free form text alert
passFail = response.substr(0,4); // PASS or FAIL
insUPD = response.substr(5,3); // INS or UPD
usrMsg = response.substr(9); // Free form alert text
if (passFail == 'PASS' && insUPD == 'INS') {
// do what you need to do here
}
alert(usrMsg);
} // if (ajax1.readyState == 4 && ajax1.status == 200) {
} // ajax1.onreadystatechange = function() {
[...]