Cannot call php delete from database using ajax - javascript

I am new to javascript and ajax, I want to call php file which deletes the selected row from Mysql database in a javascript file so I tried to explore the answers I found here concerning this question but I couldn't resolve it, here is the php file called delete-consultation.php:
<?php
global $db;
$idconsult=$_POST['del_id'];
$q = $db->prepare(
'DELETE FROM consultation
WHERE id_consultation = :idc');
$q->bindValue(':idc', (int)$idconsult , PDO::PARAM_INT);
$q->execute();
And here is how I tried to call it using ajax:
$.ajax({
url: "delete-consultation.php",
type: "POST",
cache: false,
data:{
del_id: rows[0]
},
success: function(){
console.log("true");
}
});
I am getting 200 ok as a response but always without the id paraleter and the delete operation is not being executed, am I missing anything? Any advice could help, thanks

I solved the issue by editing the ajax code like this:
$.ajax({
url: "delete-consultation.html",
type: "POST",
cache: false,
datas:{
del_id: rows[0]
},
success: function(){
console.log("true");
},
error: function(){
console.log("false");
}
});
and the php code was correct actually what was wrong is the word 'data' changed to be 'datas':

Related

$_POST empty in post Ajax Request

I tried to check the solution in the other similar post on the forum, but I did not resolve my problem yet.
So, I have this Ajax Request in my .js page
JS Code
$(document).ready(function(){
$(document).on('click', '.mySubmitTextButton', function() {
var dataToSend = {};
dataToSend.text = $("#comment").val();
console.log(dataToSend);
$.ajax({
type: "POST",
url: "../submitPages/submitText.php",
data: dataToSend,
dataType: "json",
success: function(result){
console.log(result);
var mediaToClone = $(".rowToCopy").clone();
$(".userId", mediaToClone).html(result.user);
$(".textTweet", mediaToClone).html(result.text);
$(".userAvatar", mediaToClone).attr("src",result.avatar);
mediaToClone.removeClass("rowToCopy hidden");
mediaToClone.appendTo($(".tweetBox"));
},
error: function(result){
console.log(result);
}
});
});
});
PHP Code
if (!isset($_SESSION)) { session_start(); }
include ("../db/db.php");
var_dump($_POST);
if(submitText($_POST["text"], $_SESSION["name"])){ //which is the call to the query function
$propic = getUserPic($_SESSION["name"]);
$result = array(
"text" => $_POST["text"],
"user" => $_SESSION["username"],
"avatar"=>$propic
);
echo json_encode($result);
}
FROM THE BROWSER
Form Data
text: test //This is the Params Tab
//In the response tab
<pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=1)</i>
'text' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>'ccccccccc'</font> <i>(length=9)</i>
</pre>{"text":"ccccccccc","user":"blackout_chisel","avatar":"..\/..\/img\/useravatar\/0826fc411cd2dc627ddd0b0cac0f7fb7.jpg"}
The datas seem to be correctly passed from the js to php (in the browser console I see the parameters correctly passed), but with var_dump($_POST) in the php file, I get an empty array, so I can't use $_POST["text"] in the query case the index is undefined.
Any ideas?
Ok guys, thanks all, I had a misunderstood on it. It works perfectly. I was trying to see the result var_dump($_POST), when the ajax call was already done. That's why it was obviously empty.

AJAX post to php not getting caught

Posting from javascript ajax (which according to alerts it hits correctly and succeeds at) I cannot get the post from my PHP code.
<script>
function SavePlot() {
$.ajax({
method: "POST",
url: 'PhpToR.php',
data:{action:'SavePlot'},
success:function() {
alert("gets here");
}
});
}
</script>
So above it reaches the gets here alert, so it should be posting, however it isnt caught by the below php:
if(isset($_POST['action']) && $_POST['action'] == 'SavePlot') {
echo '<script>alert("Doesnt get here")</script>';
}
I've tried many other answers but couldn't seem to succeed.
First of all, whatever you echo in your php script won't show up automatically in your current HTML DOM.
However, you can retrieve what you've echo-ed in the PHP in your AJAX call:
success: function(response){
console.log(response);
alert("gets here");
}
In your console, you should see:
<script>alert("Doesnt get here")</script>
Try specifying dataType as HTML in your ajax request.
$.ajax({
method: "POST",
url: 'PhpToR.php',
data:{action:'SavePlot'},
dataType : 'HTML',
success:function() {
alert("gets here");
}
});

AJAX call returns undefined in Header / form-data

