Posting data using jQuery Ajax to another php file [duplicate] - php

This question already has answers here:
What is the order of inline onclick vs addeventlistener and why?
(3 answers)
Closed 2 years ago.
I have two PHP pages. On one of the pages, I want to post data to the other page when a button is pressed. However, when I try to access the post array from the other page, it appears empty. Would appreciate if someone could show me where I'm going wrong. (Also I'm not allowed to use a html form to post)
Page called test2.php:
<?php
if(isset($_POST['testing1'])){
die(json_encode($_POST));
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<link rel="stylsheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" integrity="sha512-s+xg36jbIujB2S2VKfpGmlC3T5V2TF3lY48DX7u2r9XzGzgPsa6wTpOQA7J9iffvdeBN0q9tKzRxVxw1JviZPg==" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<button id="testbtn" onclick="location.href='test1.php'">Test Button</button>
<script>
$(document).ready(function(){
$('#testbtn').click(function() {
$.ajax({
method: 'POST',
url: 'test1.php',
data: {
testing1: 'string1',
testing2: '111'
},
success: function(data){
alert(data);
output = JSON.parse(data);
}
});
});
});
</script>
</body>
</html>
Page called test1.php:
<?php
$testvar = json_encode($_POST);
echo $testvar;
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<link rel="stylsheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" integrity="sha512-s+xg36jbIujB2S2VKfpGmlC3T5V2TF3lY48DX7u2r9XzGzgPsa6wTpOQA7J9iffvdeBN0q9tKzRxVxw1JviZPg==" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
</body>
</html>

the reason the it's failing is because you have so much html on test1.php
alert(data) is having an issue because there is so much content.
JSON.parse(data) is failing because it's not just json it's also html
test1.php should just simply parse post to json and echo it
<?php
echo json_encode($_POST);
?>

When you press the button 2 things are happening in same time :
The ajax call that sends data to the page test1.php
The page redirection beacause of the onClick attribute on the button.
The ajax request calls the page test1.php which is not the same instance as the page you call when you use the onClick attribute. So I think you could try placing "location.href = 'test1.php'" in the success function and store $_POST in a session variable. That way the data will reach the test1.php page before your redirect.
success: function(data){
alert(data);
output = JSON.parse(data);
location.href = 'test1.php';
}

Maybe like this:
Page called test2.php:
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<link rel="stylsheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" integrity="sha512-s+xg36jbIujB2S2VKfpGmlC3T5V2TF3lY48DX7u2r9XzGzgPsa6wTpOQA7J9iffvdeBN0q9tKzRxVxw1JviZPg==" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<button id="testbtn" onclick="location.href='test1.php'">Test Button</button>
<script>
$(document).ready(function(){
$('#testbtn').click(function() {
$.ajax({
method: 'POST',
url: 'test1.php',
data: "yourData="+"{
testing1: 'string1',
testing2: '111'
}",
dataType:"json",
success: function(data){
alert(data);
output = JSON.parse(data);
}
});
});
});
</script>
</body>
</html>
Page called test1.php:
<?php
if(isset($_POST["yourData"]){
$testvar = json_decode($_POST["yourData"]);
echo $testvar->testing1."<br/>";
echo $testvar->testing2;
}else{
echo"is not set";
}
if(!empty($_POST["yourData"]){echo $_POST["yourData"];}else{echo"is empty";}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<link rel="stylsheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" integrity="sha512-s+xg36jbIujB2S2VKfpGmlC3T5V2TF3lY48DX7u2r9XzGzgPsa6wTpOQA7J9iffvdeBN0q9tKzRxVxw1JviZPg==" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/gh/emn178/chartjs-plugin-labels/src/chartjs-plugin-labels.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
</body>
</html>
NB:
dataType:"json" used if you want to get a json answer;
if you use dataType:"json" that mean you have to change the method json_decode() in my code to json_encode();
isset() check if name of associative array is exist;
! means not;
empty() check that if the value of that name in associative array is empty (like ' ');
!empty() check that if the value of that name in associative array is not empty (not like ' ').

Related

BootstrapDialog Alert in Codeigniter Controller

I want to use bootstrapDialog alert (https://nakupanda.github.io/bootstrap3-dialog/) instead of default alertbox of browser in my controller but its not working.
I included these scripts I got from the github dist folder in the bottom of view
<link rel="stylesheet" href="assets/css/bootstrap-dialog.min.css" />
<script src="assets/js/bootstrap-dialog.min.js"></script>
Controller
function student(){
if ($student_status == 'paid'){
echo '<script type="text/javascript">';
echo 'BootstrapDialog.alert('Your Registration was successful')';
echo '</script>';
}
else {
// redirect url
}
}
I also tried to echo the css and js files in the controller but failed. If I echo the default alertbox, it works, please what could I be doing wrong?
first - you have some errors:
you need to escape your single quotes of the alert like:
echo 'BootstrapDialog.alert(\'Your Registration was successful\')';
or you could use mix of single and double quotes like:
echo 'BootstrapDialog.alert("Your Registration was successful")';
you also might need to load your script and css with a leading slash like:
<link rel="stylesheet" href="/assets/css/bootstrap-dialog.min.css" />
<script src="/assets/js/bootstrap-dialog.min.js"></script>
you are loading your stylesheet as script, <script src="assets/css/bootstrap-dialog.min.css"></script>; is incorrect, use <link rel="stylesheet" href="your.css">
second - its not a good idea to mix javascript and php the way you do it, you cannot call a jquery function from php, you can only generate html, which then executes at runtime. This would work:
if ($student_status == 'paid'){
$str=' <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.35.1/js/bootstrap-dialog.min.js"></script>
<script type="text/javascript">
setTimeout(function() {
BootstrapDialog.alert(\'Your Registration was successful\')
},10);
</script>';
echo $str;
}
note the setTimout() function, it is needed to give a little time to make sure all your files are loaded.
third - The correct way is to use ajax instead: see docs:
jquery ajax calls your php function student.
function student returns true or false.
In the ajax success callback you add your bootstrapDialog.alert
Bootstrap dialog is built on Bootstrap, so you must include bootstrap css and bootstrap js, followed by the bootstrapDialog css and js
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
http://jsfiddle.net/mreis1/YJdB7/1/
For Example
View:
<!DOCTYPE html>
<html>
<head>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.35.1/css/bootstrap-dialog.min.css" rel="stylesheet" type="text/css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap3-dialog/1.35.1/js/bootstrap-dialog.min.js"></script>
<title>Bootstrap Dialog Test</title>
</head>
<body>
<!-- IF SUCCESSFUL -->
<?php $alert= ''; ?>
<?php if ($alert == 'success'): ?>
<script type = "text/javascript">
BootstrapDialog.alert('Your Registration was Successful');
</script>
<?php endif; ?>
<!-- IF FAILED -->
<?php if($alert == 'failed'): ?>
<script type = "text/javascript">
BootstrapDialog.alert({
title: 'An Error Occured',
message: 'Your Registration failed',
type: BootstrapDialog.TYPE_DANGER,
buttonLabel: 'Close'
});
</script>
<?php endif; ?>
</body>
</html>
Controller:
function student(){
if ($student_status == 'paid'){
$data['alert'] = 'success';
}
else {
$data['alert'] = 'failed';
}
$this->load->view(view_page, $data);
}
Output:
echo "BootstrapDialog.alert('Your Registration was successful')"
You have to either escape quotes or use double quotes.
Try This Code
<link rel="stylesheet" href="<?php echo base_url();?>assets/css/bootstrap-dialog.min.css" />
<script src="<?php echo base_url();?>assets/js/bootstrap-dialog.min.js"></script>

Passing variable using ajax and open next page

I try passing variable from one page to next using ajax.
I have running passing, but I don't know how to open page with this variable.
My actual code:
<!DOCTYPE html>
<html lang="pl">
<head>
<meta charset="UTF-8">
<title>Ajax</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<!-- <script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<button id="test" class="btn btn-lg btn-primary">Test</button>
<script>
$(document).ready(function () {
$("#test").click(function () {
var variable = 'AAAaaa';
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'view.php',
data: {"temp": variable},
success: function (data) {
alert("success!");
}
});
});
});
</script>
</body>
</html>
And second page where I want watching what is in $_Post table
<?php
$table = $_POST;
?>
<pre>
<?= print_r($table);?>
</pre>
Edit for comment:
Not a problem. You can create a callback function inside ajax's
success event. On success, take that data from view.php and send it to
the second page with another ajax call. It will all be done
asynchronously and accomplish what you're asking for. – putipong
I have array in view. For example:
$array = array(
"foo" => "bar",
"bar" => "foo",
);
How to send via post and ajax this array to controller function and open this action, when I press the button.
I tried as above , but does not work
public function actionUuuu()
{
$request = Yii::$app->request;
$array = $request->post();
print_r($array)
In your view.php, you can assign the table data to $_SESSION and then retrieve later in your second page, simply by starting a session with session_start();
A session must be started on every page that requires the use of session data, else it will not work.
view.php:
session_start();
if ($_POST['temp'] == 'AAAaaa') {
$_SESSION['tableData'] = $tableData;
echo true;
} else {
echo false;
}
return;
Javascript:
$(document).ready(function () {
$("#test").click(function () {
var variable = 'AAAaaa';
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'view.php',
data: {"temp": variable},
success: function (data) {
if (data == 'true') {
window.location.replace('secondPage.php');
}
}
});
});
});
secondPage.php
session_start();
$table = $_SESSION['tableData'];

How to get value FROM Ajax in index.php

I would like to get the value sent from php via AJAX in php. But i can not get value. Where is my mistake?
It is my functions.js
$(document).ready(function(){
$(".yeni_problem").click(function(){
var uid = 1;
$.ajax({
url: 'admin.php',
type: "post",
data: {'uid': uid},
success: function(data){
// $("#cvb").text(data);
},
statusCode: {
404: function(){
alert("admin.php not found");
}
}
});
});
});
and it is my php page that, i control sending value in here. The Codes is large but i write small form. Which that when i run the small codes on other folders as other site it does't work.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HELPDESK</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/css.css">
<link rel="stylesheet" href="css/default.css">
<link rel="stylesheet" href="css/animate.css">
<link rel="stylesheet" href="css/icon.css">
</head>
<body>
<button class="yeni_problem">Yeni Problem</button>
<?php
if(isset($_POST['uid'])){
echo "Value:".$_POST['uid'];
}else{
echo "<hr>Value not found<br/>";
}
var_dump($_POST);
?>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="js.js"></script>
<script type="text/javascript" src="functions.js"></script>
<script type="text/javascript" src="bootstrap.min.js"></script>
<?php
echo "</body>
</html>";
?>
When i click to ".yeni_problem" class i can not get value.
1st- check you include Jquery
2nd- Be sure admin.php page in the same directory with file you called functions.js in if not check its path
3rd- you pass uid not data so in php use
<?php
if(isset($_POST['uid'])){
echo "Value:".$_POST['uid'];
}else{
echo "Value not found";
}
?>
4th: and if you dynamically generate the element with class="yeni_problem" .. so use
$('body').on('click',".yeni_problem", function(){
instead of
$(".yeni_problem").click(function(){
5th: if yeni_problem is a submit button or anchor so you need to use e.preventDefault(); to prevent page from reloading
$(".yeni_problem").click(function(e){
e.preventDefault();
// rest of code here
6th: if yeni_problem is a form use .submit()
$(".yeni_problem").submit(function(e){
e.preventDefault();
// rest of code here
Pay attention to your code: in the JS snippet, the parameter passed to the server is "uid", which means your server will be getting a $_POST array with a position labeled "UID".
<?php
if(isset($_POST["uid"])){
echo "Value:".$_POST["uid"];
}else{
echo "Value not found";
}
?>
You should also check what is in the $_POST variable, insert var_dump($_POST) and comment out the rest of the code.

Passing PHP value to jQuery progressbar

How to pass the PHP value $sources to the value of progress bar? I am trying to add into session in the below code but fail. Any easy way to get the $sources? Please help.
......
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
var score = '<%= session.getAttribute("sources") %>';
$( "#progressbar" ).progressbar({
value: score
});
});
</script>
</head>
<body>
<?php
session_start();
$sources=10;
......
echo '<td>Your answer was correct </td></tr>';
$sources+=1;
......
$_SESSION['sources']=$sources;
?>
<div id="progressbar"></div>
</body>
</html>
session_start() should be at the top of the page. after starting
then $_SESSION['sources'] should be set before calling it. otherwise you should check for it's value before printing to web page.
find below codes and rearrange your script.
<?php
session_start();
?>
......
<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
var score = <? echo (isset($_SESSION['sources'])) ? $_SESSION['sources'] : ""; ?>;
$( "#progressbar" ).progressbar({
value: score
});
});
</script>
</head>
<body>
<?php
$sources=10;
......
echo '<td>Your answer was correct </td></tr>';
$sources+=1;
......
$_SESSION['sources']=$sources;
?>
<div id="progressbar"></div>
</body>
</html>
var score = '<%= session.getAttribute("sources") %>';
The <%= %> is java syntax for scriplets ,
additionally it's wrapped in quotes so it is treated as a string literal from javascript.
Below is the syntactically right way (I don't know if you'll get the right value. That
depends on your program structure).
var sources = <?php echo $_SESSION['sources']; ?>;

CodeIgniter Ajax CSRF Jquery Cookie Method behaving unexpectedly

Javascript Section:
var token = $.cookie("csrf_cookie_name");
var tx = document.getElementById("tx"+working_row).value;
var mods =document.getElementById("mods"+working_row).value;
var pos = document.getElementById("pos"+working_row).value;
var startdate = document.getElementById("startdate"+working_row).value;
var enddate = document.getElementById("enddate"+working_row).value;
var fordx = document.getElementById("4dx"+working_row).value;
var qty = document.getElementById("qty"+working_row).value;
var price = document.getElementById("price"+working_row).value;
obj = new Object();
obj={'csrf_token_name':token,'tx':tx,'mods':mods,'pos':pos,'startdate':startdate,'enddate':enddate,'fordx':fordx,'qty':qty,'price':price};
alert(obj.csrf_token_name);
$.post("index.php/auth/fee_schedule",obj, function(data){
alert(data);
});
The issue I'm having is that the token variable isn't being included in the post. I'm not sure why. The Alert is [Object Object] so, null. The header of the page has the following:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Medata Preauthorzation System</title>
<link rel="stylesheet" href="<?php echo base_url();?>css/screen.css" type="text/css" media="screen">
<script type="text/javascript" src="<?php echo base_url();?>js/jquery.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/jquery.sexy-combo.min.js"></script>
<link rel="stylesheet" href="<?php echo base_url();?>css/jquery-ui-1.8.13.custom.css" type="text/css" media="screen">
<link rel="icon" type="image" href="/medata/favicon.ico">
<script type="text/javascript" src="<?php echo base_url();?>js/jquery.impromptu.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/jquery-ui-1.8.13.custom.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>js/cookie.js"></script>
</head>
So the Library and Cookie Functions are included. I use the cookie function 10 other times on the same page to do posts and it works fine, but I don't put any of them into objects with other variables, so it's just inline alla
$.post("index.php/auth/tx_history/"+tx_code, { csrf_token_name: $.cookie("csrf_cookie_name") }, function(data){
//alert(data);
$("#price"+rowid).val(data);
});
I'd Love some Suggestions, i've been hitting my head against this code most of the afternoon for non-stop issues.
Maybe:
var token = $.cookie("<?php echo $this->config->item("csrf_cookie_name"); ?>");

Categories