I have an ajax request where I register a user (wordpress). I want the user id to be sent back to the success response, but it just shows undefined, or blank in the case below:
$(document).on('submit', '.register_user_form', function(event){
event.preventDefault();
$.ajax({
type: 'POST',
url: '/wp-admin/admin-ajax.php',
dataType: 'html',
data: {
action: 'register_user_form',
currentUserName: $("#First_Name").val() + " " + $("#Last_Name").val(),
currentUserEmail: $("#email").val(),
currentUserPassword: $("#password").val(),
},
success: function(res) {
console.log(res);
}
});
});
PHP function (wordpress):
function register_user_form() {
$user_login = $_POST['currentUserName'];
$user_email = $_POST['currentUserEmail'];
$user_pass = $_POST['currentUserPassword'];
$userdata = compact( 'user_login', 'user_email', 'user_pass' );
$user_id = wp_insert_user($userdata);
echo 'this doesnt get returned';
wp_die();
}
add_action('wp_ajax_register_user_form', 'register_user_form');
add_action('wp_ajax_nopriv_register_user_form', 'register_user_form');
I have tried echo json_encode(''); but that doesn't work either. fyi - the user does get registered
Related
I have created this PHP script to update the status of users. I am having some difficulty while running the below code. The code of the page is given below: -
$query = "DELETE FROM users WHERE id='$id' ";
$query_run = mysqli_query($conn, $query);
if($query_run)
{
$_SESSION['status'] = "Successfully Deleted";
header('Location: index.php');
}
else
{
$_SESSION['status'] = "Something Went Wrong.!";
header('Location: index.php');
}
The query here fails to run. The below ajax code sends the data to this page using a POST request
$.ajax({
type: "POST",
url: "code.php",
data: {
'checking_edit_btn': true,
'student_id': stud_id,
},
success: function (response) {
$.each(response, function (key, value) {
$('#edit_id').val(value['id']);
});
$('#editStudentModal').modal('show');
};
});
update It's working now, here is the final code:
$.ajax({
type: "POST",
url: "code.php",
data: {
'delete_student': true,
'student_id': stud_id,
},
success: function (response) {
$.each(response, function (key, value) {
$('#edit_id').val(value['id']);
});
$('#editStudentModal').modal('show');
};
});
where you sending 'update_student'/'delete_student'?
try to add to data
update_student: true
or
delete_student: true
depends on button
I have been trying to work this out for hours now and cannot find any answer that helps me.
This is the code in my javascript file
function sendMovement(cel) {
var name = "test";
$.ajax({
type: 'POST',
url: '../game.php',
data: { 'Name': name },
success: function(response) {
console.log("sent");
}
});
}
This is the code from my PHP file (it is outside the js file)
if($_SERVER["REQUEST_METHOD"] == "POST") {
$data = $_POST['Name'];
console_log($data);
}
When debugging I can see that AJAX is sending a POST and it does print in the console "SENT" but it does not print $data
update: the function console_log() exists in my PHP file and it works
Try getting response in JSON format, for that your js should have dataType:'JSON' as shown below
JS Code:-
function sendMovement(cel) {
var name = "test";
$.ajax({
type: 'POST',
dataType:'JSON', //added this it to expect data response in JSON format
url: '../game.php',
data: { 'Name': name },
success: function(response) {
//logging the name from response
console.log(response.Name);
}
});
}
and in the current server side code you are not echoing or returning anything, so nothing would display in ajax response anyways.
changes in php server code:-
if($_SERVER["REQUEST_METHOD"] == "POST") {
$response = array();
$response['Name'] = $_POST['Name'];
//sending the response in JSON format
echo json_encode($response);
}
I fixed it by doing the following:
To my game.php I added the following HTML code (for debugging purposes)
<p style = "color: white;" id="response"></p>
Also added in my game.php the following
if($_SERVER["REQUEST_METHOD"] == "POST") {
$gameID = $_POST['gameID'];
$coord = $_POST['coord'];
$player = $_POST['player'];
echo "gameID: " . $gameID . "\nCoord: " . $coord . "\nPlayer: " . $player;
}
AND in my custom.js I updated
function sendMovement(cel) {
var handle = document.getElementById('response');
var info = [gameID, cel.id, current_player];
$.ajax({
type: 'POST',
url: '../game.php',
data: {
gameID: info[0],
coord: info[1],
player: info[2]
},
success: function(data) {
handle.innerHTML = data;
},
error: function (jqXHR) {
handle.innerText = 'Error: ' + jqXHR.status;
}
});
}
This my code for send realtime message.
After send message, it is not display unless i refresh the page.
I want this chat box message to show the new message entered.
This is to show the user List In the left side of the page:
$(".user-w").click(function() {
var user_id = $(this).attr("id");
// alert(user_id);
$.ajax({
type: "POST",
url: "<?php echo base_url('Message/getMessageByLists/')?>",
data: {
'user_id': user_id
},
datatype: 'html',
success: function(data) {
$("#loadMessages").html(data);
}
}); });
This is Send function:
$("#sendMessage").click(function(e)
{e.preventDefault();// alert("test");
var msg = $("#message_text").val();
var touser = $("#touser").val();
//var reservation_id = $("#reservation_id").val();
if (!msg || msg.length == 0) {
alert("enter a message");
} else {
$.ajax({
type: "POST",
url: "<?php echo base_url('Message/addMessage')?>",
// data:{'msg' : msg, 'touser' : touser, 'reservation_id' : reservation_id},
data: {
'msg': msg,
'touser': touser
},
datatype: 'text',
// Page.Server.ScriptTimeout = 300;
success: function(data) {
if (data == 1) {
//$("#loadMessages").load();
$("#message_text").val("");
} else {
alert("noo eroor chat message");
}
},
});
//return false;
} }); // End Send Function
if I am not wrong then, their might be an element with class as "user-w", also that element have "id" attribute too. So you can just execute following line, after sending the message to user.
$(".user-w[id='"+ touser +"']").trigger("click");
above line needs to placed in "success" method, like as below:
if (data == 1) {
//$("#loadMessages").load();
$("#message_text").val("");
$(".user-w[id='"+ touser +"']").trigger("click");
} else {
alert("noo eroor chat message");
}
I am trying to write a script that will add the video currently being viewed to a database of favourites. However every time it runs, an error is returned, and nothing is stored in the database.
Here is the JQuery
$(document).ready(function() {
$("#addfav").click(function() {
var form_data = {heading: $("#vidheading").text(), embed : $("#vidembed").text()};
jQuery.ajax({
type:"POST",
url:"localhost/stumble/site/add_to_fav.php",
dataType: "json",
data: form_data,
success: function (data){
console.log(data.status);
alert("This Video Has Been Added To Your Favourites")
},
error: function (data){
console.log(data.status);
alert("You Must Be Logged In to Do That")
}
});
})
})
The add_to_fav.php is this...
public function add_to_fav(){
$this->load->model('model_users');
$this->model_users->add_favs();
}
And the add_favs function is below
public function add_favs(){
if($this->session->userdata('username')){
$data = array(
'username' => $this->session->userdata('username'),
'title' => $this->input->post('heading'),
'embed' => $this->input->post('embed')
);
$query = $this->db->insert('fav_videos',$data);
if($query){
$response_array['status'] = 'success';
echo json_encode($response_array);
}}else {
$response_array['status'] = 'error';
echo json_encode($response_array);
}
}
Thank you for the input, this has me stuck but I am aware it may be something relatively simple, my hunch is that it is something to do with returning success or error.
Try
$(document).ready(function() {
$("#addfav").click(function() {
var form_data = {heading: $("#vidheading").text(), embed : $("#vidembed").text()};
jQuery.ajax({
type:"POST",
url:"http://localhost/stumble/Site/add_to_fav",
dataType: "json",
data: form_data,
success: function (data){
console.log(data.status);
alert("This Video Has Been Added To Your Favourites")
},
error: function (data){
console.log(data.status);
alert("You Must Be Logged In to Do That")
}
});
})
})
Also to use base_url in javascript. In your template view :-
<script>
window.base_url = "<?php echo base_url(); ?>";
</script>
Now you can use base_url in all your ajax scripts.
I looked at the Network tab in chrome and it's sending the right data (action, username, password) but it's not returning the message into $('#return_login'). What is wrong with my code?
jQuery:
$(function() {
$('.login').hide();
$('#login').click(function() {
event.preventDefault();
$('.login').fadeIn(500);
$('#login_submit').click(function() {
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
url: './controller',
type: 'POST',
data: 'action=login&username=' + username + "&password=" + password,
success: function(return_login) {
$('#return_login').html(return_login);
}
});
});
});
});
PHP (Methods class isn't used at all, ignore it):
<?php
require_once('Methods.php');
$Methods = new Methods;
$action = #$_POST['action'];
switch($action) {
case 'login':
echo 'lol';
break;
}
?>
$.ajax({
url: '/controller',
type: 'POST',
data:{action:'login',username:username,password:password},
success: function(return_login) {
$('#return_login').html(return_login);
}
});
//php
$action = #$_POST['action'];
And in the php make sure to put an exit after the switch statment
Try sending data in json format:
data:{action:'login',username:username,password:password}