Check db and then redirect using Ajax - php

So it's my first time handling or rather using ajax and it still rattles my mind. I made this ajax function so when everytime I push a button it checks the value of something on db and if it's true then it should redirect. It works fine or rather redirect when I refresh the webpage but that isn't what I was expecting, I was expecting that if the value on the db being checked is "EQUAL TO" or True then it should redirect without me having to refresh the page just so it can do it's stuff. Hoping for some insights, thanks!
My home.php has this:
<script src="js/ajax.js"></script>
My Ajax JS:
$.ajax
({
url: "testjax.php",
type: "post",
data: $('#Button').serialize(),
dataType:'json',
success: function (data)
{
if (data.status=='SUCCESS')
{
window.location="/anotherdirectory/";
}
else
{}
},
error: function (e) {
console.log('error:'+e);
}
});
Testjax PHP
<?php
session_start();
require_once('path/sql.php');
require_once('path/who.php');
$userID = Who::LoggedUserID(); //Found in who.php
$userData = Who::GetUserData($userID);
$userPoints = $userData['points'];
if ($userPoints==0.00)
{
$tent='SUCCESS';
}
else
{
$tent='ERROR';
}
$ary=array("status"=>$tent);
echo json_encode($ary);
?>

Related

ajax to php $variable

I try to pass this value to my php code, but I do not know how to do it. post method does not work. (I do not know why).
<script>
var val = localStorage.getItem('sumalist');
$.ajax({
type: "POST",
url: "index.php",
data: {value: val},
success: function () {
console.log(val);
}
});
</script>
and in my php code, value is not set.
if (isset($_POST["value"])) {
echo "Yes, value is set";
$value = $_POST["value"];
}else{
echo "N0, value is not set";
}
PS: My php code is in the same file in js code.
Check if this works
<?php
if(!empty($_POST)) {
$value = (isset($_POST["value"])) ? $_POST["value"] : NULL;
$return = ($value != NULL) ? "Yes, value is: ".$value : "N0, value is not set";
echo $return;
exit;
}
?>
<script src="//code.jquery.com/jquery-3.3.1.js"></script>
<script>
var val = 'value sent';
$.ajax({
type: "POST",
url: "index.php",
data: {value: val},
success: function (ret) {
console.log(ret);
}
});
</script>
Open console for result
Please use console if you're using chrome then open console and try debugging,
And first you run that ajax function in jquery ready function like this
$(document).ready(function (){ $.ajax( replaced for ajax function ) }
If you want to use the response in callback success function, use this:
success: function (ret) {
console.log(ret); //Prints 'Yes, value is set' in browser console
}
In your browser you have Developer Tools - press F12 to open, go to Network tab (FireFox, Chrome, IE - all the same), then reload your page and you will see the line for your AJAX call (if it is performed on load, or trigger your call if this is not the case), select it and right hand you'll see a extra frame where you can see all the details of your request, including request params, headers, response headers, the actual response and many other.
That's the best solution to check your AJAX request without asking uncompleted questions and seeking for the answers in case someone can assemble your full case in his mind.
Believe me - this is the best solution for you and not only for this case!
Of course your JS should be performed when DOM is ready so you have to wrap it in
${function() {
// your code here
});
in case you want to be executed on load.

How to send data from one page to another and upon success show a modal

This is my page from where I want to send data to dashboard/fpass.php page and upon success show a modal.
<script>
$(document).ready(function () {
$('#fmodal').click(function () {
$.ajax({
type: "POST",
url: "dashboard/fpass.php",
data: { name: "fpass" }
})
success: function(data) {
$("#myModal").modal();
}
});
});
</script>
And here is my next page where I want to get my data and send a mail.
<?php
if(($_POST['name'])=='fpass')
{
/*add sql connection*/
require('../includes/dbconfig.php');
/*get the image file name from the table*/
$sql="select * from admin";
$res=mysqli_query($con,$sql);
$row=mysqli_fetch_array($res);
$email=$row['email'];
$password=$row['password'];
$bemail=$row['bemail'];
$sub="dashboard login password is < ".$password." >";
/*send mail to the sql entry*/
mail($email,"Forget Password Request",$sub,$bemail);
}
?>
Try changing your AJAX:
<script>
$(document).ready(function(){
$('#fmodal').click(function(){
var name = 'fpass';
$.ajax({
type: "POST",
url: "dashboard/fpass.php",
data: { name: name },
success: function(data) {
$("#myModal").modal('show');
}
});
});
});
</script>
Man, the problem that I see is in the receiving code. AJAX needs to get some response from that file, you are not sending anything back, that's why. When you execute the mail() function, if CORRECT, then return true, 1 or any message that you want referring to the successful operation.
Try this:
if (mail($email,"Forget Password Request",$sub,$bemail))
echo true; //or echo 1, something referring to successful execution
else {
/**
* If you want to use the error{} part of the AJAX, you need to send different headers
* header('HTTP/1.1 500 Internal Server Error');
*/
// And then the echo, or just the echo is fine if you want to use it in the success section
echo false; // or echo 0, somtehing referring to a failed execution
}
In the AJAX side, you get the response, and evaluate if is true or false and then you decide what to do.
Hope that can help. J.C!
Your JS code is not valid. Have a look here, to see how $.ajax(...) is used:

Ajax doesn't call server side function when jquery handler is fired

I'm building a simple forum on which I have a user details page with two text fields, one for the user's biography and another for his interests.
When the user clicks on the save icon, a handler on the jquery is suposed to call an ajax call to update the database with the new value of the biography/interests but the ajax call isn't being called at all and I can't figure it out since I don't find any problems with the code and would apreciate if someone could take a look at it.
this is the textarea:
<textarea rows="4" cols="50" id="biography" readonly><?php if($info['bio'] == "") echo "Não existe informação para mostrar";
else echo $info['bio']; ?></textarea>
Here is the icon the user clicks on:
<li style="display:inline;" class="infoOps-li"><img class="info-icons" id="save1" src="assets/icons/save.png" alt=""></li>
this is the jequery with the ajax call:
$("#save1").click(function(){
var bio = $("#biography").val();
alert(bio); //this fires up
$.ajax({
url:"assets/phpScripts/userBioInterest.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {functionName: "bio", info:bio},
success:function(result){
alert(result.abc); //this doesn't fire
}
});
$("#biography").prop("readonly","true");
});
I know that the jquery handler is being called correctly because the first alert is executed. The alert of the ajax success function isn't, so I assume that the ajax call isn't being processed.
On the php file I have this:
function updateBio($bio)
{
$user = $_SESSION['userId'];
$bd = new database("localhost","root","","ips-connected");
$connection = $bd->getConnection();
if($bio == "")
{
echo json_encode(array("abc"=>'empty'));
exit();
}
if($stmt = mysqli_prepare($connection,"UPDATE users SET biografia = ? WHERE user_id = ?"))
{
mysqli_stmt_bind_param($stmt,'si',$bio,$user);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo json_encode(array("abc"=>'successfuly updated'));
}
$bd->closeConnection();
}
if(isset($_POST['functionName']))
{
$function = $_POST['functionName'];
echo $function;
if(isset($_POST['info']))
$info = $_POST['info'];
if($function == "bio")
{
updateBio($info);
}
else if($function == "interest")
{
updateInterests($info);
}
}
Can anyone shed some light on why isn't the ajax call being called?
Thank you
EDIT: changed "function" to "functionName" in json data object as suggested.
A possible problem is dued to a wrong parsing of the PHP output (for example due to a PHP error). You are reading the output as JSON, so if the output is not a JSON, success callback will not be triggered.
$("#save1").click(function(){
var bio = $("#biography").val();
alert(bio); //this fires up
$.ajax({
url:"assets/phpScripts/userBioInterest.php",
type: "post", //request type,
dataType: 'json',
data: {function: "bio", info:bio},
success:function(result){
alert(result.abc); //this doesn't fire
},
error: function(result){
alert("An error has occurred, check the console!");
console.log(result);
},
});
$("#biography").prop("readonly","true");
});
Try with this code, and check if an error is printed to the console.
You can use complete too, check here: http://api.jquery.com/jquery.ajax/

passing return variable from ajax to php

this is my ajax code that work perfectly if i show using an id.
$("#masa").change(function()
{ //if theres a change in the nokakitangan textbox
var masa = $("#masa").val();
var tkh_kerja = $("#tkh_kerja").val();
//Get the value in the nokakitangan textbox
if(tkh_kerja=='')
{
$("#cek_tarikh").html('<font color="Red"> Sila Isi Maklumat Tarikh Mula Bekerja </font>');
}
else
{
$("#cek_tarikh").html('<align="absmiddle"> Cek Tarikh Akhir...');
$.ajax
({ //Make the Ajax Request
type: "POST",
url: "ajax_cek_tarikhakhir.php", //file name
data: "bulan="+ masa +"&tkh_kerja="+tkh_kerja, //data
success: function(cekmasa)
{
$("#cek_tarikh").ajaxComplete(function(event, request)
{
$("#cek_tarikh").val(cekmasa);
});
}
});
}
return false;
});
the problem is, can the 'cekmasa' value pass to the php.? i need to use that value to do some code in php. is it possible to get the data from ajax? in the same page.
there is no problem when i return value in
<input align='right' type="text" name="tkh_akhir" maxlength="3" id="cek_tarikh" class="span2" readonly/>
no, that's not possible.
once your PHP page is processed by the server it sends the generated output to the client. and there is no PHP executed unless you reload the page or go to another page in your browser.
additional information: that's what often gets confused by people that start working with ajax. you use ajax because you want some "realtime behavior" without having to reload a whole html page. but ajax still is executed by your browser on the clientside.
simplified that's what you want to achieve with ajax, a communication between your browser and the server:
client(browser) <- ajax -> server(PHP)
but what you are asking for would be something like this:
server(PHP) <- ajax -> server(PHP)
which doesn't work and doesn't really make sense if you think about it.
you can call another ajax function to use php file inside success response like below
$("#masa").change(function()
{ //if theres a change in the nokakitangan textbox
var masa = $("#masa").val();
var tkh_kerja = $("#tkh_kerja").val();
//Get the value in the nokakitangan textbox
if(tkh_kerja=='')
{
$("#cek_tarikh").html('<font color="Red"> Sila Isi Maklumat Tarikh Mula Bekerja </font>');
}
else
{
$("#cek_tarikh").html('<align="absmiddle"> Cek Tarikh Akhir...');
$.ajax
({ //Make the Ajax Request
type: "POST",
url: "ajax_cek_tarikhakhir.php", //file name
data:
{
bulan:masa,
tkh_kerja:tkh_kerja
}, //data
success: function(cekmasa)
{
$("#cek_tarikh").ajaxComplete(function(event, request)
{
$("#cek_tarikh").val(cekmasa);
$.ajax
({ //Make another Ajax Request
type: "POST",
url: "", //file name
data:
{
}, //data
success: function()
{
}
});
});
}
});
}
return false;
});
You can do one thing. You can store ajax response in php session or cookie and then simply refresh page on ajax response.
//File: ajax_cek_tarikhakhir.php
// Your ajax handling code.
if(isset($__SESSION('ckmasa')){
$ckmasa = $__SESSION('ckmasa');
// use this $ckmasa for your php
}
$ckmasa = $output; // $ckmasa have data which you send to ajax response.
$__SESSION['ckmasa'] = $ckmasa;
echo $ckmasa;
return;
For your jQuery. Do as following.
$("#masa").change(function()
{ //if theres a change in the nokakitangan textbox
var masa = $("#masa").val();
var tkh_kerja = $("#tkh_kerja").val();
//Get the value in the nokakitangan textbox
if(tkh_kerja=='')
{
$("#cek_tarikh").html('<font color="Red"> Sila Isi Maklumat Tarikh Mula Bekerja </font>');
}
else
{
$("#cek_tarikh").html('<align="absmiddle"> Cek Tarikh Akhir...');
$.ajax
({ //Make the Ajax Request
type: "POST",
url: "ajax_cek_tarikhakhir.php", //file name
data: "bulan="+ masa +"&tkh_kerja="+tkh_kerja, //data
success: function(cekmasa)
{
$("#cek_tarikh").ajaxComplete(function(event, request)
{
$("#cek_tarikh").val(cekmasa);
// Reload page
location.reload();
});
}
});
}
return false;
});
I have just reloaded your page on ajax response. I have no idea how your server side code. but i tried to give some brief. hope this helps you. I have not tested code written above. Sorry for my bad English.

PHP/SQL Error: Possible race condition?

I'm a newbie at programming with AJAX and beginner at PHP programming. I'm not sure why, but when a user clicks an arrow to "Upvote" a post repeatedly and very fast, the PHP login_check decides that the user is no longer logged in. The program works if I click the arrow at a normal speed, but when I rapid fire it gets weird.
PHP code:
<?php
include "db_connect.php";
include "functions.php";
sec_session_start();
I was wondering if this is a definite case of race conditions and what I could do to prevent it--
AJAX code:
$(document).ready(function() {
$("#upvotearrow").click(function() {
setTimeout(function() { }, 500);
$resdiv=$("#upvotedownvote_resultalert");
$content=$("#upvotedownvote_resultalert_content");
$.ajax({
type: "POST",
url: "../secure/process_upvotedownvote.php",
data: { vote: "upvote", poemid: $("#poemidfield").val() },
dataType:"HTML"
})
.done(function(param) {
if (param=="true_upvote") {
$content.html("Upvote registered!");
$resdiv.css("visibility", "visible");
}
else {
$content.html("Invalid request");
$resdiv.css("visibility", "visible");
}
});
});
$("#downvotearrow").click(function() {
setTimeout(function() { }, 500);
$resdiv=$("#upvotedownvote_resultalert");
$content=$("#upvotedownvote_resultalert_content");
$.ajax({
type: "POST", //POST data
url: "../secure/process_upvotedownvote.php", //Secure upvote/downvote PHP file
data: { vote: "downvote", poemid: $("#poemidfield").val() }, //Get type of vote and poem_id in URL
dataType:"HTML" //Set datatype as HTML to send back params to AJAX function
})
.done(function(param) { //Param- variable returned by PHP file
if (param=="true_downvote") {
$content.html("Downvote registered!");
$resdiv.css("visibility", "visible");
}
else {
$content.html("Invalid request");
$resdiv.css("visibility", "visible");
}
});
});
});
The website with a live demo can be viewed here.
TO LOG IN, JUST USE THIS EMAIL: asdf#gmail.com AND THIS PASSWORD: asdf123
Thanks in advance for any advice!
I don't know about the race condition (which is likely but shouldn't mess with the session unless it is getting regenerated every time). Anyway, if I were you, I would disable the upvote/downvote button right after the first click.

Categories