i found a code fore an ajax tutorial,and am not familiar with some part of the code there
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "pay.php", true);
ajaxRequest.send(null);
can someone please tell me what the above code means,are there any variables,etc?
I am aware that pay.php is the php file it reffers to,but what does the first three line of coding mean?
The XMLHttpRequest object has a property called readyState. This is where the status of your server's response is stored. The response can be processing, downloading or completed. Each time the readyState changes then our onreadystatechange function executes.
When the property readyState is 4 that means the response is complete and you can get your data.
The function refers to a textbox named time,in a form named myform"The value is taken from the code in pay.php file.
Related
I identified an issue with postdata not being sent through AJAX on my server. To debug it, I wrote the following fairly minimalistic piece of javascript to test a simple AJAX call :
function my_custom_ajax(target_page, target_element , postdata_contents) {
// Sending the XMLHttpRequest as postdata
var xhr = new XMLHttpRequest();
xhr.open("POST", target_page, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
xhr.setRequestHeader("Content-length", postdata_contents.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(postdata_contents);
// Waiting for the request to return
xhr.onreadystatechange = return_data;
// If all went well, we update the target element
function return_data()
{
if(xhr.readyState === 4)
{
if(xhr.status === 200)
{
// We update the target element
document.getElementById(target_element).innerHTML = xhr.responseText;
}
// Throw error in case of 404 or such
else
document.getElementById(target_element).innerHTML = "XHR can't be loaded";
}
// Throw error in case request got interrupted or didn't work out
else
document.getElementById(target_element).innerHTML = "XHR error";
}
}
It is called with the following HTML :
<div onClick="my_custom_ajax('test_page.php?xhr','my_id','postdata_test');">
Click me
</div>
<div id="my_id">
xhr response will appear here
</div>
And calls a PHP page which contains only this :
exit(var_dump($_POST));
When running this piece of code in my Apache localhost or another Apache server I own, it does pass whatever is in postdata_contents as postdata. The exit(var_dump($_POST)); does show that it works properly, and does print the value of the postdata I passed to it.
However, when running this same piece of code on the Apache server where it does not work, all I get is « array(0) { } », as in, no postdata is passed according to the PHP file.
Here is Firefox's dev tool view of the request details (in french, sorry, but should be obvious what is what) :
The debug tool shows that the postdata contents are properly being sent :
However, the returned content show that the postdata was somehow not passed :
On my localhost and my other Apache server, everything is exactly the same until the very last step, where the postdata is properly passed (the var_dump message is styled but you can easily see the gist of it : postdata_test is part of $_POST) :
After hours of fiddling with the configuration of this Apache server and trying all of the debug methods and breakpoints I could think up, my nerves are too worked up to continue thinking about this rationally for now. As I have no option of using another server or just copypasting my local Apache configuration file on the new server, I defer this question to you all, hoping that somebody can figure it out or once encountered something similar.
Thanks in advance,
Eric B.
Solved it myself by accident, I had mod_dumpio activated on the server and it started working once I turned it off.
I do not know what mod_dumpio was doing to deny XHR POST but not generic HTTP POST, but at least that's solved.
Hope this will help someone else some day.
(on a sidenote, I realize the postdata query in my example was malformed, should have been « postdata_test= » instead of « postdata_test », so add that equal sign if you are stuck in my situation and want to run the same tests I did)
I was searching for a similar issue for a while now, but none of the solutions worked for me (and I couldn't find exactly the same issue).
First of all, the website I'm working on is running on Zend Framework. I suspect that it has something to do with the issue.
I want to make a pretty basic AJAX functionality, but for some reason my response always equals the html of the current page. I don't need any of Zend's functionality, the functions I need to implement could (and I'd prefer them to) work separately from the framework.
For testing purposes I made it as simple as I could and yet I fail to find the error. I have a page "test.php" which only has a link that triggers the ajax call. Here's how this call looks:
$('.quiz-link').click(function(e){
e.preventDefault();
$.ajax({
URL: "/quiz_api.php",
type: "POST",
cache: false,
data: {
'test': 'test'
},
success: function(resp){
console.log(resp);
},
error: function(resp){
console.log("Error: " + reps);
}
});
});
And this quiz_api.php is just:
<?php
echo "This is a test";
?>
When I click on the link I get the entire HTML of the current page. "This is a test" can't be found there. I'm also getting an error: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/."
I reckon it has to do with the JS files that are included into this HTML response, but I've also tried setting "async: true" and it didn't help.
I would like to avoid using Zend Framework functions for this task, because I'm not well familiar with it and even making a simple controller sounds rather painful. Instead I want to find out what's causing such behavior and see if it can be changed.
PS: I've also tried moving quiz_api.php to another domain, but it didn't change anything.
I know that it might be an older code but it works, simple and very adaptable. Here's what I came up with. Hope it works for you.
//Here is the html
Link Test
<div id="test_div"></div>
function test(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// This is the php file link
var url = "quiz_api.php";
// Attaches the variables to the url ie:var1=1&var2=2 etc...
var vars = '';
hr.open("POST", url, true);
//Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange =
function(){
if(hr.readyState == 4 && hr.status == 200){
var return_data = hr.responseText;
console.log(return_data);
document.getElementById('test_div').innerHTML = return_data;
}else{
document.getElementById('test_div').innerHTML = "XMLHttpRequest failed";
}
}
//Send the data to PHP now... and wait for response to update the login_error div
hr.send(vars); // Actually execute the request
}
you can change the whole page with a document.write instead of changing individual "div"s
I am developing application using Ajax and jsp.
My index.jsp page has HTML code for Login and some Ajax code in javascript. Ajax will call my another CheckLogin.jsp page
CheckLogin.jsp page checks on server for valid username and password. It returns "success" if it's valid otherwise will return message stating "username or password is not valid."
Now, when username and passwrod is valid, instead of success, I want to redirect the page to "Home.jsp" what should I do?
I am new to jsp. I appreciate your help on this.
JSP code gets run once on the server before it goes to the client, so JSP/JSTL cannot do a redirect following the success or otherwise of an AJAX call (without a full page refresh - which obviates the use of AJAX). You should to do the redirect with Javascript:
if (success) {
var successUrl = "Home.jsp"; // might be a good idea to return this URL in the successful AJAX call
window.location.href = successUrl;
}
On successful AJAX call/validation, the browser window will reload with the new URL (effectively a redirect).
Since I don't see your code, you can integrate this somewhere inside your validation :
<%
pageContext.forward("logged.jsp");
%>
function Edit() {
var allVals = $('#NEWFORMCampaignID').val();
if (allVals > 0) {
window.location = '/SMS/PrepareSMS?id='+allVals;
}
else
alert("Invalid campaign to Edit")
}
In order to redirect using Button click and pass some parameters, you can call the Controller Path(#RequestMapping(value="/SMS/PrepareSMS")) and then handle it there..
The variable xmlhttp=new XMLHttpRequest() is initialed. the following code :
function makerequest(serverPage,objID){
var obj=document.getElementById(objID);
xmlhttp.open("GET",serverPage);
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status ==200){
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
i am sorry i am a new learner of ajax, in the if condition, why it add xmlhttp.readyState == 4. at the function's end there is using xmlhttp.send(null); could i delete them. thank you.
Well, you want to send the ajax request that you generate, so since you're using get, null is an acceptable argument. If you use post, you should pass the querystring in the send method. More here.
If you delete the readyState condition then you could end up with the ajax returning nothing since the page would not yet be ready. See more here.
EDIT: Sample argument for POST send method:
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
This issue is very likely codeigniter specific.
I have a controller called redirect.php that redirects from and to views. This controller for the most part has one public _remap function that does all the redirecting with a case statement. Everything has been working great until I sent a $.POST from a view back to the controller. I want it to hit the _remap and look for the fact that the request is coming from AJAX then do it’s case.
I have a IS_AJAX constant I’m checking against.
define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
but whenever I hit the page it’s always remapping to the default and sending my request to that page where it’s basically returning me that pages data back when I’m echoing and alerting the data to and fro.
Any insights?
for reference,
redirect.php (there is more code to define variables and 2 more cases but it's not hitting those, it's hitting 'index' / default)
public function _remap($method)
{
switch ($method) {
case $method == 'index':
$this->load->view('main');
break;
case $method == 'IS_AJAX':
var_dump($_POST);
break;
default:
$this->load->view('main');
}
}
tweetview.php (view loaded by redirect controller in another case within redirect.php, json_tweets send is a JSON variable)
//jquery
$.post("http://localhost/2fb/index.php/redirect", {'json_tweets': json_tweets},
function(data) {
alert(data);
});
Instead of doing all this you can rely on $this->input->is_ajax_request() from http://codeigniter.com/user_guide/libraries/input.html. If you are not interested in loading a library, here is somewhat similar code I have in production for last two years at least.
$ajax = ($_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest')? true : false;
Look at the string, its XMLHttpRequest and the jQuery is the frontend JS toolkit
Just to add more, I usually have one entry point for Ajax calls, so obviously I have one controller for ajax and route all my calls through it. Why would I do that? Simple reason, I make sure all my forms submit to a simple non ajax form handler at server if JS is turned off. If JS is on, jQuery/prototype/YUI takes control and sends data to my ajax controller. The end handler which actually does all the validation/verification/db interaction is common code.
case $method == 'IS_AJAX':
Your $method is not IS_AJAX with this url:
http://localhost/2fb/index.php/redirect
This would bring you to the redirect controller without a method (will default to "index"). You literally would need:
http://localhost/2fb/index.php/redirect/IS_AJAX
...to step into that case. You seem to be confusing your constant IS_AJAX with the method requested, which you seem to be using correctly when checking for index (although this is the same as the default case, so it's redundant).
$method, or whatever you name the first parameter in _remap(), will always be the routed controller function that is called.
EDIT: I failed to mention this earlier, but the switch block evaluates the expression you pass to it, so there is no need to do the comparison manually. Example:
switch ($method) {
// case $method === 'index':
case 'index':
$this->load->view('main');
break;
}
try this ,
$.ajax({
type: "POST",
url: "your function url goes here",
data: data,
success: function(html){
window.location = 'redirect url goes here';
}
});