I am trying to get the contents from some autogenerated divs (with php) and put the contents in a php file for further processing. The reason for that is I have counters that count the number of clicks in each div. Now, I ran into a problem. When I echo back the data from the php file, the call is made, but I get undefined in the form-data section of the headers, and NULL if I do var_dump($_POST). I am almost certain I am doing something wrong with the AJAX call. I am inexperienced to say the least in AJAX or Javascript. Any ideas? The code is pasted below. Thanks for any help / ideas.
The AJAX:
$(document).ready(function(e) {
$("form[ajax=true]").submit(function(e) {
e.preventDefault();
var form_data = $(this).find(".test");
var form_url = $(this).attr("action");
var form_method = $(this).attr("method").toUpperCase();
$.ajax({
url: form_url,
type: form_method,
data: form_data,
cache: false,
success: function(returnhtml){
$("#resultcart").html(returnhtml);
}
});
});
});
The PHP is a simple echo. Please advise.
Suppose you have a div
<div id="send_me">
<div class="sub-item">Hello, please send me via ajax</div>
<span class="sub-item">Hello, please send me also via ajax</span>
</div>
Make AJAX request like
$.ajax({
url: 'get_sorted_content.php',
type: 'POST', // GET is default
data: {
yourData: $('#send_me').html()
// in PHP, use $_POST['yourData']
},
success: function(msg) {
alert('Data returned from PHP: ' + msg);
},
error: function(msg) {
alert('AJAX request failed!' + msg);
}
});
Now in PHP, you can access this data passed in the following manner
<?php
// get_sorted_content.php
if(!empty($_POST['yourdata']))
echo 'data received!';
else
echo 'no data received!';
?>
It's sorted. Thanks to everyone. The problem was I didn't respect the pattern parent -> child of the divs. All I needed to do was to wrap everything in another div. I really didn't know this was happening because I was echoing HTML code from PHP.

ajax success but not post data in the another page

i have this simple code:
var addUser = "simply";
$.ajax({
type: 'POST',
url: 'userControl.php',
data: {addUser: addUser},
success: function(response){
alert("success");
}
});
this is the page that i POST to: userControl.php, the if statement not entering so i didnt post? but i got alert message "success".
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == 'POST'){ //if page was requested with POST
echo $_POST['addUser'];
}
?>
I got the alert message "success", but the data is not POST to the other page.
Im also try out to write 'simply' with one apostrophe. in another page in the same project i have a same Ajax and its working, so why this one not working? any ideas? i need to do it only with ajax, submit with form will not help me.
thanks
Pass data this way data: 'addUser=' + addUser
see below code
var addUser = "simply";
$.ajax({
type: 'POST',
url: 'userControl.php',
data: 'addUser=' + addUser,
success: function(response){
alert("success");
}
});
and you should remove window.location because it is possible before your ajax call completes page will redirect

jquery .ajax always returns error - data being added to database

I am trying to add users to a database using jquery ajax calls. The users get added just fine to the database, but the ajax always returns with error. I'm not sure how to retrieve the specific error either. Below is my code, form, php, and jquery.
Here is the jquery
$(document).ready(function() {
//ajax call for all forms.
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
Here is the PHP
<?php
include 'class_lib.php';
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
echo json_encode('true');
} else {
echo json_encode('false');
}
}
Here is the HTML
<div id='newUser' class='tool'>
<h3>New User</h3>
<form method='post' name='newUser' data='../php/newUser.php'>
<span>Username</span><input type='text' name='username'><br>
<span>Password</span><input type='password' name='password'>
<input type='submit' name='submit' class='button' style='visibility: hidden'>
</form>
<span class='result'> </span>
</div>
#Musa, above you mentioned
My guess is its a parsing error, try removing dataType: 'json', and see if it works
You absolutely solved the problem I was having! My ajax post request was similar to above and it just kept returning to the 'error' section. Although I checked using firebug, the status was 200(ok) and there were no errors.
removing 'dataType:json' solved this issue for me. Thanks a lot!
Turns out I had to add async: false to the $.ajax function. It wasn't getting a response back from the php.
I know this is an old question but I have just run into a weird situation like this ( jquery ajax returns success when directly executed, but returns error when attached to button, even though server response is 200 OK )
And found that having the button inside the form tags caused JQuery to always return error. Simply changing the form tags to div solved the problem.
I believe JQuery assumes the communication should be form encoded, even though you say it is application/json.
Try moving your button outside your form and see what happens...
I had the same problem and discovery there. All the time the problem is the version of my jQuery, I had use jquery version (jquery-1.10.2.js) but this version is not Ajax stablish. So, I change version for (jquery-1.8.2.js) and this miracle heppened.
Good Luck Guy!
You should specify status Code 200 for successful response.
<?php
http_response_code(200);
?>
See here: http://php.net/manual/en/function.http-response-code.php
The first solution
Try to remove dataType in your js file like that:
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
The second solution
Send a real clean JSON to AJAX like that:
PHP
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
$error = [
"title"=> 'true',
"body"=> 'some info here ... '
];
echo json_encode($error);
} else {
$error = [
"title"=> 'false',
"body"=> 'some info here ... '
];
echo json_encode($error);
}
}
JavaScript
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (data) {
let x = JSON.parse(JSON.stringify(data));
console.log(x.title);
console.log(x.body);
},
error: function() {
//code here
}
});
});
});

Categories