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}
Related
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
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 question already has answers here:
Get response from PHP file using AJAX
(5 answers)
Closed 5 years ago.
I'm new to programming and i'm not good at all with Ajax.
I want to get a value back from a php script in Ajax.
I send a javascript variable to a php script like that :
$('#deleteSelectedButton').on('click', function () {
if (confirm('Do you want to suppress the messages ?')) {
$.ajax({
type: 'POST',
url: 'suppression-message',
data: {
'checkboxIdArray': checkboxIdArray.toString(),
}
});
return false;
}
});
This is sent to the following php script which is deleting messages according to the id contained in the checkboxIdArray:
if (isset($_POST['checkboxIdArray'])) {
$checkboxIdArray = $_POST['checkboxIdArray'];
$str = json_encode($checkboxIdArray);
$tab = explode(",", $str);
$deleteSuccess = true;
foreach($tab as $id)
{
$id = filter_var($id, FILTER_SANITIZE_NUMBER_INT);
if (!$messageModelDb->delete($id)) {
$deleteSuccess = false;
die();
}
}
if ($deleteSuccess === true) {
$message = 'Success';;
} else {
$message= "Error";
}
}
I want to get the $message variable back to my javascript in order to display a message according to the result of the script.
I would really appreciate some help ...
Thank you.
You have to use success function and actually include the message in the response
$.ajax({
type: 'POST',
url: 'suppression-message',
data: {
'checkboxIdArray': checkboxIdArray.toString(),
},
success : function(response){
// your code or logic
alert(response);
}
});
PHP
if ($deleteSuccess === true) {
$message = 'Success';
} else {
$message= "Error";
}
echo $message;
$('#deleteSelectedButton').on('click', function () {
if (confirm('Do you want to suppress the messages ?')) {
$.ajax({
type: 'POST',
url: 'suppression-message',
data: {
'checkboxIdArray': checkboxIdArray.toString(),
},
success: function(response){
alert(response);
}
});
return false;
}
});
There is nothing special about an HTTP request made with JavaScript.
You output data in the response to it in from PHP in the same way as any other HTTP response.
echo $message;
In JavaScript, you process it as described in the documentation for jQuery.ajax.
Write a function that accepts a the response content as the first argument.
Then call done on the jqXHR object that .ajax returns and pass it that function.
function handleResponse(data) {
alert(data);
}
var jqXHR = $.ajax({
type: 'POST',
url: 'suppression-message',
data: {
'checkboxIdArray': checkboxIdArray.toString(),
}
});
jqXHR.done(handleResponse);
Try out the code to get the value in ajax
<script>
$('#deleteSelectedButton').on('click', function () {
if (confirm('Do you want to suppress the messages ?')) {
$.ajax({
type: 'POST',
url: 'suppression-message',
data: {
'checkboxIdArray': checkboxIdArray.toString(),
}
}).done(function(result)
{
alert(result);
});
return false;
}
});
</script>
Here is the php code
<?php
if (isset($_POST['checkboxIdArray'])) {
$checkboxIdArray = $_POST['checkboxIdArray'];
$str = json_encode($checkboxIdArray);
$tab = explode(",", $str);
$deleteSuccess = true;
foreach($tab as $id)
{
$id = filter_var($id, FILTER_SANITIZE_NUMBER_INT);
if (!$messageModelDb->delete($id)) {
$deleteSuccess = false;
die();
}
}
if ($deleteSuccess === true) {
$message = 'Success';;
} else {
$message= "Error";
}
echo $message;
}
?>
Since jQuery implemented deferreds, .done is the preferred way to implement a success callback. You should also implement a .fail method with a failure response code.
I've been trying to post data using AJAX that will update a field in my database however I am having trouble doing so. Everything seems like it should run fine and I get no errors in the console but I've no idea why my db won't update.
Can someone help me out here please?
AJAX:
function ajaxUpdate() {
var arr = {var1: name, var2: age};
$.ajax({
url: 'ajax/confirm.php',
type: 'POST',
data: JSON.stringify(arr),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(data) {
console.log("success");
}
});
}
Confirm.php:
$name=$_POST['var1'];
$age=$_POST['var2'];
if($name == "Stuart") {
mysqli_query($connection,"UPDATE people SET age='$age'");
}
else if($name == "Peter") {
mysqli_query($connection,"UPDATE people SET age='$age'");
}
The connection to my database is working as I have $connection setup and went to the page /ajax/confirm.php in my browser and I see "Connection successful" in my console as I defined if successful.
So I am unsure as to why this isn't updating?
Are my values not being posted correctly?
I'm new to AJAX so forgive me if this is something very simple!
Thanks
Try the following:
function ajaxUpdate() {
var arr = {var1: name, var2: age};
$.ajax({
url: 'ajax/confirm.php',
type: 'POST',
data: arr,
success: function(data) {
console.log("success");
}
});
}
Instead of converting the object into json string send it as is.
Edit: Also remove dataType and probably contentType too. Your code is at risk of SQL Injection. Look into prepared statements and escaping mysql data.
Maybe this well help.
<script type="text/javascript">
function ajaxUpdate() {
var data = $('#formID').serialize();
$.ajax({
url: 'ajax/confirm.php',
type: 'POST',
data: data,
dataType: 'json',
encode : true,
success: function(data) {
if(data == "ok"){
console.log("success");
}else{
console.log(data);
}
}
});
}
</script>
confirm.php
<?php
$name = $_POST['name'];
$age = $_POST['age'];
switch ($name) {
case 'Stuart':
$sql = "UPDATE people SET age = ? WHERE name = ? ";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, 'si', $name, $age);
if (mysqli_stmt_execute($stmt)) {
echo json_encode('ok');
} else {
echo json_encode(mysqli_stmt_error($stmt));
}
break;
case 'Peter':
$sql = "UPDATE people SET age = ? WHERE name = ? ";
$stmt = mysqli_prepare($connection, $sql);
mysqli_stmt_bind_param($stmt, 'si', $name, $age);
if (mysqli_stmt_execute($stmt)) {
echo json_encode('ok');
} else {
echo json_encode(mysqli_stmt_error($stmt));
}
break;
default:
echo json_encode('Unknown name ');
}
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.