I am currently trying to output a number of records through pages. However I am already kinda failing at the beginning...
The <table> with all the records gets updated through ajax. However the problem I have is that whenever I click on the link which should update the part.php?page=1 it doesn't do anything.
file part.php
function activateEMode(aa){
//update all val etc
loadDoc("partB.php?page=1"+val+"&person="+person+"&status="+status+"&s_priortiy="+val1+"&s_uDate="+val2+"&s_fDate="+val3+"&search="+search+"&aa="+aa+"&q="+val, partiB);
}
file partB.php
$page = $_GET['page'];
for ($i=1;$i<5;$i++){
echo '<a href=part.php?page='.$i.'>'.$i.'</a>';
}
echo $page;
So what I am trying to achieve is that, when ajax function loadDoc is called it should set the ?page to the <a> pressed. Would be nice if you could help me :).
You can use window.location.replace to jump to a new link.
It will be like this:
var currnet_Location = windows.location;
var current_Location = current_Location.substring(0, current_Location.indexOf("page="));
var location_to_jump = current_Location+"New Location";
window.location.replace(location_to_jump);
Good Luck :)
Related
I am writing a page update which works with PHP to read a SQL database the page echo's the contents in a div section 'track_data'. yet it doesn't do this update idk
I have JavaScript script which I dont really fully understand and hopeful someone could explain its principally the check response section I think is failing ? :
in my PHP page :
<script type="text/javascript">
function InitReload() {
new Ajax.PeriodicalUpdater('track_data', 'fetch_sql.php', {
method: 'get', frequency: 60, decay: 1});
}
</script>
Thanks for looking and hopefully someone undersstands this and can put a smile on my face for the second time today :)
Steps to fix
Thanks for the suggestions of syntax errors. I haven't really got very far with this here are the changes you suggested which I have changed but I still think there is something wrong with last function as it doesn't update div section.
Code in JS file
// Start Clock refresh
// uses new new Ajax.PeriodicalUpdater(
// in main fetch file to trigger the auto update of the page.
// Written by Denise Rose
var gUpdateDiv;
var gContentURL;
var gcheckInterval;
var gcheckURL = "";
var gCurrentCheck ="";
_fetchUpdater('track_data','/fetch_sql.php','/fetch_sql.php',8000);
function _fetchUpdater(updateDiv,contentURL,checkURL,checkInterval)
{
gUpdateDiv = updateDiv;
gContentURL = contentURL;
gcheckInterval = checkInterval;
gcheckURL = checkURL;
setTimeout('check();',gCheckInterval);
}
//Called by _fetchUpdater every (n) seconds determins if content should be updated.
function check()
{
new Ajax.Request(gContentUrl,{method:'get', onSuccess:'checkResponse'});
setTimeout('check();',gCheckInterval);
}
// looks for the response and determines if the div should be updated.
function checkResponse(transport)
{
var content = transport.response.Text;
if(gCurrentCheck != content) {
gCurrentCheck = content;
new Ajax.Request(gContentUrl, {method: 'get',onSuccess:function t() {
$(gUpdateDiv).innerHTML = t.responseText; /*t.response.json()*/}
});
}
}
This is the bit I dont understand
function checkResponse(transport)
{
var content = transport.response.Text;
if(gCurrentCheck != content) {
gCurrentCheck = content;
new Ajax.Request(gContentUrl, {method: 'get',onSuccess:function t() {
$(gUpdateDiv).innerHTML = t.response.json();/*t.responseText;*/}
});
}
}
Method and Issues
What is transport here and what is t? if it stores the contents of the body text from the second in gCurrentCheck and compares to transport version content then why doesn't it update if its different please which it is if the SQL has created a different page?
I did find this https://api.jquery.com/jquery.ajaxtransport/
First Answer not using Ajax
I was given a neat and JS version as an answer, which is not really what I was looking for. I was hopeful to get the one working with one with Ajax but I appreciate your efforts is very kind. I just really wanted to send a refresh to the div area so that the PHP rebuilt the page from the SQL.
I might have been missing the MIT javascript http://www.prototypejs.org/ lol but I dont think it was.
Just to help:
AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files. ... Make requests to the server without reloading the page.
Researching
I found this Update div with the result of an Ajax-call but it did not really explain as the OP was using PHP like me not HTML. The answer was given:
$.ajax({
url: 'http://dowmian.com/xs1/getcam.php',
type: 'GET',
data: {id: <?php echo $cam_id; ?>},
success: function(responseText){
$('#update-div').html(responseText);
},
error: function(responseText){
}
});
I dont think above it answered posters question or mine as ajax is a server based push how is this relevant? as if its PHP driven the needs a refresh at server to refresh the contents not to provide new html. It is this refresh I am not interested in to re-copy PHP code elsewhere in JS as its already in my PHP. Does that make more sense?
Update
I did find a bracket missing and a set of single quotes inserted by editor. Which I have updated above but there was no significant change.
Cheers Nicolas . I am still hopeful that someone knows about Ajax as it sits underneath these technologies. I have a server side PHP file that I was hoping to use AJAX to pull just the PHP from the section it was pointing to an gUpdateDiv . As its derived from the server and created on the fly from SQL. I dont see how your answer would help push this data back in to the from the server . The $(gUpdateDiv).innerHTML was supposed to be acted upon not the whole page . What I am unsure of is how a trigger from this can update timer just this $(gUpdateDiv).innerHTML . I am also not aware if a server based refresh would do this or if the transport id provided from the file would be able to deliver just that . I think I am missing something a vital part that I dont have or have grasped yet. The reason there is two timers is effectively it checks the same file at a different point in time as its created by PHP it might be different from the first if it is i.e. the SQL data has changed, I want this to update this $(gUpdateDiv).innerHTML with the data which it compared it to the second 'Get' in the second request. It sounds, simple in practice but have got stuck comparing two versions and insuring second version gets used .
Further update placing an alert in the Javascript file did not pop up like it does here https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert however the same alert in the initiating PHP worked fine and created the alert. called the same function from the main PHP nd the alert occurred so the JavaScript is running next visit F12 on the page to see if there is any warnings or errors. Ok after adding JQuery which I thought I had added this started working however It is not doing what i Expected it to do. As the contained both text and graphics created by PHP I expected this all to be updated The graphics are not the text is any ideas? .
Further to the image problems I placed an extra line to update the image however I used this too in PHP
<script type="text/javascript">
//initpage() ;
function updateArtworkDisplay() {
document.querySelector('#np_track_artwork').src = 'images/nowplaying_artwork_2.png?' + new Date().getTime();
}
</Script>
But it didnt work to update the image in php?
<div id='outer_img'><img id='#np_track_artwork' src='/images/nowplaying_artwork_2.png' alt='Playing track artwork' width='200' height='200'></div>
in js change
/ looks for the response and determines if the div should be updated.
function checkResponse(transport)
{
var content = transport.response.Text;
if(gCurrentCheck != content) {
gCurrentCheck = content;
new Ajax.Request(gContentUrl, {method: 'get',onSuccess:function t() {
$(gUpdateDiv).innerHTML = t.responseText; /*t.response.json()*/}
});
updateArtworkDisplay(); // fire up the redraw in php file.
}
}
Nearly there it does almost what it needs to apart from the redraw which is not happening
// Start Clock refresh
// uses new new Ajax.PeriodicalUpdater(
// in main fetch file to trigger the auto update of the page.
// Written by Denise Rose
var gUpdateDiv="";
var gContentURL="";
var gcheckInterval=0;
var gcheckURL = "";
var gCurrentCheck ="";
_fetchUpdater('track_data','/fetch_sql.php','/fetch_sql.php',8000);
function _fetchUpdater(updateDiv,contentURL,checkURL,checkInterval)
{
gUpdateDiv = updateDiv;
gContentURL = contentURL;
gcheckInterval = checkInterval;
gCheckURL = checkURL;
setTimeout('check();',gcheckInterval);
}
//Called by _fetchUpdater every (n) seconds determins if content should be updated.
function check()
{
new Ajax.Request(gCheckURL,{method:'get', onSuccess:'CheckResponse()'});
setTimeout('check();',gcheckInterval);
}
// looks for the response and determines if the div should be updated.
function checkResponse(transport)
{
var content = transport.response.Text;
if(gCurrentCheck != content) {
gCurrentCheck = content;
new Ajax.Request(gContentUrl, {method: 'get',onSuccess:function t() {
$(gUpdateDiv).innerHTML = t.responseText; /*t.response.json()*/}
});
$time = new Date().getTime();
new Ajax.Request('outer_img', {method: 'get',onSuccess:function s() {
$('outer_img').innerHTML = "<img id='#np_track_artwork' src='/images/nowplaying_artwork_2.png?t='"+$time+" alt='Playing track artwork' width='200' height='200'>"}
});
}
}
GIVEN UP WITH THIS PLEASE DELETE MY PERSONAL INFORMATION AND POSTSript-fetch-async-await/
I use the following buttons in my view file (don't pay attention to second one, but I just wanted to show you why I'm not using a normal form submit):
<?php echo CHtml::Button('Search Symptom(s)', array('id'=>'search')); ?>
<?php echo CHtml::Button('Add Another Symptom to Search', array('id'=>'addSymptom')); ?>
When the user clicks the buttons this javascript runs (it's inside a document.ready function)
$('#search').click(function()
{
//create new symptom in javascript
var newSymptom =
{
symptomCode: $('#symptomToBeSearchedCode').val(),
dateSymptomFirstSeen: $('#dateSymptomSeen').val(),
symptomTitle: $('#symptomToBeSearchedTitle').val()
};
//pass new symptom into symptomsList array
symptomsList.push(newSymptom);
//make ajax call to server
$.ajax({
type:'POST',
url: '/mysymptomsbook/index.php?r=symptomhistory/search',
data:{symptomsList: symptomsList} ,
dataType:'html'
});
});
symptomsList is an array with JS objects
This is the code in my controller action:
if(isset($_POST['symptomsList']))
{
foreach($_POST['symptomsList'] as $symptom)
{
//populate symptom search model attributes with user id, current date, and form input
$newSymptom = new Symptomhistory;
$newSymptom->setAttributes(array(
'user_id'=>Yii::app()->user->id,
'dateSearched'=>date('Y-m-d'),
'symptomCode'=>$symptom['symptomCode'],
'dateSymptomFirstSeen'=>$symptom['dateSymptomFirstSeen'],
'symptomTitle'=>$symptom['symptomTitle'],
));
//save search history
$newSymptom->save();
//add into the searched for symptoms code the latest code
array_push($symptomCodes, strval($symptom['symptomCode']));
}
$this->redirect(array('disease/index'));
}
I was planning on using redirect to send the $symptomCodes array to the other controlleraction (DiseasesController and actionIndex), but even without passing anything the redirect doesn't work. The models get saved to my database normally.
Anyone have any idea what is wrong? I'm thinking it has to do with Ajax since it's waiting for a response, but I want my controller to redirect instead. Any help as always, is greatly appreciated :)
I had similar problem, recommend you to look at this topic at official forum:
redirect not working when called via Ajax-Request
See the last answer in topic.
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);
});
});
});
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.
On my website its quite important to show products names on Order history (my_account/order_history), while in opencart there is only shown order id. I have partly solved the problem however I would very appreciate some hints how to proceed.
The topic was once opened in 2011 in http://forum.opencart.com/viewtopic.php?f=20&t=46387&p=437991#p437991
The main problem is that the file order_list.tpl doesnt have access to $product['name'] in controller order.php (where its defined in function info() instead of function index()), only order_info.tpl have. I tried to copy the parts of the code from the function info() to the function index() but it still didnt have access there. Any hint what I have to do ? Do i need to change something in model file ? or how to modify controller file (order.php) to allow order_list.tpl to have the right access ?
One approach I have tried is rendering the content order_info using javascript on the order_list.tpl in new div (as described in http://goo.gl/nMXhEu ) however as a newbie in js I coudlnt modify it to open right after page-load (not on moveover). I have tried to change mouseover to load, beforeload a few other without any success..
$("body").on("mouseover", function(e){
$(".order-info").load(e.target.href, function(){
$(e.target).addClass("unloaded");
});
});
Any help or hint how to proceed would be very appreciated
$(function () {
$(".order-info a").each(function () {
var $me = $(this);
$me.load($me.attr('href'),function(){
$me.addClass("unloaded");
};
});
thanks for help cske, I really appreciate it. However I still could not make it work. I also tried to make some small adjustments, without any success (but then I am not js developer).
So I decided to try once again to modify the controller file, to make $product['name'] accessible to order_list.tpl (as described in the question). I was able to do so by adding
$products = $this->model_account_order->getOrderProducts($result['order_id']);
and
foreach ($products as $product) {
$this->data['products'][] = array('name'=> $product['name'],);
}
after
foreach ($results as $result) {
which makes possible to call it in orders array for example
$this->data['orders'][] = array(
'product_name' => $product['name'],
It is working solution however:
1. it shows only one product per order
2. it throws notice
Notice: Undefined index: order_id
The notice can be turned off in Admin area.
I am Ok with this solution, but obviously it might not be the right solution for other shops.
I used the solution that only shows the first product for the order to figure out how to show all products for the order and their quantities.
Instead of:
foreach ($products as $product) {
$this->data['products'][] = array('name'=> $product['name'],);
}
use:
$this->data['products'] = array();
$prod = "";
foreach ($products as $product) {
$prod .= $product['quantity'] . " x " . $product['name'] .'<br>';
}
and in:
$this->data['orders'][] = array(
add:
'product_data' => $prod,
then in order_list.tpl you can get the product list with quantities with:
<?php echo $order['product_data']; ?>