I'm going to ask a question that has been mentioned very often but I can't understand what is missing in my code to make it work. I have two PHP files, one that acts as a viewer and the other one that processes, performs processes and a javascript file where I put my ajax requests. My goal is simple to pass a variable between my Js and my PHP.
My global.js file
window.onload = function(){
for($i = 0; $i <= 0; $i++){
console.log("after for");
console.log($i);
$input = document.getElementsByClassName('from_1')[$i].textContent;
$sub = document.getElementsByClassName('subject_1')[$i].textContent;
$recei = document.getElementsByClassName('received_1')[$i].textContent;
$preview = document.getElementsByClassName('bodypreview_1')[$i].textContent;
$body_1 = document.getElementsByClassName('body_1')[$i].textContent;
console.log("*********************");
console.log($input);
console.log($sub);
console.log($recei);
console.log($preview);
console.log($body_1);
console.log("*********************");
}};
I recover data with getElementsById and store it in variables. Then in the same file I make my Ajax call
function btn_urgent(html){
console.log("*************************");
console.log("btn_urgent");
console.log($input);
console.log("*************************");
$.ajax({url: '../../wp-content/plugins/game_plugin/process_general.php',
type: 'POST',
data: {info: 'insert_to_db', $input: $input},
success: function(output) {
console.log("*************************");
console.log("ssrtsgsgsg");
alert(output);
console.log("*************************");
return($input);
}
In my game. php file I have an onclick that calls my function "btn_urgent".
<button type="submit" class="btn btn-primary col-2" onclick="btn_urgent()" >urgent</button>
Once my Ajax function is called it calls another function insert_to_db in the process_general file.
function insert_to_db($input){
global $wpdb;
echo json_encode;
$wpdb->insert(
'test_insert', //table name
array(
'id' => 550,
'from_mail' => $input,
), //columns
array(
'%d',
'%s',
)
);
}
As you can see I'm trying to make a $input insert when I click my onclick. but it doesn't work. On the other hand my function insert_to_db is well called by my Ajax request but it does not pass $input. I think I'm forgetting something in the success story, but I don't know what. If someone has a few tips solution to offer me I am a buyer. I don't know how important this is, but I'm getting into wordpress. I remain available if necessary, thank you all and have a good day.
</div>
On your ajax data, it have invalid field name:
data: {info: 'insert_to_db', $input: $input},
Change to this:
data: {info: 'insert_to_db', input: $input},
on your php, you need grab the data like this:
$info = $_POST['info'];
$input= $_POST['input'];
// Then call the function
insert_to_db($input)