How to get Variable in php when passing through javascript? - javascript

I am passing my variable through an AJAX request in javascript. How to assign this the value of this variable to a new variable in the tabs.php file?
JS code
var build = {
m_count : (document.getElementById('count').value),
}
$.ajax({
data: build,
type: "POST",
url: "tabs.php",});
success: function(data) {
console.log(data);
}
});
Output of console is nothing.

You don't need to assign it. Your value will be accessible on tabs.php by the _POST array as it $_POST['m_count'].
I also strongly suggest you to test if the array variable m_count is set to avoid eventual php error when m_count is missing by doing the following:
if (isset($_POST['m_count']))
{
# If possible set the content type header to json app.
# header('Content-Type: application/json');
$message = "m_count value is equal to: " . $_POST['m_count'];
echo json_encode([ "message" => $message ]);
}
Also you you have an extra }); before the success function in your javascript.
var build = {
m_count : document.getElementById('count').value,
}
$.ajax({
data: build,
type: "POST",
url: "tabs.php",
success: function(data) {
console.log(data);
},
});

Related

Passing value to php from local storage using Ajax

I.m want to pass the values from js to php that is stored in local storage
js
let cartItems = localStorage.getItem("productsInCart");
var jsonString = JSON.stringify(cartItems);
$.ajax({
url:"read.php",
method: "post",
data: {data : jsonString},
success: function(res){
console.log(res);
}
})
php
<?php
print_r($_POST)
?>
on .php im getting just "array ()"
using #reyno's method with all the code in the same file called 'store_user_order.php'
<?php
if(isset($_POST["data"])) {
print_r($_POST["data"]);
} else {
?>
<button>SEND</button><br/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"> </script>
<script>
const cartItems = localStorage.getItem("productsInCart");
const jsonString = JSON.stringify(cartItems);
$("button").click(function() {
$.ajax({
url: 'store_user_order.php',
method: 'post',
data: {
data: jsonString
},
success: function(res) {
$('body').append(res);
},
error: function(err) {
$('body').append(err);
}
});
})
</script>
<?php } ?>
This should work if you have items in the localstorage
While testing, for checking values use method: "get", make sure that your test values aren't huge - you will see submitted values in the address bar.
For testing (php + MySQL) I always use this method:
success ? changes() : errors_list();`
I don't use js, so deal with syntax yourself, please.
on .php im getting just "array ()"
You received an empty $ _POST array - nothing was sent.
Because there was nothing to send, or there was an error sending

Jquery throws an 'Illegal invocation' error

I'm trying to create a forum and jquery throws an 'illegal invocation' error.
Here is my jquery code:
$('#formSumbit').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'data-get.php',
type: 'POST',
data: new FormData(this),
contentType: false,
dataType: 'json',
success: function(value) {
var serialize = $.parseJSON(value);
if (serialize.success == 'false') {
$('.alert').fadeIn().delay(3000).fadeOut();
$('.alert-msgText').html(serialize.datamsg);
}
}
});
});
And here is my PHP code:
<?php
$user = $_POST['user'];
$msg = $_POST['message'];
if(empty($user)&&empty($message)) {
$data = array(
'success' => 'false',
'datamsg' => 'Please fill the textboxes'
);
echo json_encode($data);
} else {
mysqli_query($con,"INSERT INTO forums(name,message) VALUES ('$user','$msg')");
$data = array(
'success' => 'true',
'datamsg' => 'Done!'
);
echo json_encode($data);
}
exit();
?>
When the textboxes are empty and i click the submit button, nothing seems to work and jquery throws an illegal invocation error. I don't understand what the problem is. Can you please help?
And thanks in advance!
1) You have a typo mismatch between your form and your JavaScript:
<form id="formSubmit" and $('#formSumbit') - it should be $('#formSubmit') to match the spellings.
2) Unless you are trying to upload files via this AJAX request, then you can simplify things by replacing data: new FormData(this), contentType: false, with just data: $(this).serialize(). This will get rid of the illegal invocation error.
3) Writing dataType: 'json' means that jQuery will automatically try to parse the data coming from the server as JSON, and convert it. Therefore, in your "success" function, value will already be parsed and converted to an object. In turn therefore, using $.parseJSON is not necessary. You can just access value.success directly, for instance.
Here's a fixed version:
$('#formSubmit').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'data-get.php',
type: 'POST',
data: $(this).serialize(),
dataType: 'json',
success: function(value) {
if (value.success == 'false') {
$('.alert').fadeIn().delay(3000).fadeOut();
$('.alert-msgText').html(value.datamsg);
}
}
});
});
Working demo: https://jsfiddle.net/khp5rs9m/2/ (In the demo I changed your URL for a fake one, just so it would get a response, but you can see where I have altered it and left your settings in the commented-out part).

Insert statement into custom WordPress database

I have a custom database that I want to insert items into from a WordPress front-end interface. When I submit the form, I can get the JSON values just fine, but for some reason, it doesn't seem to be inserting into the database. I do not get any error messages.
Here's what I'm doing (please note that I am testing the name variable, hence why it's not pulling from an input field):
I am using the auto_increment_id value from SHOW TABLE STATUS to create the commmittee_id value, and would prefer for that to be inserted as the primary key.
JavaScript
$(".addButton").click(function() {
var commitAddID = $(this).attr('id');
var name = "1name";
var date_created = $("#addCommCreated_input_"+commitAddID).val();
var status = $("#addCommStatus_input_"+commitAddID).val();
var disbanded = $("#addCommDisbanded_input_"+commitAddID).val();
var dataString = {
'action': 'addCommittee',
'committee_id': commitAddID,
'old_id': commitAddID,
'name': name,
'description': '',
'date_created': date_created,
'status': status,
'disbanded': disbanded
};
jQuery.ajax({
url: addCommittee.ajaxurl,
type: "POST",
data: dataString,
dataType: "json",
success: function (response) {
$("#name_"+commitAddID).html(name);
$("#created_"+commitAddID).html(date_created);
$("#status_"+commitAddID).html(status);
$("#disbanded_"+commitAddID).html(disbanded);
}
});
functions.php
// set up AJAX call for addCommittee
add_action('wp_ajax_addCommittee', 'addCommittee');
add_action('wp_ajax_nopriv_addCommittee', 'addCommittee');
function addCommittee() {
global $wpdb;
$committee_id = esc_sql($_POST['committee_id']);
$old_id = esc_sql($_POST['old_id']);
$name = esc_sql($_POST['name']);
$created = esc_sql($_POST['date_created']);
$status = esc_sql($_POST['status']);
$disbanded = esc_sql($_POST['disbanded']);
$desc= esc_sql($_POST['description']);
$wpdb->insert('wp_bubu_committees',
array(
'old_id' => '',
'name' => $name,
'description' => '',
'date_created' => $created,
'status' => $status,
'disbanded' => $disbanded
)
);
exit();
}
I have also localized the AJAX URL in functions.php. Any ideas?
Edit: Updated the code-- the action was set to the . I now am able to insert into the database, but it only allows me to insert one item. Attempting to insert additional items returns nothing, but the data does post to JSON.
Remove the data type json.
jQuery.ajax({
url: addCommittee.ajaxurl,
type: "POST",
data: dataString,
success: function (response) {
$("#name_"+commitAddID).html(name);
$("#created_"+commitAddID).html(date_created);
$("#status_"+commitAddID).html(status);
$("#disbanded_"+commitAddID).html(disbanded);
alert(response);
}
});

ajax - sending data as json to php server and receiving response

I'm trying to grasp more than I should at once.
Let's say I have 2 inputs and a button, and on button click I want to create a json containing the data from those inputs and send it to the server.
I think this should do it, but I might be wrong as I've seen a lot of different (poorly explained) methods of doing something similar.
var Item = function(First, Second) {
return {
FirstPart : First.val(),
SecondPart : Second.val(),
};
};
$(document).ready(function(){
$("#send_item").click(function() {
var form = $("#add_item");
if (form) {
item = Item($("#first"), $("#second"));
$.ajax ({
type: "POST",
url: "post.php",
data: { 'test' : item },
success: function(result) {
console.log(result);
}
});
}
});
});
In PHP I have
class ClientData
{
public $First;
public $Second;
public function __construct($F, $S)
{
$this->First = F;
$this->Second = S;
}
}
if (isset($_POST['test']))
{
// do stuff, get an object of type ClientData
}
The problem is that $_POST['test'] appears to be an array (if I pass it to json_decode I get an error that says it is an array and if I iterate it using foreach I get the values that I expect to see).
Is that ajax call correct? Is there something else I should do in the PHP bit?
You should specify a content type of json and use JSON.stringify() to format the data payload.
$.ajax ({
type: "POST",
url: "post.php",
data: JSON.stringify({ test: item }),
contentType: "application/json; charset=utf-8",
success: function(result) {
console.log(result);
}
});
When sending an AJAX request you need to send valid JSON. You can send an array, but you need form valid JSON before you send your data to the server. So in your JavaScript code form valid JSON and send that data to your endpoint.
In your case the test key holds a value containing a JavaScript object with two attributes. JSON is key value coding in string format, your PHP script does not not how to handle JavaScript (jQuery) objects.
https://jsfiddle.net/s1hkkws1/15/
This should help out.
For sending raw form data:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: item ,
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['FirstPart']) && isset($_POST['SecondPart']))
{
$fpart = $_POST['FirstPart'];
$spart = $_POST['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
For sending json string:
js part:
$.ajax ({
type: "POST",
url: "post.php",
data: {'test': JSON.stringify(item)},
success: function(result) {
console.log(result);
}
});
php part:
..
if (isset($_POST['test']))
{
$json_data = $_POST['test'];
$json_arr = json_decode($json_data, true);
$fpart = $json_arr['FirstPart'];
$spart = $json_arr['SecondPart'];
$obj = new ClientData($fpart, $spart);
}
...
Try send in ajax:
data: { 'test': JSON.stringify(item) },
instead:
data: { 'test' : item },

$_POST empty after ajax post called

So the purpose of me using this ajax post is to use some JS variables in a wordpress loop, so I can call a custom loop depending on what the variables are in the ajax post.
Below is the ajax call.
$('.collection-more').click(function() {
$.ajax({
type: 'post',
url: 'http://tmet.dev/wp-content/themes/muban-trust/single-collection.php',
data: { "test" : "hello" },
success: function( data ) {
console.log( data );
}
});
})
Currently I'm sending hard-coded data.
In my single-collection.php page:
<?php
print_r($_POST);
if(isset($POST['filters[Artist]']))
{
$filters_obj = $_POST['filters[Artist]'];
$filters_array = json_decode($filters_obj, TRUE);
for($i = 0; $i < sizeof($filters_array); $i++)
{
echo '<p>h'.$obj->name.'</p>';
}
}
?>
I'm using the print_r just to debug the problem, currently it returns:
Array()
The problem is that I cannot access the Json object called "test" within the single-collection.php
How do I access it?
Thanks in advance!
EDIT: Screenshot of firebug
From ajax to php :
this is the conventional way
var payload = {
smth1: "name",
smth2: "age"
};
and then when calling ajax
$.ajax({
url: "somephp.php",
type: 'POST',
data: payload,
dataType: 'json',
crossDomain: true
})
From phpPost to javascript:
right way getting the post parameters:
$fields = $_POST['fields'];
$usernameGiven = $fields['smth1'];
$passwordGiven = $fields['smth2'];
and when returning smthn to javascript
$result = array(
"something" => "something",
"something2" => $something2
);
echo json_encode($result);
Use $_POST['test'] to access the test parameter. Your print_r() shows that it is filled in correctly.
Your PHP code is accessing $_POST['filters[Artist]'] but there is no such parameter in the Javascript. If you pass:
data: { 'filters[Artist]': somevalue }
you can access it in PHP as $_POST['filters']['Artist'].

Categories

Resources