I run the PHP code by ajax method with the click of a button.
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
}
});
});
I would like the file.php to be able to run the js code, for example:
if ($time < $_SESSION['time']) {
[...]
}
else {
echo '<script>alert("lol");</script>';
}
And that when the button .btn_ranking on the page is pressed, an 'lol' alert will be displayed. If it is possible?
you can echo a response to the AJAX call and then run the JS according to the response..
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time },
success: function (data) {
if(data==1){
//do this
}else if(data==2){
//do that
alert('LOOL');
}
}
});
});
PHP CODE:
if ($time < $_SESSION['time']) {
echo '1';
}
else {
echo '2';
}
You can't said to a server-side script to use javascript.
What you have to do is to handle the return of you'r ajax and ask to you'r front-side script to alert it. Something like that :
file.php :
if ($time < $_SESSION['time']) {
[...]
}
else {
echo 'lol';
exit();
}
Front-side :
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
},
success : function(data) {
alert(data);
}
});
});
When you used ajax for call php script, everything will be print in the return of the php code will be return to the HTTP repsonse and so be on the Ajax return function as params.
Ok .. First change your js code to handle answer from php script:
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time }
success: function(data) {
console.log(data);
// check if it is true/false, show up alert
}
});
});
Then change php script (file.php), something like that:
$response = [];
if ($time < $_SESSION['time']) {
$response['data'] = false;
}
else {
$response['data'] = true;
}
return json_encode($response);
Something like that is the idea :) When u send ajax with POST method get variables from there, not from $_SESSION :)
U can see good example here
Related
Im quiet confused with this code. Im reading this code of ajax which inserts the data automatically. but what im confused is this line if(result=='12') then trigger ajax what does 12 means why it should be 12 then conditioned to before ajax. Apparently im still learning ajax thanks. P.S this is working well btw im just confused with the code
here is the full code of the create function javascript / ajax
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var result = '';
if(empoyeeName.val()==''){
empoyeeName.parent().parent().addClass('has-error');
}else{
empoyeeName.parent().parent().removeClass('has-error');
result +='1'; //ALSO THIS NUMBER 1 WHY SHOULD IT BE 1?
}
if(address.val()==''){
address.parent().parent().addClass('has-error');
}else{
address.parent().parent().removeClass('has-error');
result +='2'; //ALSO THIS NUMBER 2 WHY SHOULD IT BE 2?
}
if(result=='12'){ //HERE IS WHAT IM CONFUSED
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type ="updated"
}
$('.alert-success').html('Employee '+type+' successfully').fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
}
});
As I have explained in my commentaries, and since you wanted an example. This is how I will proceed in order to avoid checking for result == '12':
$('#btnSave').click(function()
{
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
// Validate form
var empoyeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var formValid = true;
if (empoyeeName.val() == '')
{
empoyeeName.parent().parent().addClass('has-error');
formValid = false;
}
else
{
empoyeeName.parent().parent().removeClass('has-error');
}
if (address.val() == '')
{
address.parent().parent().addClass('has-error');
formValid = false;
}
else
{
address.parent().parent().removeClass('has-error');
}
// If form is not valid, return here.
if (!formValid)
return;
// Otherwise, do the ajax call...
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response)
{
if (response.success)
{
$('#myModal').modal('hide');
$('#myForm')[0].reset();
var type = '';
if (response.type=='add')
type = 'added';
else if (response.type=='update')
type ="updated";
$('.alert-success').html('Employee ' + type + 'successfully')
.fadeIn().delay(4000).fadeOut('slow');
showAllEmployee();
}
else
{
alert('Error');
}
},
error: function()
{
alert('Could not add data');
}
});
});
It's just checking existence of values and appending string to it.
if(empoyeeName.val()=='')
This check empty name and add error if name is empty. else it concat 1 to result.
if(address.val()=='')
This check empty address and add error if address is empty. else it concat 2 to result.
So if both of them are non empty that means result will be 12 and than only you make ajax call else show error.
Bear with me I'm my javascript is a little rusty. So I'm trying to use a call by ajax to a PHP file and give it a plan type then make sense of it check to see if it then return a true or false if some allowed slots are less than some slots used up for the plan. Here is the Form in XHTML.
<form method="post" action="/membership-change-success" id="PaymentForm">
<input type="hidden" name="planChosen" id="planChosen" value="" />
</form>
On the same file. The ( < PLAN CHOICE > ) gets parsed out to the current plan.
<script>
var hash = window.location.hash;
var currentPlan = "( < PLAN CHOICE > )";
$(".planChoice").click(function(event){
var isGood=confirm('Are you sure you want to change your plan?');
var success;
$("#planChosen").val($(this).data("plan"));
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: ({plan: $(this).data("plan")}),
success: function (data) { //This is what is not working I can't get it to return true
success = data;
}
});
if(success) {
if (isGood) {
$("#PaymentForm").submit();
}
window.location = '/membership-change-success';
} else {
alert('Please make sure you deactivate your listings to the appropriate amount before you Downgrade.')
}
});
My PHP for the ajax response looks like this.
<?php
require ('../includes/common.php');
include_once ('../includes/db-common.php');
require ('../includes/config.php');
$membership = new membership($dbobject);
$listing = new listing($dbobject);
$totalAvailableListings = ($membership->get_listingsAmount($_POST['plan']));
if($totalAvailableListings>=$listing->get_active_listings($user->id)){
echo json_encode(true); // I've tried with out jason_encode too
} else {
echo json_encode(false);
}
And that's pretty much it if you have any suggestions please let me know.
So I've tried to do it another way.
$(".planChoice").click(function (event) {
var isGood = confirm('Are you sure you want to change your plan?');
var success;
$("#planChosen").val($(this).data("plan"));
if (false) {
if (isGood) {
$("#PaymentForm").submit();
alert('you did it');
}
} else {
alert(isSuccessful($(this).data("plan")));
//alert('Please make sure you deactivate your listings to the appropriate amount before you downgrade.');
}
});
and I have an ajax function
function isSuccessful(plan) {
return $.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: {plan: plan}
});
}
The alert tells me this [object XMLHttpRequest]
any suggestions?
$.ajax() returns results asynchronously. Use .then() chained to $.ajax() call to perform task based on response
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: {plan: $(this).data("plan")}
})
.then(function(success) {
if (success) {
$("#PaymentForm").submit();
}
// if `form` is submitted why do we need to set `.location`?
// window.location = '/membership-change-success';
} else {
alert('Please make sure you deactivate your listings to the appropriate amount before you Downgrade.')
}
}, function err(jqxhr, textStatus, errorThrown) {
console.log(errorThrow)
})
You should use the following form for your ajax call
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: ({plan: $(this).data("plan")}),
success: success = data
})
.done(function(response) {
if(success) {
if (isGood) {
$("#PaymentForm").submit();
}
window.location = '/membership-change-success';
}
else {
alert('Please make sure you deactivate your listings to the
appropriate amount before you Downgrade.')
}
});
the .done() clause ensures that you perform that code after the ajax call is finished and the response is obtained.
For a link like this
DELETE
i am using this ajax call
$(function() {
$(".delete_msgs").click(function() {
var msgid = $(this).attr("id");
var dataString4 = 'msgid=' + msgid;
$('a#'+msgid).html('<img src="img/loader.gif" class="loading" />');
$.ajax({
type: "POST",
url: "del_msg.php",
data: dataString4,
cache: false,
success: function(data){
if (data == 0) {
//alert('Sent!');
} else {
$('a#'+msgid).html(data);
$('.viewmessage'+msgid).hide();
}
}
});
return false;
});
});
The del_msg.php file contains that code:
if(isset($_POST)) {
$msgid = $_POST['msgid'];
$delmsg = mysql_query("DELETE FROM messages
WHERE id = $msgid") or die(mysql_error());
echo 'Message sent!';
} else {
echo 0;
}
My big question is, how can i protect my send throught AJAX function? Anyone can change the id of the #a element and, consequently, can delete any row from my database.
Is there a more secure way to call php with ajax, or at least, to hide my important variables sent via ajax?
I have this PHP CodeIgniter code where in the view I am getting input from a text field. Using AJAC I am trying to pass this value to the controller using GET request. The controller will then call a function from my model to retrieve a database record matching the search criteria.
For some reason it doesn't work. I tried to do a var dump in the controller to see if the value is passed by AJAX, but I am not getting anything. Any ideas what I am doing wrong and why I can't receive the form value in the controller?
View:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.13.3/jquery.min.js"</script>
<script language="Javascript">
$(document).ready(function () {
$('#submitbutton').click(function () {
$.ajax({
url: "../../index.php/testcontroller/getdatabasedata",
data: {
'searchvalue' : $('#inputtext').val()
},
method: 'GET'
}).done(function (data) {
var dataarray = data.split('##');
$('#question').html(dataarray[ 1 ]);
$('#answer1').html(dataarray[ 2 ]);
});
return false;
});
});
</script>
</body>
Controller
public function getdatabasedata()
{
$this->load->model('testmodel');
$year = $this->input->get('searchvalue');
//I TRIED TO DO A VARDUMP($YEAR) BUT I DON'T GET ANYTHING!
$movie = $this->testmodel->findquestion($year);
$moviesstring = implode(",", $movie);
echo $moviesstring;
}
Model
function findquestion($searchvalue)
{
$this->db->where('answer1', $searchvalue);
$res = $this->db->get('questions');
var_dump($res)
if ($res->num_rows() == 0)
{
return "...";
}
$moviearray = $res->row_array();
return $moviearray;
}
Script:
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script language="Javascript">
$(document).ready(function ()
{
$("#submitbutton").bind("click",function()
{
var target_url = '<?php echo(base_url()."testcontroller/getdatabasedata") ; ?>';
var data = {'searchvalue' : $('#inputtext').val() };
$.ajax ({
url : target_url,
type: 'GET',
data: data,
cache: false,
success: function(controller_data)
{
var dataarray = controller_data.split('#');
$('#question').html(dataarray[1]);
$('#answer1').html(dataarray[3]);
},
});
return false;
});
});
</script>
.bind("click",function() - add quotes to click event.
var dataarray = controller_data.split('#'); - split
data caracter must match character in implode function in controller.
Controller:
public function getdatabasedata(){
$this->load->model('testmodel');
$year = $this->input->get('searchvalue');
$movie = $this->testmodel->findquestion($year);
$separated = implode("#", $movie);
echo $separated;
}
Hope this helped.
I will share my usual ajax code that I use in my views , make sure your base url is correct
$("#submitbutton").bind("click",function()
{
var target_url = '<?php echo(base_url()."testcontroller/getdatabasedata") ; ?>';
$.ajax
(
{
url : target_url,
type: "GET",
// data: {'searchvalue' : $('#inputtext').val()},
cache: false,
success: function(data)
{
alert(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("error during loading ....");
}
});
});// end loading via ajax
and in your controller just echo something
public function getdatabasedata()
{
//$this->load->model('testmodel');
//$year = $this->input->get('searchvalue');
//I TRIED TO DO A VARDUMP($YEAR) BUT I DON'T GET ANYTHING!
//$movie = $this->testmodel->findquestion($year);
//$moviesstring = implode(",", $movie);
//echo $moviesstring;
echo "hello";
}
I have the below JQuery ajax function which is used to update a PHP Session variable.
I POST two variables, which the PHP page collects and sets the relevant Session variable.
Occasionally though it doesn't work, even though the correct values are being Posted across.
So I started to look at whether the Ajax was completing OK in these cases by adding success / error functions to the ajax.
But what I have found is that on every occasion I am gettng a response from the error function, and not the success function, even when it does complete succesfully and update the PHP variable.
Am I missing something here. Do I need to create a response or should that be automatic?
My Javascript is:
GBD.updateFunction = function(p,x)
{
$.ajax(
{
type: "POST",
url: "SetSession.php",
dataType:'text',
data:
{
item:p,
section:x
},
success: function()
{
alert('success');
},
error: function()
{
alert('failure');
}
});
console.log(p + " " + x + " selected");
return false;
}
The setSession . php is:
$section = (isset($_POST['section']) ? $_POST['section'] : 0 );
if($section == 1)
{
if(isset($_POST['item']))
{
$pageVar = $_POST['item'];
$_SESSION['pagevar'] = $pageVar;
}
else
{
$_SESSION['pagevar'] = $_SESSION['pagevar'];
};
}
?>
Try this way
//server code
$section = (isset($_POST['section']) ? $_POST['section'] : 0 );
if($section == 1)
{
if(isset($_POST['item']))
{
$pageVar = $_POST['item'];
$_SESSION['pagevar'] = $pageVar;
}
else
{
$_SESSION['pagevar'] = $_SESSION['pagevar'];
};
echo "success";
}
?>
//ajax call
GBD.updateFunction = function(p,x)
{
$.ajax(
{
type: "POST",
url: "SetSession.php",
dataType:'text',
data:
{
item:p,
section:x
},
success: function(data)
{
console.log(data);
},
error: function(jqxhr)
{
//it will be errors: 324, 500, 404 or anythings else
console.lgo(jqxhr.responseText);
}
});
return false;
}