Really bizarre bug when using jquery ajax and php - javascript

I'm trying to create a like button for different images posted by user. This is my html :
Like
This is my javascript:
<script>
$(function(){
$(".likes").click(function(){
var postid = $(this).attr("id");
alert(postid);
$.ajax({
type:'POST',
url:'likes.php',
data:'id='+postid,
success:function(data){
alert("success");
}
});
});
});
</script>
This is likes.php, for testing purpose it's quite simple:
<?php
require('config.php');
$postid=$_POST['id'];
echo $postid;
?>
When I clicked the like button, a small window will correctly postid, and then "success",which indicates that the ajax is successful, however, when I opened likes.php, I got an error that says: Notice: Undefined index: id in C:\XAMPP\htdocs\likes.php on line 3
I tried adding e.preventDefault(). I tried different syntax,such as data:'id='+postid, data:{id:postid},data:{'id':postid},etc. I experimented with basically all combinations of single quotes and double quotes. I also tried adding datatype:html and datatype:text. Every time I just got a alert that says "success", but when I open likes.php, $_POST['id'] is always undefined.
Can someone help me please this bug took me a lot of time.
Update: I found that even if I entered a completely non-existing url, like url:"aabbll.php", after I clicked the "like" button, I would still see a window that alerts "success", why does the page keep alerting "success" even though clearly the AJAX process wasn't a success?

You are not sending the post variable "id" when you are opening like.php in a new browser window.
The error "Notice: Undefined index" is shown because the $_POST array does not contain the id field.
You can use a chrome extension called postman to test endpoints with post variables.
A tip to improve the code could be to wrap it in an if isset statement
if(isset($_POST['id'])){
// this code will only be executed if the post variable is sent to the page
$postid=$_POST['id'];
// update database
echo "Success";
}else{
echo "ERROR: No id post variable found";
}
Your javascript code is sending the post variable

Try to put var_dump($_POST) to see what you really post.

Couple of suggestions.
Your JS can be simply
<script>
$(function() {
$('.likes').on('click', function() {
var postid = $(this).attr('id');
$.post("likes.php", {id: postid}).done(function( data ) {
alert( 'Data Loaded: ' + data );
});
});
});
For your PHP
<?php
if (!isset($_POST['id'])) {
/// Do what you want to do in this case.
}
$id = $_POST['id'];
// If using PHP7
$id = $_POST['id'] ?? null;
Though $('.likes') works try to avoid that since it is slowest selector in most cases.

Related

Load php file within javascript (AJAX or others)

I am trying to finish one page of my website the last couple of hours while achieving the following.
While clicking on a button, the following should happen
Download link appears (done - works)
The mySQL table should be opened and a counter should be incremented
As far as I got the points. Javascript cannot handle that and thus we can use AJAX or jQuery. I was already checking out different posts and websites such as:
how to execute php code within javascript
https://www.w3schools.com/js/js_ajax_database.asp
and much more. However, I guess I do have problems with the AJAX syntax and I actually don't know if the requested php files is loaded/opened or not. Especially the second link given above is almost similar to what I am searching for. However, it does not work. To check if the php file is called, I set an alert which works if I do call the file explicitly in the browser. Maybe this does not work with AJAX as I expect it. Here the code to get more familiar with the inconstency I am doing.
The page code:
<?php
echo '<div><button onclick="incrementAndDownload('testPath', 'fileName'); ">Click me</button></div>';
?>
<script>
function incrementAndDownload (link, fileName)
{
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
// Print something if necessary
}
});
//- Open the link
// window.open(arguments[0], "_blank");
//- Increment download inside mysql
//var xhttp;
//xhttp = new XMLHttpRequest();
//xhttp.open("GET", "openfoam/increment.php?foo=nana", true);
//xhttp.send();
}
</script>
The increment.php looks as follows:
<?php
echo '<script type="text/javascript" language="Javascript">
alert("Test message if the script is called...");
</script>';
// Code for accessing the mysql database and manipulate the data
//$page_id = mysql_real_escape_string(html_entities($_POST['file']));
?>
Now when I click the button, the javascript is executed (e.g., if I uncomment the window.open) this works as expected. However, as already said, the second part is to open the database via php and increment a number (counter). For any reason, I am not able to figure out where the problem is located. I am even not sure if AJAX opens the increment.php file (the alert messages never appears so I guess it is never called). Any suggestion is appreciated and I hope that this question does not just contain a fundamental small error. Thank in advance, Tobi
It's not the way the AJAX works. If you call alert() on a destination page it won't show in your browser. Your case is very basic so I will keep my solution on a basic level.
In increment.php just echo something, it can be just OK string. So when you go to increment.php page you will see only OK, nothing more, nothing less.
Then go back to your javascript and check what is your response.
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
if (data == 'OK') {
console.log('It works, sir!');
}
}
});
If you don't see a message in a console after these modifications something doesn't work. However, I think your page is executed properly, but you just don't get feedback, because you don't handle the response (data param in your case).
Check it out and don't forget to give me a feedback!🤓

