ajax $_POST array missing - javascript

I use the jquery $.post function to post to my local server. It posts correctly and I see the value inside the $_POST array. But when I upload the same code online on a website, the $_POST returns empty. Somehow the 'name' var is not even being sent over? What am I missing?
Heres the jquery/javascript side:
$("#box").keyup(function( event ) {
//Simple test to see if it gets to the
//file.
$.post( "test-file.php", { name:"John"}, function() {
alert( "success" );
})
.done(function(data) {
//Checking the respones from the file
alert( "second success: "+data );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
});
Heres what the test-file.php file does:
<?php
//Checking to see if I get to the
//file
echo "TEST:";
//Checking to see whats inside the post
var_dump($_POST);
?>

You need to write the url of your php page.
If it's www.my_url.com/test-file.php you need to write it like this:
$.post( "www.my_url.com/test-file.php", { name:"John"}, function() {
alert( "success" );
}) .....

It looks like you are posting JSON data to php. Make sure you double check the content-type header to be sure.
Generally speaking the $_POST variable is only populate when you post application/x-www-form-urlencoded. See if the below works for you:
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);

Related

admin-ajax returning 0 - not submitting form data to db

I'm trying to send form data to a table called attendants. I have the form, the AJAX and query created, but when trying to test (when submitting the form), I see a POST http://localhost/rsvp/wp-admin/admin-ajax.php 400 (Bad Request) error on console.
Unsure what's causing this as when I run a console.log(ajaxurl); the URL it returns is http://localhost/rsvp/wp-admin/admin-ajax.php which is correct.
Unsure what's happening here?
EDIT: I've recently discovered that http://localhost/rsvp/wp-admin/admin-ajax.php returns 0.
form.php (Folder Path: rsvp > template-parts > parts > form.php) :
<div class="form sectionPadding" id="rsvp-form">
<form id="rsvpForm" method="post">
<?php get_template_part('template-parts/snippets/form-step-1'); ?>
<?php get_template_part('template-parts/snippets/form-step-2'); ?>
</form>
</div>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
form.js (form.js compiles into theme.min.js. The path to theme.min.js is rsvp > assets > build > js > theme.min.js) :
jQuery('#rsvpForm').on('submit', function(e) {
e.preventDefault();
jQuery.ajax({
action: 'send_to_db',
dataType: "text",
type: "post",
data: $('form').serialize(),
url: ajaxurl,
success: function(data) {
console.log(data);
},
error: function() {
console.log("Error");
}
});
});
functions.php
add_action("wp_ajax_send_to_db", "send_to_db");
add_action("wp_ajax_nopriv_send_to_db", "send_to_db");
function send_to_db(){
if (isset($_POST['submit'])) {
global $wpdb;
$first_name = $_POST['fname'];
$table_name = $wpdb->prefix . "attendants";
$row_result = $wpdb->query("INSERT INTO $table_name (first_name) VALUES ('$first_name')" );
if ($row_result == 1){
echo "submitted";
} else{
echo "error";
}
die();
}
}
To summarize, my folder structure is:
rsvp
assets
build
js
theme.min.js
template-parts
parts
form
form.php
form.js
functions.php
EDIT: I've recently discovered that
http://localhost/rsvp/wp-admin/admin-ajax.php returns 0.
That's indeed the expected return value when the request (URL) doesn't contain the AJAX action name. Additionally, the HTTP response status would also be a 400 Bad Request which basically means "missing action name" or "there's no callback registered for that action".
And in your case, it seems that your AJAX script is not sending the AJAX action.
Because in your form.js script, the action parameter should be in the data — and as far as I know, jQuery.ajax() doesn't have a action property:
jQuery.ajax({
action: 'send_to_db', // this should be in 'data'
...
data: $('form').serialize(),
...
});
So you can do data: $('form').serialize() + '&action=send_to_db' like so:
jQuery.ajax({
...
data: $('form').serialize() + '&action=send_to_db',
...
});
That way, WordPress would recognize the AJAX action (via $_REQUEST['action']) and then run the proper AJAX handler / PHP callback, which is send_to_db() in your case.
And you can confirm if your AJAX callback is registered properly by visiting /wp-admin/admin-ajax.php?action=send_to_db — are you still seeing a 0?
Update
If the HTTP response status is no longer 400 (where it should now be 200), then it means your AJAX request is sending an action (send_to_db in your case) and that there's a PHP callback registered for that AJAX action (wp_ajax_send_to_db / wp_ajax_nopriv_send_to_db).
But because your callback is only doing something when the POST variable submit is set, then if your AJAX request data doesn't include that, the response would still be a 0.
If you want to avoid that, then you can do something like so:
function send_to_db() {
if ( isset( $_POST['submit'] ) ) {
// ... your code here.
//die();
} else {
echo 'Invalid request!';
}
wp_die(); // It's recommended to always call this to end an AJAX request,
// but die() is OK, too.
}
And with that, when you manually go to /wp-admin/admin-ajax.php?action=send_to_db (i.e. without sending any POST data), you'd see Invalid request! on the page. window.fetch( '/wp-admin/admin-ajax.php?action=send_to_db' ) would even receive that same response.
So now that the error 400 is gone, you just need to make sure your AJAX request is sending the proper data and that your PHP callback is working (or doing what it needs to do). And on Chrome, you can easily inspect the request and response data, headers, etc. by opening the developer tools and go to the Network → XHR tab and simply click on the relevant request.
Your SQL query is highly insecure and I strongly suggest you to use wpdb::prepare() to prepare the query for safe execution:
//$row_result = $wpdb->query("INSERT INTO $table_name (first_name) VALUES ('$first_name')" );
$query = $wpdb->prepare(
"INSERT INTO $table_name (first_name) VALUES (%s)",
sanitize_text_field( $first_name )
);
$row_result = $wpdb->query( $query );
Alternatively, for inserting a single database row/entry, you can just use wpdb::insert():
$row_result = $wpdb->insert( $table_name, array(
'first_name' => sanitize_text_field( $first_name ),
) );
And I have actually tested your original PHP callback, and it worked, so long as the request data are good. :)

