I am making a forum webpage where I'll put delete this buttons under each comment. Now when you press this button, I send the ID of the comment to PHP file using ajax which looks like this:
function Deletethis(index) {
var result = confirm("Want to delete?");
if (result==true) {
$.ajax({
url: "deletepost.php",
type: "POST",
data: index,
success: function(){
location.reload();
}
});
} else return false;
}
Now the problem is I can't receive it from the PHP end. I've used the debugger and saw that the index value is right. My PHP looks like this:
<?php
$con = mysqli_connect("localhost", "root", "123", "test") or die("DIE");
if (isset($_POST['index'])) {
$SoonToBeDeletedComment = $_POST['index'];
};
$index = intval($SoonToBeDeletedComment);
mysqli_query($con, "DELETE FROM commentsbox WHERE commentsbox.`ID` = $index");
echo "Post Deleted...";
mysqli_close($con);
?>
My code doesnt give any errors but it doesn't delete the post either. When I do the same process manually on navicat, it is working so I thought maybe the index is a string and it should be an integer. So I used intval but it didnt solve the problem either. Any ideas to help me improve my code is appreciated. Thanks in advance
In jQuery's .ajax call, the data property needs to be an object, not a string (string only it it's a full GET query string, actually, but it's not what you need here).
So, try this:
$.ajax({
url: "deletepost.php",
type: "POST",
data: {id: index},
success: function(response){
alert(response);
// location.reload();
}
});
And then in PHP, get it as:
$_POST['id']
UPDATE
Sanity checklist:
is your Deletethis function actually receiving the index?
is your ajax calling the right script?
is ajax data property an object, like I explained above?
what is the output of the PHP script?
what are the contents of $_POST?
is the id inside the $_POST array ($_POST['id'])?
does the row with that id exist in the db?
These questions should help you pinpoint the problem more accurately.
You send param to your PHP code without define his name : data: { index: index } // param : value
function Deletethis(index)
{
if ( confirm("Want to delete?") )
{
$.ajax({
url: "deletepost.php",
type: "POST",
data: {
index: index
},
success: function(){
window.location.reload();
}
});
}
}
Check also if your PHP code is working by calling page directly with param.
Related
I wonder how I can pass value from Jquery to PHP. I found similar codes but not even one of them work.
Everytime alert shows value of variable but when I open site there is not any. Var_dump shows that $_POST is null. I am ran out of ideas do you have any?
jQuery code:
$("#password-button").click(function(){
var password="";
var numbers =[0,0,0,0,0,0];
for(var i=0;i<=5;i++){
numbers[i] = Math.floor((Math.random() * 25) + 65);
password += String.fromCharCode(numbers[i]);
}
$(".LoginError").text("Nowe haslo: " + password);
$.ajax({
type: 'post',
url: 'dzialaj.php',
data: {'password': password},
cache:false,
success: function(data)
{
alert(data);
console.log(result)
console.log(result.status);
}
});
});
PHP:
if(isset($_POST['password'])){
$temp = $_POST['password'];
echo $temp;
}
Since it looks like you are new on ajax, let's try something more simple ok? Check this js:
<script>
var string = "my string"; // What i want to pass to php
$.ajax({
type: 'post', // the method (could be GET btw)
url: 'output.php', // The file where my php code is
data: {
'test': string // all variables i want to pass. In this case, only one.
},
success: function(data) { // in case of success get the output, i named data
alert(data); // do something with the output, like an alert
}
});
</script>
Now my output.php
<?php
if(isset($_POST['test'])) { //if i have this post
echo $_POST['test']; // print it
}
So basically i have a js variable and used in my php code. If i need a response i could get it from php and return it to js like the variable data does.
Everything working so far? Great. Now replace the js mentioned above with your current code. Before run the ajax just do an console.log or alert to check if you variable password is what you expect. If it's not, you need to check what's wrong with your js or html code.
Here is a example what i think you are trying to achieve (not sure if i understand correctly)
EDIT
<script>
var hash = "my hash";
$.ajax({
type: 'post',
url: 'output.php',
data: {
'hash': hash },
success: function(data) {
if (data == 'ok') {
alert('All good. Everything saved!');
} else {
alert('something went wrong...');
}
}
});
</script>
Now my output.php
<?php
if(isset($_POST['hash'])) {
//run sql query saving what you need in your db and check if the insert/update was successful;
// im naming my verification $result (a boolean)
if ($result) echo 'ok';
else echo 'error';
}
Since the page won't redirect to the php, you need a response in you ajax to know what was the result of you php code (if was successful or not).
Here is the others answers i mentioned in the coments:
How to redirect through 'POST' method using Javascript?
Send POST data on redirect with Javascript/jQuery?
jQuery - Redirect with post data
Javascript - redirect to a page with POST data
I am fairly new in the Ajax's world, tho I've tried it maybe twice and it always worked like a charm. Now I am trying to send variable with ajax() method but it seems like I have 0 errors in my console but I think the problem is that I am sending no variable at all.. If, in my php file, I echo a string it's working. So my problem is that I can't echo out the variable. I am on Laravel 5, this is why you will see Request::get('my_input_name').
Here is my js code :
$('.select_blocs_check').click(function() {
var blocID = $(this).val();
$.ajax({
type: "POST",
url: "http://localhost/send/getBlocHtml/",
data: {id: blocID},
success: function(html) {
$('#preview-wrap').html(html);
}
});
});
This is my php file
public function getBlocHtml()
{
$bloc_id = Request::get('id');
echo $bloc_id;
}
So, if I change my php file like this
public function getBlocHtml()
{
$bloc_id = Request::all();
print_r($bloc_id);
}
Now, it will print out : array(). Like if I have nothing in my data.. What's wrong with my data parameter in $.ajax ?
I see Laravel 5 in your question. Try Request::input('id'); Which will pull both Post and get.
Change how you pass your data. Try this :
$.ajax({
type: "POST",
url: "http://localhost/send/getBlocHtml/",
data: {'id': blocID},
success: function(html) {
$('#preview-wrap').html(html);
}
});
try change Request::get('value') to Input::get('value')
API says
This method is used for all request verbs (GET, POST, PUT, and DELETE)
In Laravel 5 API is Input static method.
And article which may help to you.
I am trying to understand a $.ajax call:
var url = "/api/followuser.php/" + userID ;
$.ajax(url, { 'success': function(data) {
/do something
}
});
Thia ajax call is required to pass the variable 'userID' to the file '/api/followuser.php' to make a database query(php/Mysql).
I don't have access to '/api/followuser.php' .
Can anyone help me figure out how to get the variable 'userID' from the URL in a php file to be used in a database query.( I know how to pass variable as 'data: userID,' in $.ajax and use it in a php file but i want to understand this particular example)
Maybe you mean followuser.php?user_id= instead? The slash is probably causing issues since that's interpreted as a directory by the server:
var url = "/api/followuser.php?user_id=" + userID;
you need to use GET method with ajax, to do this you can use next example
$.ajax({
url: "/api/followuser.php",
type: "GET",
data: {variable: "valueofvariable"},
success: function(data) {
console.log(data);
}
});
so in your php file you can read the variable like this
<?php
if(isset($_GET["variable"])){
echo $_GET["variable"];
// if this works you should see in console 'valueofvariable'
}
?>
This is a process that I use for other ajax update functions, but for this specific instance, it doesn't want to work. I don't know if I'm missing something in my code, or if the fact that part of the query string is a url and needs to be encoded before the AJAX plugin (don't know this and couldn't find any info on it, just brainstorming).
When I access the php script directly and echo out the query, then run it in console mode, it works fine. When I try to access it with AJAX, I get the success response, but the entry is not updated in the DB, so I assume that means the script did not run properly.
Here is my code:
AJAX
jQuery('#nl-details').on('click','#d-cl-change', function(){
var mls = jQuery('#d-mls').val(),
cl = jQuery('#d-cl-input').val(),
url = 'scripts/forms/cl/clchange.php?mls='+mls+'url='+cl;
jQuery('#test').html(url); //This is just for me to view the URL
jQuery.ajax({
url: url,
dataType: 'json',
success: function(data){
jQuery('#d-cl-save').fadeIn('200').delay('800').fadeOut('800');
jQuery('#d-cl-url').html('Go to Listing');
},
error: function(){
jQuery('#d-cl-fail').fadeIn('200').delay('800').fadeOut('800');
}
});
});
PHP
//Generic include for MYSQL Credentials
define('INCLUDE_CHECK',true);
require('../../c.php');
$url = mysqli_real_escape_string($link,urldecode($_GET['url']));
$mls = mysqli_real_escape_string($link,$_GET['mls']);
$query = "UPDATE `nht_actprop`
SET CLLINK = '".$url."'
WHERE MSTMLSNO = '".$mls."'";
$result = mysqli_query($link,$query);
echo $query;
mysqli_close($link);
On this line of yor code you are missing a &
url = 'scripts/forms/cl/clchange.php?mls='+mls+'url='+cl;
I think it's supposed to be like this
url = 'scripts/forms/cl/clchange.php?mls='+mls+'&url='+cl;
I see that you have chosen a best answer already but I would just like to share with you how I would tackle this task.
I would recommend using AJAX's type option to send data via GET like this:
jQuery('#nl-details').on('click','#d-cl-change', function(){
var url = 'scripts/forms/cl/clchange.php';
jQuery('#test').html(url); //This is just for me to view the URL
jQuery.ajax({
url: url,
type: 'GET',
data: {
mls: jQuery('#d-mls').val(),
url: jQuery('#d-cl-input').val()
},
dataType: 'json',
success: function(data){
jQuery('#d-cl-save').fadeIn('200').delay('800').fadeOut('800');
jQuery('#d-cl-url').html('Go to Listing');
},
error: function(){
jQuery('#d-cl-fail').fadeIn('200').delay('800').fadeOut('800');
}
});
});
And the best part is that you don't have to change your PHP at all
Good luck! Let me know your thoughts
I have a PHP program for counting user banner clicks. My banner link is something like this:
<a href="<?=$banner_url;?>" onclick="banner_click_count('<?=$banner_id;?>')"><img src=...>
When user clicks on image, it runs banner_click_count() function with $banner_id as parameter.
function banner_click_count($ban_id)
{
$.ajax({
type: "POST",
url: 'banner_click.php',
data: {banner_id: $ban_id}
});
}
At banner_click.php, I get the banner_id with $banner_id = $_GET['banner_id']);, search the database based on it. Find the record, then add 1 to banner_count column field. After that, redirect to banner_url.
When I run the program, I get Parse error: parse error, expecting T_VARIABLE' or '$'' on line $.ajax({
Addendum: the error is cleared with all your help, but when I click on the link it redirects to banner_url directly and does not run the AJAX function.
Addendum:I put the alert("hello"); at the top of ajax function and i got it. So it goes into function
1.You need to put your javascript function under <script> tag
2.you need to pass json string as post data
3.though you are passing your data as post so you will get this data in php as $_POST not $_GET
So change your function as below
<script>
function banner_click_count(ban_id)
{
$.ajax({
type: "POST",
url: 'banner_click.php',
data: {banner_id: ban_id}
});
}
</script>
// in your php use as below
echo $_POST['banner_id']
Make sure banner_id is in quotes and that you are including JQuery in your page.
And don't forget a success/error return.
$.ajax({
type: "POST",
url: 'banner_click.php',
data: {'banner_id': $ban_id},
success: function(s) {
console.log('success' + s);
},
error: function(e) {
console.log('error' + e);
}
});
Don't we need a return false before the function ends?
I found the solution. Thanks to all.
function banner_click_count(ban_id)
{
$.post(
"banner_click.php",
{
banner_id: ban_id
});
}