WordPress Button triggered ajax request

So I have actually read stackoverflow questions about this, but they are somewhat quite old to work with newest version of wordpress.
My end goal is to submit to database some data from my forms but for now ajax response is not working for me. On custom page load in WP all code is loaded so all functions should work. All of this is inside of PHP file for now that why echo is used to create JS scripts. Here's the important part of my code
echo '<button id="ZapisPrace">Save</button>
<script>
jQuery("#ZapisPrace").click(function($){
var data={
action: "addToDB",
info: "nomz"
};
jQuery.post(ajaxurl,data,function(response){
alert("Response was "+ response);
});
});
</script>';
add_action('wp_ajax_addToDB','pridajDoDB');
function pridajDoDB(){
echo '<script>console.log("AAA")</script>';
wp_die();
}
Using current version of WP so variable ajaxurl is pointing to the
/wordpress/wp-admin/admin-ajax.php
No console.log is happening, response is always 0, even when I remove pridajDoDB function or add_action. It's just not triggering the ajax request correctly. Can somebody let me know why?
Also I have not used yet functions like wp_localize_script, wp_register_script or wp_enqueue_script because all of this is in one PHP file that's loaded, and I don't need to import jquery as far as I know its default available in WP. I am just learning how to use WP, PHP AJAX and jQuery, so I have still quite a lot to learn.
PS: I am supposed to use the WP way of using ajax.
Change php code as follows.
add_action('wp_ajax_addToDB','addToDB');
function addToDB(){
echo "AAA";
wp_die();
}
Ok so I didn't figure out how code above works, however I managed to get it working trough different wp structure I found online:
BTW: I used onClick function here but it works even when replaced with jQuery click event.
add_action('wp_ajax_addToDB','pridajDoDB');
echo '<button onClick='triggerAjax()'>Save</button>?>';
<script>
function triggerAjax(){
<?php $nonce = wp_create_nonce( 'subbmitData' );?>//used so ajax response can verify from where is the request coming
jQuery.ajax({
type: "post",url: "admin-ajax.php",data: { action: 'addToDB', _ajax_nonce: '<?php echo $nonce; ?>' },
success: function(html){
console.log(html);//this will console log everything that happens in ajax called php function. Echo works as well.
}
});
}
</script>
<?php
function pridajDoDB(){
check_ajax_referer( "subbmitData" );//this check from where is the request coming from
//here database commands works but if you echo or console log something it will be just passed to success function above
die();
}
?>

Why does my jquery ajax post succeed but the $_POST array is still empty?

This is my first question on here, please bear with me:
My ajax request is:
<script>
$.ajax({
type:"POST",
url:"http://localhost/folder/something.php",
data: { BuildingName:'Jacaranda'},
success: function(data){alert("It worked")},
error: function(data){alert("It failed")},
});
</script>
In my something.php file I have:
$Building= $_POST['BuildingName']; //Error Occurs Here
I get an error on this line stating:
Notice: Undefined index: BuildingName.
When I do VAR_DUMP it returns the $_POST array as empty.
I have checked and rechecked. Looked at different answers here and cannot seem to find the problem. I hope it is not staring me in the face.
I appreciate any help, thank you.
SOLUTION: Instead of simply trying to pass data between pages solely which I do not think is possible(correct me if I'm wrong), there has to be an intermediary. I passed my data into MySQL and had my webpage "listen" to the DB and do something based on the most recent entry.
SOLUTION USING SESSIONS per the advice of Lukas1 (you're right this is more efficient.)
<?php
$_SESSION['Building']= 'something';
$Building= $_SESSION['Building'];
echo "<script> $('#Jacaranda').click(function(){
var id = $(this).attr('id');
$Building= id;
}) </script>";
?>
And my call on the next page is:
<?php echo $Building ?>
Works perfectly without using database as intermediary.
Just change your data attribute to
"BuildingName=Jacaranda"
and it should work all fine.

jQuery loading value from php file into html input on button click - not working