How to get response from PHP server asynchronously

First of all I know that there are many questions already regarding this.After reading all answers and trying it out ..but none of them worked.So I'm uploading a question here.Please don't delete it.
So,I created a html file with a form and then sent the form data using ajax jQuery to PHP file as follows.
$("#form-id").submit(function e() {
e.preventDefault();
var sdata=("#text_feild").val();
$.ajax({
url:"filename.php",
type:"POST",
data:sdata
});
//display the message sent by PHP
/*Use the data sent by PHP to perform
different function*/
Now I want PHP to send a message to js or html or anything else.Also, I want PHP to send some Boolean data which I will be using to perform some function.
If you want to send multiple data then you can do this by using array and send them json encoded and you will receive data in "success" callback function of ajax call
consider below example
ajax call
$("#form-id").submit(function e() {
e.preventDefault();
var sdata=("#text_feild").val();
$.ajax({
url:"filename.php",
type:"POST",
data:sdata,
async: true,
dataType: 'json',
success: function(data) {
console.log(data); // check result in console
$('#result').html((data.content) ? (data.content) : '???');
$('#result').prop('title', data.title);
$('#jsonstring').html('Json object: '+JSON.stringify(data));
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
<?php
$result = array(
'title' => 'Title',
'status' => 0,
);
echo json_encode($result);
?>
You can use the powerful pure javascript browser native fetch api.
To retrieve text/html.
fetch("https://api.github.com/")
.then(function(response) { return response.text() })
.then(function(text) {
console.log(text)
})
To retrieve json.
fetch("https://www.reddit.com/.json").then(v => v.json()).then((function(v){
syn = JSON.stringify(v)
main.innerHTML += syn
})
)
<div id="main">
Server side the base of a json api would be:
if ($_GET["myapi"] != ""){
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
echo json_encode(["Hello","World"]);
exit;
}
Calling: mysite/?myapi=whatever
Output: ["Hello","World"], with a json header, and CORS enabled.
Learn more about javascript promise(s)

How can get data from html form and javascript array using PHP and AJAX

I'm sending a HTML form and javascript array using AJAX post method. But I can't get my data in the PHP file.
$.post("addOrder.php", {
"form": $("#placeOrderForm").serialize(),
"array": array
}, function(responce) {});
Please read the docs clearly.
The update code:
$.post("addOrder.php",
$("#placeOrderForm").serialize(),
function(response) {
}
);
And in addOrder.php, print the posted array using.
echo '<pre>';print_r($_POST);echo '</pre>';
If you are using firebug, you will get the posted variables' array in response tab.
// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$var = isset($_POST['var']) ? $_POST['var'] : null;
Can you try something like below:
var request = $.ajax({
url: "addOrder.php",
type: "POST",
data: {<data1> : <val1>},
dataType: "html"
});
request.done(function(msg) {
$("#log").html( msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
Looks like you passing argument is having issue.
In addForm.php try this:
var_dump($_POST)
This will enable you to inspect the form data posted.
Try something like this in your php file:
$params = array();
echo parse_str($_POST, $params);
Thanks everyone. I found my answer. I used "serializeArray" for sending form.
html
<form id="placeOrderForm">
<input name="po">
<input name="desc">
</form>
javascript
var array = [1,2];
$.post("addOrder.php",{
"form":$("#placeOrderForm").serializeArray(),
"array":array
}, function (responce) {});
php
$form_input_data_1 = $_POST['form'][0]['value']; // get po's data
$form_input_data_2 = $_POST['form'][1]['value']; // get desc's data
$array_index_1_data = $_POST['array'][0]; // get 1
$array_index_2_data = $_POST['array'][1]; // get 2

use getJSON with variable

I apologize beforehand if the question is not clear, but i'll try.
I currently have this code that pull the status of all the devices from my home automation controller.
function pull_light_status (lights_array) {
$.getJSON( "resources/php/getjson.php", function( json ) {
var vera_obj = json;
$.each(lights_array,function(myindex, myvalue){
var id_del_object = myvalue;
var id_status = vera_obj.devices[id_del_object].states[0].value;
})
})
}
Due to the structure of the object i get its getting really hard for me to work with that object so I'm thinking in using another route.
I can get the status of an specific device by using this php called change_state.php
<?php
$url = 'http://ip:port/data_request?id=variableget&DeviceNum' . $_POST['device_id'] . "&serviceId=urn:upnp-org:serviceId:SwitchPower1&Variable=Status";
$jsondata_send = file_get_contents($url);
//echo $jsondata_send;
?>
My question is:
Is it possible to replace the JS to something that will allow me to request the json response of a device variable I specify?
Something like this?
function pull_light_status (lights_array) {
$.each(lights_array,function(myindex, myvalue){
$.getJSON( "resources/php/change_state.php",{ device_id: + myvalue})
.done(function(json) {
var vera_obj = json;
console.log (vera_obj);
})
})
}
What I would expect in return is a 0 or 1, that way I can play with the status of the devices.
Try using $.post since you are expecting a POST payload on the php side.
function pull_light_status (lights_array) {
$.each(lights_array,function(myindex, myvalue){
$.post( "resources/php/change_state.php", { device_id: myvalue })
.done(function( data ) {
var vera_obj = json;
console.log (vera_obj);
});
})
}
While on the php side you need to make sure that you are sending back a json encoded string.
So a var_dump($jsondata_send); would be in order, if it's all right, print it out along with the headers.
<?php
$url = 'http://ip:port/data_request?id=variableget&DeviceNum' . $_POST['device_id'] . "&serviceId=urn:upnp-org:serviceId:SwitchPower1&Variable=Status";
$jsondata_send = file_get_contents($url);
header('Content-Type: application/json');
print $jsondata_send;
?>
If you want to use getJSON instead, in the php file, change $_POST['device_id'] into $_GET['device_id']

Save form data using AJAX to PHP

How can I save the form data in a file or a local db (maybe using AJAX) which send the data via form action to an external db?
The source code for my form is here: http://jsbin.com/ojUjEKa/1/edit
What changes (if any) should I make to the code?
EDIT:
Right. So I'm able to store the data into localStorage using AJAX and want to send the data stored across to a file called backend.php. Here's my html file: http://jsbin.com/iSorEYu/1/edit
and here's my backend.php file: http://jsbin.com/OGIbEDuX/1/edit
The AJAX is working absolutely fine to store the fields in localStorage but things go wrong when it tries to send the data across to backend.php. I receive the following errors:
[24-Jan-2014 08:40:34 America/Chicago] PHP Notice: Undefined index: data in /home4/private/public_html/marketer/backend.php on line 7
[24-Jan-2014 08:40:34 America/Chicago] PHP Warning: Invalid argument supplied for foreach() in /home4/private/public_html/marketer/backend.php on line 10
[24-Jan-2014 08:40:58 America/Chicago] PHP Notice: Undefined index: data in /home4/private/public_html/marketer/backend.php on line 7
[24-Jan-2014 08:40:58 America/Chicago] PHP Warning: Invalid argument supplied for foreach() in /home4/private/public_html/marketer/backend.php on line 10
What's the issue here?
LocalStorage would be your best bet. I would suggest using storejs as their API is straight forward, easy to use, and x-browser.
You could then trigger the form values to be stored on the "blur" event of each field.
$('input').on('blur', function (e) {
var el = e.target;
store.set(el.attr('name'), el.val());
});
When you are ready to submit to the server, you could use something like the following:
$('#formID').on('submit', function (e) {
e.preventDefault();
$.post('/my/save/route', store.getAll(), function () { ... });
});
You of course could do all of this without storejs and use vanilla JS to interact with the native LocalStorage API.
PHP:
<h1>Below is the data retrieved from SERVER</h1>
<?php
date_default_timezone_set('America/Chicago'); // CDT
echo '<h2>Server Timezone : ' . date_default_timezone_get() . '</h2>';
$current_date = date('d/m/Y == H:i:s ');
print "<h2>Server Time : " . $current_date . "</h2>";
$dataObject = $_POST; //Fetching all posts
echo "<pre>"; //making the dump look nice in html.
var_dump($dataObject);
echo "</pre>";
//Writes it as json to the file, you can transform it any way you want
$json = json_encode($dataObject);
file_put_contents('your_data.txt', $json);
?>
JS:
<script type="text/javascript">
$(document).ready(function(){
localStorage.clear();
$("form").on("submit", function() {
if(window.localStorage!==undefined) {
var fields = $(this).serialize();
localStorage.setItem("eloqua-fields", JSON.stringify( fields ));
alert("Stored Succesfully");
$(this).find("input[type=text]").val("");
alert("Now Passing stored data to Server through AJAX jQuery");
$.ajax({
type: "POST",
url: "backend.php",
data: fields,
success: function(data) {
$('#output').html(data);
}
});
} else {
alert("Storage Failed. Try refreshing");
}
});
});
</script>

Categories

Resources