I'm trying to pass a php variable from page1.html (which contains a php variable that I got from another form) to page2.php using ajax but it's not working, so I need your help.
code from page1.php:
<script>
var url = 'page2.php';
$("#save").click( function() {
$.ajax({
url : url,
type: 'post',
data : {
admin : <?php echo $admin; ?>,
gname : <?php echo $gname; ?>,
filename : docname,
content : encodeURIComponent(editor.getValue())
}
});
});
</script>
The datas filename and content are being sent successfully but admin and gname are not.
Thanks in advance.
UPDATE:
<?php
if(isset($_GET['admin'])) {
$admin = $_GET['admin'];
}
if(isset($_GET['gname'])) {
$gname = $_GET['gname'];
}
?>
This code is where I get the php variable that I want to send, from another form which is irrelevant to this question.
Here you go buddy, replace your script code with this.
<script>
var url = 'page2.php';
var admin = '<?php echo $admin; ?>';
var gname = '<?php echo $gname; ?>';
$("#save").click( function() {
$.ajax({
url : url,
type: 'post',
data : {
admin : admin,
gname : gname,
filename : docname,
content : encodeURIComponent(editor.getValue())
}
});
});
</script>
Youre using the type post so must use the $_POST in php
PHP
<?php
if(isset($_POST['admin'])) {
$admin = $_POST['admin'];
}
if(isset($_POST['gname'])) {
$gname = $_POST['gname'];
}
?>
You are using $_GET['admin'] which is used to fetch parameters delivered with GET method. You should be using $_POST['admin'] since you have set POST as your http request type in the JS code.
As everyone is saying you're mixing POST and GET. But it caught another thing that may bother you. Are those variables strings? If they are, maybe you're missing the apostrophe/single quote.
<script>
var url = 'page2.php';
$("#save").click( function() {
$.ajax({
url : url,
type: 'post',
data : {
admin : '<?php echo $admin; ?>',
gname : '<?php echo $gname; ?>',
filename : docname,
content : encodeURIComponent(editor.getValue())
}
});
});
</script>>
Your below code
<?php
if(isset($_GET['admin'])) {
$admin = $_GET['admin'];
}
if(isset($_GET['gname'])) {
$gname = $_GET['gname'];
}
?>
is to be replaced by
<?php
if(isset($_POST['admin'])) {
$admin = $_POST['admin'];
}
if(isset($_POST['gname'])) {
$gname = $_POST['gname'];
}
?>
You are sending POST parameters,while using get in PHP script. And another issue is you are not using quotes with $admin and $gname variables in ajax request.
Try following :
<script>
var url = 'page2.php';
$("#save").click( function() {
$.ajax({
url : url,
type: 'post',
data : {
admin : '<?php echo $admin; ?>',
gname : '<?php echo $gname; ?>',
filename : docname,
content : encodeURIComponent(editor.getValue())
}
});
});
</script>
PHP Script:
<?php
if(isset($_POST['admin'])) {
$admin = $_POST['admin'];
}
if(isset($_POST['gname'])) {
$gname = $_POST['gname'];
}
?>
Check if it helps you.
Related
I am trying to fetch events from an external php file onto the full calendar view. I had asked a similar question sometime back but I am still struggling with this thing.
CODE (JS):
<script>
$(document).ready(function() {
$('#ccategory').change(function(){
var id = $(this).val();
var user = $('#current_user').val();
var calendar = $('#calendar').fullCalendar({
events: {
url: '<?php echo get_site_url(); ?>/get_calcat_calendar.php',
data: function() { // a function that returns an object
return {
dynamic_value1: id,
dynamic_value2: user
};
}
error: function() {
alert('There was an error while fetching events.');
}
}
});
});
});
</script>
Also I am going to add the file which is generating the json file below:
PHP CODE:
while($row = mysqli_fetch_assoc($result)){
$title = get_the_title($row['ID']);
$url = get_permalink($row['ID']);
$e = array();
$e['title'] = $title;
$e['url'] = $url;
$e['start'] = $row['start_date'];
$e['end'] = $row['end_date'];
$e['color'] = '#33cc33';
array_push($events, $e);
}
echo json_encode($events);
exit();
This is the code which I am using the fetch the json from the database. Any help will be greatly appreciated. Thank You
REQUIREMENT UPDATE:
[{"title":"Timeout72","url":"http:\/\/www.goawebsites.com\/goacalendar\/event\/timeout72\/","start":"2017-11-29","end":"2017-12-31","color":"#33cc33"}]
<div id='calendar'></div>
OTHER CALENDAR SCRIPT:
<script>
$(document).ready(function() {
var user_id = $('#current_user').val();
$('#calendar').fullCalendar({
displayEventTime: false,
events: [
<?php foreach($result as $r) { ?>
{
<?php $title = get_the_title($r['event_id']); ?>
<?php $url = get_permalink($r['event_id']); ?>
title: '<?php echo html_entity_decode($title); ?>',
start: '<?php echo $r['start_date'] ?>',
end: '<?php echo $r['end_date']." 23:59:59" ?>',
url: '<?php echo $url; ?>',
color: '#33cc33'
},
<?php } ?>
]
});
});
</script>
This should be more like what you need:
1) When you first set up your calendar, define your extra "user" and "category" data parameters dynamically (using a callback function).
2) Inside your category "change" event, all you need to do now is simply tell the calendar to refetch the events. There is no need to completely re-initialise the calendar, as you have been doing.
I can't see all of the code, including where you first initialise the calendar, so this may not be 100% accurate, but this is the general idea:
$(document).ready(function() {
$('#calendar').fullCalendar({
events: {
url: '<?php echo get_site_url(); ?>/get_calcat_calendar.php',
data: function() { //using a callback function here allows fullCalendar to fetch the latest values of these parameters every time it makes a new request to the server, rather than them being supplied statically at initialisation
return {
id: $('#ccategory').val(),
user: $('#current_user').val()
};
},
error: function() {
alert('There was an error while fetching events.');
}
}
});
$('#ccategory').change(function() {
//just tell the calendar re-fetch the events. It will automatically get the latest category ID value and send it to the server as a parameter
$("#calendar").fullCalendar("refetchEvents");
});
});
This is based on the pattern shown in the "Dynamic data parameter" section in the documentation at https://fullcalendar.io/docs/event_data/events_json_feed/
Can some help me to solve this problem
I have a map on my website and i want to refresh map only on clicking on category my this is my product
<?php
/* $message = "in home";
echo "<script type='text/javascript'>alert('$message');</script>";*/
foreach($categories as $category){
echo '<li><img src="'.base_url('uploads/'.$category->image).'" alt="'.$category->cat_name.'" width="30" height="30"/></br><span>'.$category->cat_name.'</span></li>';
}
?>
</ul>
</div>
</div>
<script>
function changeData(category){
var urlCI = '.base_url('main/home/' .$category->adv_category).';
$.ajax({
type: "POST",
url: urlCI,
data:{'categoryReq':category},
success: function(response) {
if(response!=''){
$('map_marker').html(response);
}else{
return false;
}
}
});
}
</script>
my controller code is if you need other code please ask i will give. I give this just for refrence, thank you
public function home($cat=NULL)
{
//$cat=10;
//echo debug_backtrace()[1]['function'];
if($_POST)
{
print_result($_POST);
}
$sql="SELECT * FROM (`ad_category`) WHERE `status`=1 AND `del_status`=0";
$this->data['categories']=$this->db->query($sql)->result();
if($cat)
{
//$message = $cat;
//echo "<script type='text/javascript'>alert('$message');</script>";
//$this->data['middle_view']='home_again';
$this->data['ads']=$this->advt_m->get_advts($cat);
$this->input->post('map_marker',$this->data);
$this->data['subview']='home';
$this->load->view('__layout_main',$this->data);
}
else
{
/*$message = "Here 2";
echo "<script type='text/javascript'>alert('$message');</script>";
*/
$this->data['subview']='home';
//$this->data['middle_view']='home';
$this->data['ads']=NULL;
$this->load->view('__layout_main',$this->data);
}
var urlCI = '.base_url('main/home/' .$category->adv_category).';
probably should be
var urlCI = '<?php echo base_url("main/home/$category->adv_category"); ?>';
Split the Map div and its javascripts into another view.
Create function with all necessary functionalities for map. Add and load the it through Ajax call.
Ajax success:
success:function(response){
$('div').html(response);
//response will be the function which holds the $this->load->view('map');
}
map.php
<div id="map">
YOUR MAP GOES HERE
</div>
<script>
MAP SCRIPT
</script>
main.php (Your frontend)
<div id="map_here">
</div>
<script>
$.ajax({
type:"POST",
//Send some values
data:{
somevalue:'somedata',
category:"mine"
},
url:"<?php echo base_url();?>mycontroller/mapfunc",
success:function(response){
$('#map_here').html(response);
}
})
</script>
myconroller:
function mapfunc(){
//Using this value you can change the script
$data['category'] = $_POST('category');
$data['location'] = $_POST('somevalue');
//Process the works
$this->load->view('map',$data);
//On Ajax call this page can be loaded
}
Each ajax call it will reload the div.
any doubts just comment it...
I am working with SugarCRM API for get_module_fieldsand displaying its results in Checkbox You can check here . I have saved some checkbox value in database using AngularJS checklist-model and now I want to update it.So for that I want to display saved checkbox as checked but I unable to do that.Is any one can tell me how to do that?
here is my script code and i dont know what to write in $scope.users.mod_fields so that i can display checked checkbox
<script>
var app = angular.module("myApp", ["checklist-model"]);
app.controller('myCtrl', function($scope,$http) {
$scope.users = {};
$scope.users.mod_name = '<?php echo $module_name;?>';
$scope.users.mod_id = '<?php echo $module_id;?>';
$scope.users.mod_fields ='';
$scope.updateModule=function(){
$http.post("update_modulelist.php", {'mod_id':$scope.users.mod_id,'mod_name':$scope.users.mod_name, 'mod_fields' : $scope.users.mod_fields})
.success(function(data,status,headers,config){
alert(JSON.stringify(data));
//alert("Data Inserted Successfully");
window.location.href="show_modulelist.php";
});
}
});
</script>
You haven't put the HTML code, but to update this, you actually need to modify the checklistModel, not ngChecked or ngModel.
Done like this & got perfect answer:
var app = angular.module("myApp", ["checklist-model"]);
app.controller('myCtrl', function($scope,$http) {
$scope.users = {
mod_fields: '<?php foreach ($items as $key=>$val) { echo $val.',';}?>'
};
$scope.users.mod_name = '<?php echo $module_name;?>';
$scope.users.mod_id = '<?php echo $module_id;?>';
$scope.users.mod_fields = <?php
$module_fields = $_GET['fields'];
$module_fie =explode(',',$module_fields);
json_encode($module_fie);
echo json_encode($module_fie) ?>;
$scope.updateModule=function(users){
$http.post("update_modulelist.php", {'mod_id':$scope.users.mod_id,'mod_name':$scope.users.mod_name, 'mod_fields' : $scope.users.mod_fields})
.success(function(data,status,headers,config){
window.location.href="show_modulelist.php";
});
}
});
I am submitting form data via Ajax and would like to display a message above the form on successful submit.
Currently the form does send the data successfully. It should render the feedback message on form submit <?php $this->renderFeedbackMessages(); ?> as defined in my config.php
Where am I going wrong? Possibly doing things in the wrong order due to first time working with mvc?
my config.php file I have the following defined;
define("FEEDBACK_BOOK_ADD_SUCCESSFUL", "Book add successful.");
my model;
public function addIsbn($isbn)
{
// insert query here
$count = $query->rowCount();
if ($count == 1) {
$_SESSION["feedback_positive"][] = FEEDBACK_BOOK_ADD_SUCCESSFUL;
return true;
} else {
$_SESSION["feedback_negative"][] = FEEDBACK_NOTE_CREATION_FAILED;
}
// default return
return false;
}
my controller;
function addIsbn()
{
// $_POST info here
header('location: ' . URL . 'admin/searchIsbn');
}
my searchIsbn.php;
<?php $this->renderFeedbackMessages(); ?>
<div>
//my html form here
</div>
<div id="result"></div>
<script>
$('#form').submit(function() {
event.preventDefault();
var isbn = $('#isbn_search').val();
var url='https://www.googleapis.com/books/v1/volumes?q=isbn:'+isbn;
$.getJSON(url,function(data){
$.each(data.items, function(entryIndex, entry){
$('#result').html('');
var html = '<div class="result">';
html += '<h3>' + entry.volumeInfo.isbn + '</h3>';
html += '<hr><button type="button" id="add" name="add">add to library</button></div>';
$(html).hide().appendTo('#result').fadeIn(1000);
$('#add').click(function(ev) {
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>admin/addIsbn',
data: {
'isbn' : isbn
}
});
});
});
});
});
</script>
No console error messages.
You are redirecting here:
header('location: ' . URL . 'admin/addIsbn');
remove it.
echo the success message here and add it to an HTML element's .html() API.
Your page will not be refreshed.
Your page is making the call to admin/addIsbn which is redirected to admin/searchIsbn. So you already have the output of renderFeedbackMessages() being sent to your function.
Use the success callback to output the results to the page:
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>admin/addIsbn',
data: {
'isbn' : isbn
},
success: function(data) {
$('#result').html(data);
}
});
The only way I could get this to work was to add an auto-refresh to my Ajax success function as follows;
window.location.reload(true);
Working however open to suggestions.
I have a dynamic login header. 2 links, login / register and profile / logout.
I have a php class function that was being used to check if logged in and displaying relevant links, it worked fine.
I then moved to an ajax login as I didn't want a page refresh and the login box drops down and rolls back up. Again, it works fine.
I've noticed a slight issue, by slight I mean very irritating :)
Once logged in, Every single page refresh on new page shows a flicker where 'profile' becomes 'login' and then flickers back again. It only happens when the page is loading and doesn't last long but it's not very nice.
Could someone help me solve it please? I'm pretty new to Ajax/jQuery and spent ages wiht the help of some guys in here getting the ajax/jquery part functional in the first place.
this is script that toggles the login divs
<script>
window.onload = function(){
$(function() {
var loggedIn = <?php echo json_encode($general->loggedIn()); ?>;
$("#loggedIn").toggle(loggedIn);
$("#loggedOut").toggle(!loggedIn);
});
}
</script>
Thanks
EDIT: Ajax
function validLogin(){
$('#error').hide();
var username = $('#username').val();
var password = $('#password').val();
if(username == ""){
$('input#username').focus();
return false;
}
if(password == ""){
$('input#password').focus();
return false;
}
var params = {username: username, password: password};
var url = "../loginProcessAjax.php";
$("#statusLogin").show();
$.ajax({
type: 'POST',
url: url,
data: params,
dataType: 'json',
beforeSend: function() {
document.getElementById("statusLogin").innerHTML= '<img src="../images/loginLoading.gif" /> checking...' ;
},
success: function(data) {
$("#statusLogin").hide();
if(data.success == true){
$('#loggedIn').show();
$('#loginContent').slideToggle();
$('#loggedOut').hide();
}else{
// alert("data.message... " + data.message);//undefined
$("#error").show().html(data.message);
}
},
error: function( error ) {
console.log(error);
}
});
}
Use PHP to hide the unwanted element by doing the following
<?php
$loggedIn = $general->loggedIn();
?>
... Some HTML
<div>
<div id="loggedIn" <?php echo ( $loggedIn ? '' : 'style="display: none;"' ); ?>>
.... Logged in stuff
</div>
<div id="loggedOut" <?php echo ( !$loggedIn ? '' : 'style="display: none;"' ); ?>>
.... Logged Out Stuff
</div>
</div>
<script>
var loggedIn = <?php echo json_encode($loggedIn); ?>;
$('#loginForm').submit(function() {
... Handle form submit
... When ajax returns true or false we can set loggedIn and then toggle the containers
});
</script>
// CSS-Stylesheet
#loggedIn,
#loggedOut {display: none}
<script>
$(document).ready(function() {
var loggedIn = <?php echo json_encode($general->loggedIn()); ?>;
if (loggedIn == true) { // i can just guess here...
$("#loggedIn").show();
}
else {
$("#loggedOut").show();
}
});
</script>
Three possible solutions:
If the script element is placed inside the body, move
it to head element.
Use the following script instead:
$(document).ready(function () {
'use strict';
var loggedIn = <?php echo json_encode($general->loggedIn()); ?>;
$('#loggedIn').toggle(loggedIn);
$('#loggedOut').toggle(!loggedIn);
});
Hide both links in the "logged in" div using $('#loggedIn
a).hide(); and then, show them on the window.onload event using
$('#loggedIn a).show();. A bit dirty, bit it may work.