THIS PROBLEM IS NOW SOLVED. THANK YOU TO EVERYONE WHO REPLIED.
Hello,
I am trying to solve a problem that I may have approached from the wrong direction, so maybe someone could suggest a better solution.
I am writing a little web app for work, that has a search function. When user submits a search string, form gets posted to a CodeIgniter controller. If search returns a result, CodeIgniter loads a page with results. If there is no results, user's current page just gets reloaded, without any indication that search returned no results. So, this is not user friendly at all and i decided to re-do that with some help from $.ajax().
That was rather easy, but now I am stuck trying to figure out what to do with the data i receive back, if search is successful.
I know $.load() can replace a part of the page, but i need to redirect the user to a completely different page, while POSTing the data
my ajax search just returned. The data that comes back from PHP is in json_encode() format.
NOTE: $.jGrowl() is a jQuery plugin that displays a Growl-like message.
$("#alias_s").submit(function() {
event.preventDefault();
var term = $('input#alias_search').val();
$.post("<?=base_url()?>aliases/searchAliases", {
searchTerm: term },
function(data) {
if(!data) {
$.jGrowl("Search for '" + term + "' returned no results", { life: 5000 });;
} else {
//
// How do i post this data to another page and redirect a user there?
//
}
});
UPDATE: I managed to find a work-around to this issue.
I take the data that was returned from $.post() and use $.load() to POST it back to the same controller, that in turn takes the data and loads correct view files. The only downside is that URL it still the same, which breaks couple of small things, but I can deal with that...
$('#content').load("<?=base_url()?>aliases", { searchData: data});
UPDATE #2: I finally made it work like i wanted. What i did, is take the data that was returned from PHP in JSON format, post it back to the same controller, and let CodeIgniter take care of loading views, this way all my URL dependent stuff works too.
$('<form action="CONTROLLER" method="post"><input type="hidden" id="searchData" name="searchData" value='+data+'></form>').appendTo($("body")).submit();
There were 2 caveats though.
appendTo($("body")) was needed to make it the form submit correctly in Firefox.
POST was cutting off my JSON string after first space, so i had to use str_replace() in php do fix that.
echo str_replace(' ', '%20', json_encode($search_results));
THIS PROBLEM IS NOW SOLVED. THANK YOU TO EVERYONE WHO REPLIED.
I am writing a little web app for work, that has a search function. When user submits a search string, form gets posted to a CodeIgniter controller. If search returns a result, CodeIgniter loads a page with results. If there is no results, user's current page just gets reloaded, without any indication that search returned no results.
I think you should just fix that bad behavior, and have the "Search" action return the page with some error information. Using AJAX doesn't really do you any good if you want to completely reload the page anyway.
If you want redirect the user another page, why do you stop the execution a form in a javascript?
Maybe this work, but i not tested.
$("#alias_s").submit(function() {
var term = $('input#alias_search').val();
$.post("<?=base_url()?>aliases/searchAliases", {
searchTerm: term },
function(data) {
if(!data) {
$.jGrowl("Search for '" + term + "' returned no results", { life: 5000 });;
return false;
} else {
//
//
//
}
});
This has been solved. Solution is in my original post.
Related
I got a problem and I´m about to hurt the MVC-paradigm, so I rather ask you what to do.
I got a page which is refreshed every 10 seconds with jQuery .post()-method.
setInterval(function() {
$.post("http://XYZ.de<?php echo $this->webroot."Posts/index"; ?>", { liveUpdate: "true" },
function(response) {
$('#loadingContent').html(response);
}
);
}, 10000);
now, where the "Posts/index" is placed I have to call the PostsController.php of Cake which allows me to reset the variables.
But it doesn´t work that way and the response is filled with all the html of a normal page-call but I only want to have the pure PHP-variables updated without html appended to that div.
What am I doing wrong?
Thanks in advance for your patience.
Since your array is complex multilevel and you do not want to parse JSON, the only way I see doing it would be using jQuery load().
setInterval(function() {
jQuery("#RefreshMeOnPage")
.load("http://XYZ.de<?php echo $this->webroot."Posts/index"; ?> #RefreshMeInResults > *", {liveUpdate: "true"});
}, 10000);
It will make post request to server and replace contents of existing element with id RefreshMeOnPage with the contents of newly received element with id RefreshMeInResults. Docs http://api.jquery.com/load/.
NOTE: Still with refresh rate of 10 seconds, I think you should look into ajax comet solution http://cometdaily.com/maturity.html. It will receive data only when there is change, although it requires some configuration.
I am using php and an apache server. My application gathers data from the user, put's it in a database, then uses PDFLib to display the formatted data back to the user as a pdf. My problem is, I would like the pdf to display as a new page, this works. But, I also have a blank page left up with the URL containing the variables used to display the pdf. I would like this page to show a different summary page, in HTML, without the variables in the URL, but I don't know how to do that. In the code that follows, I am going to the summary page if the medical flag is false. What I would like is to go to BOTH pages if the medical flag is true. Is this possible?
if($medical_flag) {
header("Location: {$_SERVER['PHP_SELF']}/./index.php?step=wc_pdf&id={$event_id}");
} else {
header("Location: {$_SERVER['PHP_SELF']}?step=success&id={$event_id}");
}
exit;
OK, I understand how this is impossible, but I still haven't figured out how to solve the problem. I thought I could toss the opening of the PDF back at jQuery with something like this:
jQuery(document).ready(function ()
{
function display_pdf_page(data, textStatus) {
var current_record = data || {};
//somehow display the pdf now
}
function show_pdf(eventid){
jQuery.getJSON(
'./inc/get_current_record_data_json.php',
{'id': eventid},
display_pdf_page
);
}
...
});
Then after I process the data in php "call" the above using:
echo '<script type="text/javascript">'
, 'show_pdf($event_id);'
, '</script>';
But that doesn't work either, php doesn't know where to find show_pdf. My lack of understanding of client/server side events is killing me here. Call be obtuse... I don't get it.
This solution will not work as designed.
First, if you want to hide the data, you should switch to POST rather than GET. This way, the data is included in the HTTP payload instead of the URI.
Secondly, you should either include a hidden iframe for javascript to access the page for which generate the PDF. On successful execution of the AJAX call (or whatever method you use), you can then redirect the page to your desired destination.
As suggested by sixeightzero, POST should be used instead of GET in such cases.
However, maybe you could accomplish the desired effect with a big iframe spaning the window (100% width and height)?
Ok guys I know this question has been asked before but I am very new to PHP and JavaScript and hadn't even heard of ajax until i started looking for an answer to this question so do not understand previous answers.
I am creating a site that essentially is a bunch of videos in a SQL database, it shows one video at a time, I would like to have a next and previous video buttons.
However I cant get past this ajax thing so my question is even simpler. I have looked at this question/answer and think it pretty much sums up what im asking:
How do I run PHP code when a user clicks on a link?
I have copied that exact code,
<script type="text/javascript">
function doSomething() {
$.get("backend.php");
return false;
}
</script>
Click Me!
And in my backend.php file i have literally just got <?php echo "Hello" ?> just to test it and therefore my understanding is that when i click the link the javascript onClick event is trigged which in turn calls the backend.php file, which says to print "Hello" to the page. However when i click the link it does nothing.
Eventually obviously im going to need to get a lot more complex with my php functions and calling variables and all that stuff but i like to figure things out for myself for the most part so i learn. However im stuck on this bit. Also whilst im here i will ask another thing, I want to 'give back' to the users of the site for answering my questions but I can only really well enough in HTML and CSS to answer other peoples questions, any advice on being able to find the simpler questions on here so i can answer some.
Thanks in advance :)
It does nothing becuase you don't do anything with the result. My guess is that in the example you took, it does some work and doesn't show anything to the user. So if you just had some stuff you wanted to run on the server without returning any output to the user, you could simply do that, and it would work.
Example from jQuery's .get() documentation
What you do:
Example: Request the test.php page, but ignore the return results.
$.get("test.php");
What you want to do:
Example: Alert out the results from requesting test.php (HTML or XML, depending on what was returned).
$.get("test.php", function(data){
alert("Data Loaded: " + data);
});
Take a look at the .get() documentation. You're using it incorrectly.
You should be passing data (optional) and handling the data that gets returned, at a minimum:
$.get("backend.php",
{
// data passed to backend.php goes here in
//
// name: value
//
// format. OR you can leave it blank.
}, function(data) {
// data is the return value of backend.php
// process data here
}
);
If you pass data, you can retrieve it on backend.php using $_GET. In this case:
$_GET['name'];
$.get("test.php", { name: "John", time: "2pm" }, function(data) {
alert("Data Loaded: " + data);
});
http://api.jquery.com/jQuery.get/
This would alert the data. right now that function only returns false.
$.get('backend.php', function(data) {
alert(data);
});
Your code will not print to the page the way you have it set up; you're part of the way there, in that you have called the page, but the response needs to be handled somehow. If you open up the developer tools in Chrome, you can click on the Network tab and see the request and response to verify that what you coded is actually working, but now you need to put the response somewhere.
By passing a function as the second variable into $.get, you can make your request show up on the page. Try something like this:
$.get("backend.php", function (data) { $('body').append(data); } );
Your code is not handling with that data. So instead, you should use following code :
$.get("backend.php", function(response) {
alert(response);
})
Or, to show that data on UI, assign it to any html element.
For more understanding , please visit :jQuery.get() link
i am trying from my main web page to check and in some cases send a variable via URL like this (http://192.168.0.110/CVAL.CGI?A0=1) this is to modify the status of something in my web page depending on the value seen in the url.
Sounds like you need Ajax.
There are many javascript libraries that can help you with this functionality such as jQuery, Prototype, or one of the many found on this page.
Hope that is what you are looking for and is helpful. Next time post more specific details so we can answer your question correctly the first time. Specific, detailed examples of what you want to do are also helpful.
UPDATED:
Here is an example using the Prototype Javascript library given your example form:
new Ajax.Request('/CVAL.CGI?A0=1', {
method: 'get',
parameters: { anotherValue: 'something' },
onSuccess: function(transport) {
alert(transport.responseText); // this is what the server returned
}
});
This would result in a request to /CVAL.CGI?A0=1&anotherValue=something. Whatever CVAL.CGI returns in response to that request, is available from transport.responseText.
This way, the user never has to leave the page or submit a form but it is all done behind the scenes. Your parameters can be any values you want to send which you can grab from form fields or other user input. You can return responses in JSON to make accessing the return data easier as well. Change method from 'get' to 'post' to do post requests.
In my continued effort to understand hash tags and page navigation I'm hitting a road block with resubmitting form data if a user uses the browsers navigation buttons (e.g. back and forward).
My function that uses the form data is below:
if(page == "/visits_results") {
$('#start').val(start);
$.post("visits_results.php", $("#profile_form_id").serialize(),
function(data) {
$('#search_results').html(data);
location.href = "#visits_results=" + start;
});
}
This works fine and dandy if the form is still visible, for instance if I use pagination it performs as I would expect.
My issue is when the user clicks the browsers back button (the form has now been removed) and then they click the browsers forward button. The event gets triggered but my serialized form data is now empty. Is there any way to cache the form data so I can continue to call it?
Any thoughts?
Your best bet (I think) would be to store the serialized data in a cookie. When the user returns to the page which he/she has already filled out, retrieve the data from the cookie, unserialize it, and place it back where it belongs.
Cookies are fairly trivial to work with, there is a decent cross-browser implementation for reading/writing cookies on quirksmode:
http://www.quirksmode.org/js/cookies.html
or if you'd prefer to use a plugin:
http://code.google.com/p/cookies/
http://plugins.jquery.com/project/Cookie
You can save data fairly easily using localStorage like http://jsfiddle.net/zDPjm/
Well, sure, you could do something very simple such as:
if ($("#profile_form_id").serialize() != "") serializedFormData = $("#profile_form_id").serialize();
$.post("visits_results.php", serializedFormData, /* Rest of Code */