AJAX not updating MySql data - javascript

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

Related

Why isnt my ajax response returning anything?

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

PHP not receiving AJAX POST from js File

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;
}
});
}

Posting data using Ajax

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 ');
}

unable to get value in controller from jquery, ajax in php code igniter

AJAX:
$(document).ready(function () {
$('.my_button').click(function () {
var data = $(this).val();
//alert(BASE_URL);
$.ajax({
type: "POST",
ContentType: 'application/json',
data: data,
url: BASE_URL + 'index.php?deo/dashboard',
error: function () {
alert("An error occoured!");
},
success: function (msg) {
alert('result from controller');
}
});
alert(data);
});
});
CONTROLLER:
public function dashboard() {
$data = $this->input->post('data');
$data = json_decode($data);
echo "<script>alert('count ".$data."');</script>";
}
Am trying to send value from my jquery, ajax to controller, am able to get value from my view page to jquery page and able to print that. But unable to send the value from ajax page to controller page, after sending the data i got the success data. but unable to get and print the data in my controller page. Thanks in advance
If your using firefox a good thing to use is firebug add on and then you can use the console to check for errors on there. To see if the ajax has any errors while sending.
Remove question mark after index.php? and I think your base url is not working correct try just.
Url
// With index.php
url: 'index.php/deo/dashboard',
// Or without index.php
url: 'deo/dashboard',
Or
// With index.php
url: <?php echo site_url('index.php/deo/dashboard');?>,
// Or without index.php
url: <?php echo site_url('deo/dashboard');?>,
Script
$(document).ready(function () {
$('.my_button').click(function () {
var data = $(this).val();
$.ajax({
type: "POST",
data: data,
url: 'index.php/deo/dashboard',
// url: <?php echo site_url('index.php/deo/dashboard');?>,
success: function (msg) {
alert('result from controller');
},
error: function () {
alert("An error occoured!");
}
});
alert(data);
});
});
Controller
public function dashboard() {
$data = $this->input->post('data');
echo "<script>alert('count ".$data."');</script>";
}

Jquery AJAX with codeigniter, always returns error

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.

Categories