I'm having an issue that I can't seem to solve. First thing is first. I'm running this on Ubuntu 14.04 with apache and php5. I am using the netbeans IDE which i originally assumed to be the issue but then i ran it directly from the web root /var/www/html. php is working i already tested it. i can run html pages and php pages from the root. I have developed a few applications already using this computer. Some which use very advanced ajax to calls to google apis. I have no idea why all of a sudden I can't make the simplest ajax call. Anyways the problem is that when I make my ajax call to a php file nothing happens. if i inspect the page in browser, it shows that it pulled in a bunch of random iframes. I have never used an iframe before. I am really hoping that I just need a different set of eyes on this and that it isn't something else.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Index HTML</title>
<meta charset="UTF-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: "getHTML.php",
data: { "test": "testing"},
type: "GET",
dataType: "xml",
statusCode: {
0: function () {
alert("Thank You");
},
200: function (html) {
$("#page").append(html);
}
}
});
});
</script>
</head>
<body>
<div id="page">The Div</div>
</body>
</html>
getHTML.php
<?php
echo "Hello World";
?>
After running this in mozilla firefox, no iframes are being pulled in. I can only assume it is some bug with chrome. So now to answer the question: why aren't I getting any response from the ajax call?
So I am now getting a response from my ajax calls. Way worse though. I changes my $.ajax to a $.post() and then to a $.get() and now it is return a duplicate of index.html over and over and over in an infinite loop. From what i understand the default url that $.get/post take is the current url. But I added getHTML.php as the url argument. so I am at a loss. I can't get any work done if I can't solve this issue. Can anyone help?
$(document).ready(function(){
$.get("getHTML.php", function(data)
$("body").append(data);
});
});
Its best to use JSON for these requests:
$return_data = array();
if (condition){
$return_data['status'] = 'success';
} else {
$return_data['status'] = 'info';
}
echo json_encode($return_data);
exit();
Remember to specify return data type:
function send() {
var data = $('#signup_form').serialize();
$.ajax({
type: "POST",
url: "signup_process.php",
data: data,
dataType: 'json',
success: function (data) {
alert(data.status);
if (data.status == 'success') {
// everything went alright, submit
$('#signup_form').submit();
} else if (data.status == 'info')
{
console.log(data.status);
$("label#email_error").show();
return false;
}
}
});
return false;
};
Ok so the solution to this issue has nothing to do with any programming. For the iframes, this way a strange google chrome issue, luckily it doesn't affect the visuals as nothing displays. As far as the ajax problem, I was doing it right (tested on a different computer) but the Apache2 server was not responding to ajax requests. It is gonna take some time searching through log files to find a proper solution.
Related
I am a beginner in coding and am learning ajax but my code is not working can anyone tell me what is wrong in my code.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({url: "demo.txt", success: function(result){
$("#div1").html(result);
}});
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>
</body>
</html>
this is demo.txt
<h2>jQuery and AJAX is FUN!!!</h2>
<p id="p1">This is some text in a paragraph.</p>
this is my console error
enter image description here
This is how your URL can use ajax, because Ajax has cross domain restrictions
If you are using vscode editor, you can download the "live server" plug-in and right-click in HTML to open the web page
Pls follow the documentation provided at
jQuery.ajax() | jQuery API Documentation
It should work fine when you include in the same order.
Little information about Ajax. Why do we use ajax, Ajax is mostly used for sending data from Javascript to the Back-end server. Lets say if you want to get the user input from front-end and you want to store the data in your database. Ajax comes to help.
Example of a simple ajax function with passing user data (namely data1 and data2):
$.ajax({
type: "post",
data: {
user_data1 : data1,
user_data2 : data2,
},
url: YOUR_FUNCTION_PATH,
success: function(data){
// After success passing data to YOUR_FUNCTION
// Handle what you do next
},
error: function (request, status, error) {
// Error of passing data to YOUR_FUNCTION
// Debug to see what is wrong
}
});
Then in your YOUR_FUNCTION and if you sending data to PHP function,
$user_data1 = $_POST['user_data1'];
$user_data2 = $_POST['user_data2'];
If you are using the old one, CodeIgniter, it is pretty simple to get the data.
$user_data1 = $this->input->post('user_data1');
$user_data2 = $this->input->post('user_data2');
Your URL may need to start with localhost, for example: http://localhost :8080
I am trying to create a commenting system for my site. A script is used to show massages (or alert) when the comment is submitted. I don't have enough knowledge in js to debug and fix this problem myself so I though I would ask here till I learn more about js.
My script imports which are in the header:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" async></script>
<script type="text/javascript" src="/js/main.js" async></script>
And my main.js script:
// Static comments
jQuery(document).ready(function ($) {
var $comments = $('.js-comments');
$('#comment-form').submit(function () {
var form = this;
$(form).addClass('submitting');
$('#comment-form-submit').html('Loading ...');
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
contentType: 'application/x-www-form-urlencoded',
success: function (data) {
$('#comment-form-submit').html('Submitted');
$('.new-comment-form .js-notice').removeClass('notice--danger').addClass('notice--success');
showAlert('<p style="color:#47bd40">Thanks for your comment! It will show on the site once it has been approved.</p>');
},
error: function (err) {
console.log(err);
$('#comment-form-submit').html('Submit Comment');
$('.new-comment-form .js-notice').removeClass('notice--success').addClass('notice--danger');
showAlert('<p style="color:#e64848">Submission failed, please fill in all the required inputs.</p>');
$(form).removeClass('submitting');
}
});
return false;
});
function showAlert(message) {
$('.new-comment-form .js-notice').removeClass('hidden');
$('.new-comment-form .js-notice-text').html(message);
}
});
My problem is, if I submit the comment, the script doesn't work, but if I waited for sometime and submitted again, it works just fine.
I am guessing it has something to do with loading the scripts and running them, I saw some similar questions here but non of the answers fixed my problem.
Async on your script tags means 'Asynchronous'.
Usually, when you load a webpage, the browser will request (if not in its updated cache already) all the files and imports that are specified in your main html. One of these things that are loaded at start up is all your script tags.
But you have async in there.
So your code is not running because it doesn't exist yet!
Remove async and it should run fine.
Good day, all,
Long-time listener, first-time poster...
I have a client who has been promised a seemingly very complex bit of functionality. They want to load the contents of 3 separate pages into one, after a visitor to their site successfully logs in to their account. They want this to happen without a page refresh. Ajax is the solution. I am not, however, experienced with Ajax.
I'm having trouble figuring out how to tell when a $.get command (using jQuery's Ajax commands) has finished loading its content. My approach is to, once the login has been successful, to go and fetch the 3 separate pages, load their XHTML content into variables, and redraw the pages. Below you'll see my pseudo-code. I use "XXItemXX" to stand-in for actual paths. Each resulting page that I'm trying to pull in has a div with class "content" surrounding the data I want to retrieve. The XHTML looks like this:
<html>
<head>
<title>Page Name</title>
</head>
<body>
<div id="header">...</div>
<div class="content">
.
.
.
</div>
<div id="footer">...</div>
</body>
</html>
The jQuery code I've built follows. I'm able to get the form submitted and even get the content back from the various .get commands. The problem is, I can't seem to daisy-chain things as I normally would. I am struggling to figure out how to only fire the jQuery commands to draw the page once all 3 have been successfully retrieved. I'm afraid my biggest stumbling point is how to articulate this when searching with Google to see how others have dealt with this problem. I'm not sure exactly how to describe what I'm trying to accomplish in 10 words or less or in a fashion that will actually return the information I need.
Can anyone help with this? I'm afraid I have too little time and too much to learn.
<script type="text/javascript">
$('XXLoginFormXX').submit(function () {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
beforeSend: function() {
$('<div class="loading">Loading...</div>').insertBefore('XXLoginFormXX').css('position','absolute');
},
success: function(data) {
// On successful login, draw page.
$('.loading').fadeOut('slow');
var dr_editProfileXHTML, dr_accountOrderListXHTML, dr_wishListsXHTML;
$.get('XXPathToEditProfilePageXX', function(data1){
var dr_editProfileXHTML = $('div.content', data1);
});
$.get('XXPathToAccountOrderListPageXX', function(data2){
var dr_accountOrderListXHTML = $('div.content',data2);
});
$.get('XXPathToWishListsPageXX', function(data3){
var dr_wishListsXHTML = $('div.content',data3);
});
$('div.content').fadeOut(function(){
$(this).html(dr_editProfileXHTML);
$('XXEditProfileXHTMLXX').before(dr_accountOrderListXHTML);
$('XXEditProfileXHTMLXX').before(dr_wishListsXHTML);
}).fadeIn();
}
});
return false;
});
</script>
Thank you very much for your time, help, and consideration.
Yours,
Sylvan012
If your problem is to wait that all 3 requests have returned, then:
store the results in variables scoped a bit higher so that each of the callbacks can access them
add a variable drawing in the same scope
in each of the callbacks, check if all 3 variables are non-null and drawing is false
if that's the case, then set drawing to true, and do the work
After working on this with people's generous help, I believe I've gotten it. All my thanks to Dave Briand who taught me about .when and .then.
Following is the pseudo-code I came up with. It seems to be working! Sure there's a lot of clean-up to do, but all three of the pages are now being pulled-in! Whoot!
What do you think of my solution?
<script type="text/javascript">
$('XXLoginFormXX').submit(function () {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
beforeSend: function() {
$('<div class="loading">Loading...</div>').insertBefore('XXLoginFormXX').css('position','absolute');
},
success: function(data) {
// On successful login, draw page.
var Page01XHTML;
var Page02XHTML;
var Page03XHTML;
$.when(
$.get('XXPathToEditProfilePageXX', function(data1){
var Page02XHTML = $('div.content', data1);
}),
$.get('XXPathToAccountOrderListPageXX', function(data2){
var Page03XHTML = $('div.content',data2);
}),
$.get('XXPathToWishListsPageXX', function(data3){
var Page01XHTML = $('div.content',data3);
})
).then(function(Page02XHTML,Page03XHTML,Page01XHTML){
$('.loading').fadeOut('slow');
$('div.content').fadeOut(function(){
$(this).attr('id','MyAccount').html(' ' + Page01XHTML + Page03XHTML + Page02XHTML + ' ').parents('body').find('.content').each(function(){
dr_thisID = $(this).attr('id');
if (dr_thisID != 'MyAccount') {
$(this).appendTo($('div#MyAccount'));
}
}).parents('div#MyAccount').children().each(function(){
dr_thisClass = $(this).attr('class');
if (dr_thisClass != 'content') {
$(this).remove();
}
});
}).fadeIn();
});
}
});
return false;
});
</script>
I've started working with ajax a little lately, but I'm having trouble with something I feel is incredibly simple: storing a JS variable in PHP.
Say I want to store a zip code (assigned with Javascript) and pass that to a PHP variable via AJAX: Why doesn't this work?
Keeping it simple for demonstration purposes, but this is the functionality I desire..
zipCode.js:
$(document).ready(function() {
var zip = '123456';
$.ajax({
url: 'zip.php',
data: {zip_code:zip},
type: 'POST'
});
});
zip.php:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="zipcode.js"></script>
</head>
<body>
<?php
echo $_POST['zip_code'];
?>
</body>
</html>
An error: "Notice: Undefined index: zip_code" is all that is returned. Shouldn't "123456" be echo'd out?
You are supposed to put this:
<?php
// query database before echoing an associative array of `json_encode()`ed data if a response is needed
echo json_encode(array('zip_code' => $_POST['zip_code']);
?>
on a separate page, that is not an HTML page. AJAX just sends to that page, so you can use it and echo it out, making database queries before that, or what have you. Upon success you will see the result of your echo as the argument passed to the success method in this case if you used data as the argument the result for zip_code would be held in data.zip_code. Also, set your dataType:'JSON' in $.ajax({/*here*/}).
Here:
var zip = '123456';
$.ajax({
url: 'zip.php',
data: {zip_code:zip},
type: 'POST',
dataType: 'JSON',
success: function(data){
// in here is where you do stuff to your page
console.log(data.zip_code);
}
});
When you load the page, a call is being made to the server for zip.php, however that request is in no way linked to the page you're currently viewing.
If you look at the response to your ajax request - you'll see a copy of the page with the correct zip code echo'd
The actual answer then depends on what exactly you're trying to do (and a less simplified version of the code) to give you the best option.
The current setup you have doesn't make sense in practice
That is not how AJAX works. Thake a look at the example below. It will make an AJAX post to handle_zip.php and alert the results (Received ZIP code 123456)
start_page.html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="zipcode.js"></script>
</head>
<body>
This is just a static page.
</body>
</html>
zipcode.js:
$(document).ready(function() {
var zip = '123456';
$.ajax({
url: 'handle_post.php',
data: {zip_code:zip},
type: 'POST',
success: handleData
});
});
}
function handleData(data) {
alert(data);
}
handle_post.php:
<?php
die ('Received ZIP code ' . $_POST['zip_code']);
As others have mentioned, it sounds like you're expecting the two bits of code to run at the same time. The reality is that:
zip.php will be parsed on the server (and resulting in the error)
Server will then serve up the HTML to the browser (which will have a blank body due to the $_POST not existing when the PHP was parsed)
browser will see the javascript .ready() and run that code
server will handle the POST request to zip.php, and generate the HTML you're expecting. It'll be returned in the AJAX response, but as you're not handling the response, nothing is shown in the current session. (you can see the POST response using any of the common web developer tools)
Remember, PHP runs on the server, then any javascript runs on the client. You're also missing the step of handling the response from the request you made in your javascript.
try this to give you better idea of what's happening.
$.ajax({
url: 'zip.php',
data: {zip_code:zip},
type: 'POST'
});.done(function(data ) {
console.log(data)
});
In your code, the server is creating the page first, so no javascript is run yet, therefore it creates an error because $_POST['zip_code'] doesn't exist. Then it sends this page to your browser and you can see that. At this point is when your browser executes the javascript, it sends the request again, now with POST data, the server should return the response of the request and you should be able to see it in the console.
You could make this 2 separate pages, one for viewing the page, and anotherone for processing the ajax request, or if for your application you want to do it in the same page, you would need an if statement to get rid of that error, something like
if(isset($_POST['zip_code'])){
echo $_POST['zip_code];
}
I've a problem with an AJAX GET call using jQuery.
Here's my code:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
url : "http://localhost:8080/aplus-framework-webapp/reportServlet?",
data: "STAT_START_DATE=20131001&STAT_END_DATE=20131031&CAMPAIGN_START_DATE=2013-10-31&CAMPAIGN_END_DATE=2013-10-01&ORDER=Stato",
dataType: "json",
type: "GET",
processdata: true,
success : function (data) {
alert("IN");
},
error : function (richiesta,stato,errori) {
alert("NOT SUCCESS");
}
});// end ajax call
}); // end ready
</script>
The servlet reportServlet is my Java servlet running in localhost that return a JSON:
{"url":"http://d1p0y6pjyasam8.cloudfront.net/PGBANNER/text/20131105100823campaigns.csv"}
I test the page in local but I always see the alert reporting 'NOT SUCCESS'.
I'm new to JS, anyone have any idea on which could be my mistake?
Thanks
Alessio
Are Sure Your servlet return header json ?
If the website you're requesting from and the servlet you're requesting on do not have the same port (for instance 80 and 8080), it will break the Same Origin Policy.
See this stackoverflow question form more information and answers.
Try removing the question mark at the end of your url
I assume you mean with 'page in local' that you try this in a local file on your hard-drive. This is disabled due to security reasons in mainly all browsers. You can find further information how to disable this in Google Chrome for development purposes here:
http://opensourcehacker.com/2010/11/29/disabling-cross-domain-security-check-for-ajax-development-in-google-chrome/