i have a text file with a number that is inside it. The number should be +1 inside the text file and the new value should be updated inside index.php all this should happen after a button inside index.php is clicked, but thats not happening.. i did a lot of googling and i tried many things from what i sow still it's not working, keeping in mind I'm new to jQuery. below is all the involved code explained. any help will be appreciated!
The php script inside index.php to retrieve the value from num.txt and place it inside the text input once index.php is loaded, this works perfectly:
<?php
$filename = "num.txt";
$file = fopen("num.txt","r+");
$number = fread($file, filesize($filename));
fclose($file);
?>
The text input code, as you can see will take the $number value from the above script and this works fine. keep in mind i used the id of the input and the class of it then i ended up adding a div and using its class, i didn't know what to do so i tested them all, same thing nothing worked:
<div class="on"><input type="text" id ="omlat" class="inv-number" value="<?php echo $number;?>"></input></div>
jQuery to update the value after clicking on the submit button. this function should only refresh the value of the input value by calling inum.php and taking the value inside inum.php after the code there is excited:
$(document).ready(function(){
$(".reloadpg").click(function(){
$(".on").load("http://localhost/einvoice/inum.php");
});
});
Code inside inum.php, this code works fine i tested it (this code takes the number inside num.txt and +1 the value as you can see):
<?php
header("Cache-Control: no-cache");
$filename = "num.txt";
$file = fopen("num.txt","r+");
$number = fread($file, filesize($filename));
$number = $number + 1; //the new number to proceed
file_put_contents('num.txt', $number);
echo $number;
fclose($file);
?>
-- Update --
The code bellow worked for the above part it worked perfectly but now I'm facing another problem. Another function that listens to the same button that was working before stopped working! so what i did was that i toke some of the code that the guys bellow provided and pot it inside the older function that was listening to the button click the whole code is as follows(please read the comments to understand the code):
$('.create-invoice').on('click',function()
{
//Below is the code i added from the first problem above its not working here.. when it was alone outside this function as the accepted answer it will work but it will stop this function from working!
$.get( "/einvoice/inum.php", function(data) {
$('.inv-number').val(data);
});
//Above is the code i added from the first problem..
//below is the original code for the function, keep in mind only the below code is bing excited the above is not.. its not refreshing the part of the page it should its calling the php script successfully tho, but i will have to refresh the page my self to see the number updated
grab_invoice_data();
// Declare a variable
var jsonObj = invoice_data;
// Lets convert our JSON object
var postData = JSON.stringify(jsonObj);
// Lets put our stringified json into a variable for posting
var postArray = {json:postData};
$.download("php/json.php", postArray, 'post');
//if cookie exists
var i_n = $('.inv-number').val();
$.cookie('lid', ++i_n, { expires: 365 } );
//invoices created
if( $.cookie('ic') ){
var ck_inv_created = ($.cookie('ic'));
$.cookie('ic', (++ck_inv_created));
} else {
$.cookie('ic', ++inv_created);
}
})
You're replacing the input with the number, rather than just updating its value. Try this instead...
$(document).ready(function(){
$(".reloadpg").click(function(){
$.get("http://localhost/einvoice/inum.php", function(data) {
$(".on input").val(data);
});
});
});
That uses jQuery's get() method to make an ajax call that passes the response into a callback function as a parameter. You can then do whatever you need with it inside that function.
You jquery part is not good. Try this :
$(document).ready(function(){
$(".reloadpg").click(function(){
$.get( "/einvoice/inum.php", function( data ) {
$("#omlat").val(data);
});
});
});

How to use send responses back to ajax and process each response separately

On Page1:
An AJAX script is processed loading Page2
On Page2:
A mysqli Database query will run, if the database query is successful, I want to send a success response back to AJAX query and reload the page. If the database query fails, I want to send a fail response back to AJAX query and redirect to fail page.
Is this possible? How would I write this? I'm new to AJAX and have reviewed some AJAX scripts and also read documentation, but I learn best by experimenting with code to find solutions that work for me. I have played with a few ajax scripts but can't get any of them to work correctly and can't find one that does anything near what I need. Seems like it would be a fairly easy ajax script, so I was hoping someone could help me with it.
Here's a possible jQuery solution. Let me know if you want pure JavaScript.
index.html
<input type="text" id="input" />
<button type="button">Submit!</button>
scripts.js
$('button').on('click',function() {
var val = $('#input').val();
sendQuery(val);
});
function sendQuery(x) {
var val = x;
$('body').load('query.php?input=' + val);
}
query.php
$mysqli = new mysqli('localhost','root','password','db');
$val = $_GET['input'];
$query = <<<Q
SELECT
*
FROM
table
WHERE
column = ?
Q;
$stmt = $mysqli->stmt_init();
if($stmt->prepare($query)) {
$stmt->bind_param("i",$val);
$stmt->execute();
while($stmt->fetch()) {
#if the query is successful
echo '<script>
$(function() {
location.reload();
});
</script>';
}
} else {
echo '<script>
$(function() {
window.location.href = "http://www.yoursite.com/errorpage.html";
});
</script>';
}
$mysqli->close();
The only thing I'm uncertain about is why you want to send a response back with AJAX, and then move to a completely new page. To me that kind of seems like that negates the reason you're wanting to use AJAX in the first place. Any thoughts?
What the above does is use jQuery to load XMLHTTPRequest.responseText into the body (the reponseText is the scripts that are echoed by your php doc). In this case, in the case of success from the db, it echoes a script that reloads the page. In the case of a failure, it echoes a script that moves the user to an error page.

Categories

Resources