Before going to the specific question I need to explain a few basic steps.
First, the application in question deals with the management of appointments online by customers.
The customer after filling a form with the treatments for the beauty center and providing their information comes to the confirmation page.
Now this page performing an ajax request to store the appointment on the database.
If everything is successful is shown a page containing the details of the appointment with the success message.
The problem is that the page is currently displayed only in the response, that is, in the tab network console browser.
So my question is simple: How can I replace the entire structure of the html page with actual one shown in the response?
I found a lot of questions on the web even on StackOverflow. But all of this is limited on an append to a div. I do not need to hang but also replace the <html>, how to rewrite the html page. I have no idea how to do this and I need some advice from you.
For completeness, this is the code that comes back to me ajax response html:
$.ajax({
'type': 'POST',
'url': 'backend_api/ajax_save_appointment',
'data': postData,
'success': function(response)
{
console.log(response);
},
'error': function(jqXHR, textStatus, errorThrown)
{
console.log('Error on saving appointment:', jqXHR, textStatus, errorThrown);
}
});
If your response includes the <head> and <body> tags:
$("html").html(response);.
If not, and it's only content, then do:
$("body").html(response);.
if the response is the html content, you can use this line of code:
...
'success': function(response)
{
$("body").html(response);
}
...
update:
this will be hard to replace the html tag, but what you can do:
...
'success': function(response)
{
$("html").html($("html", response).html());
}
...
you parse the response with jquery, getting the content of html and replacing the content of the current html
this question has already been treated here:
Replace HTML page with contents retrieved via AJAX
Basically, you may try (My bad this is not working on IE):
document.open();
document.write(newContent);
document.close();
or, since you are using jquery
$("body").html(data);
Regards
Perhaps you can use following code in your 'success'-function to redirect to a different route.
window.location.href = 'http://host.local/path/to/appointment-details';
#JudgeProhet It seems to me that you do not need AJAX request for this purpose. There is no advantage in doing it this way. If the entire page is updated it could be done by an ordinary HTTP request. If you want to use AJAX, you could simply use JavaScript to redirect to new page, which contains appointment details.
$.ajax({
'type': 'POST',
'url': '/backend/ajax_save_appointment',
'data': postData,
'success': function(response)
{
console.log(response);
// redirect browser to new location
window.location.href = '/backend/appointment_details';
},
'error': function(xhr, status, error)
{
console.log('Error on saving appointment:', xhr, status, error);
// display error message to the user
}
});
I don't have enough reps to leave a comment (!!) but the UPDATE answer by #fribu-smart-solutions (https://stackoverflow.com/a/33914275/1428972) should be marked as the correct one, using:
$("html").html($("html", response).html());
This fully replaces the page via ajax. This does the job properly whereas others even using "html" doesn't fully work.
I know this is an old post but it just solved my problem on the same issue! :)
Related
I am developing a web app using HTML, PHP and JavaScript. I found a way to call PHP methods that run database operations from the client-side (HTML and JS) using AJAX, here's an example:
if (confirm('Sure you want to do that?')) {
$.ajax({
url: "myScripts.php",
type: "POST",
data: {
paramForOperation: myParam,
option: "doAction1"
},
cache: false,
success: function(response) {
//Here I reload or load another page after server is done
window.open("myPage.php", "_self");
}
});
}
So here I call the php file with the script that does an INSERT/ DELETE / WHATEVER on the database. It works fine, but what if I couldn't insert because the index already exists or any other reason? What if some type of data is wrong and I can't insert it? I know I can validate that on the server side using PHP, but how do I return a message saying "Operation complete" or "You should use numbers on X field"?
I thought of something like alert(response); but what will it return? An echo($msg); from my PHP functions? Is there a way to send the result message on that response thing in AJAX?
Thank you for your help.
Any output of the PHP script will be received in response. Remember, the PHP script runs on the server and just generates output. The PHP code itself never reaches the client.
So, you can just echo a message, and alert it in Response.
Bringing it up a notch, you can return a small piece of JSON or XML that can be parsed and which can contain an error message and some error code, so you script can also respond to that, and maybe change its behaviour (if the insert succeeded, add the new data to the page, for instance).
And of course, instead of returning always code 200 (meaning OKAY) from PHP, you could consider returning other HTTP status codes, so the code already indicates whether something went wrong or not. Depending on the status code, jQuery will execute either the success or the error handler, so it's easy to make different handlers for different situation.
Let your server respond with appropriate HTTP Status Codes and meaningful error messages. Use the error function of the ajax call.
$.ajax({
url: "myScripts.php",
type: "POST",
data: {},
success: function(response) {
/* no error occured, do stuff... */
}
error: function(jqXHR, textStatus, errorThrown) {
/* handle the error, add custom error messages to any DOM objects, ... */
console.log(textStatus, errorThrown);
}
Some docs: $.ajax and HTTP Status Codes
So I have searched the forum for similar questions unfortunately I have been unlucky to find an answer that suits my problem.
I am trying to make an ajax call in my jquery using the following code;
function submitForm(formData)
{
$.ajax({
type: 'POST',
url: 'addEvents.php',
data: formData,
dataType:'json',
cache:false,
timeout:7000,
success: function(data){
$('#addEventsForm #response').removeClass().addClass((data.error === true) ? 'error' : 'success').html(data.msg).fadeIn('fast');
if($('#addEventsForm #response').hasClass('success')){
setTimeout("$('#addEventsForm')",5000);
}
},
error:function(XHR,textStatus,errorThrown)
{
$('#addEventsForm #response').removeClass().addClass('error').html('<p> There was an <strong>' + errorThrown +
'</strong> error due to <strong>'+ textStatus +'</strong> condition.</p>').fadeIn('fast');
console.log(arguments);
//alert(XMLHttpRequest.responseText);
},
complete:function(XHR,status)
{
$('#addEventsForm')[0].reset();
}
});
}
But I am getting a sysntax error. I have tried doing this to see what errors I get in chrome
console.log(arguments);
but the responseText in the [Object, "parsererror" , SyntaxError] node seems to display the entire html of the page that contains the form where I am inserting the record.
I am still getting my feet wet in ajax so I am not yet a pro in absolutely understanding the error messages and what they mean.
Is the above js/jQuery code located on the addEvents.php page -- that is, on same page that you are posting the AJAX to? (In other words, are both the form/ajax and the AJAX destination on the same physical PHP page?)
If so, you will get exactly what you describe: the entire HTML of the page spat back at you.
AJAX, by design, must post to a different physical page on the server. That's just how it works.
Also, FWIW, note that dataType: 'json', refers to the data being returned, not the data being sent. Perhaps you already know this, but it is a common misunderstanding so is worth mentioning.
Edit:
As Felix points out, this answer is not technically perfect. It is possible to post AJAX code to the same page, but you must specifically allow for that. Perhaps FK or another could edit this post to add an example of what that additional code would look like?
I have a select box(list box) where it has 3 values drop down like Pending,Approve,NotApproved and when I select any one of them I want to fire a query so that I get data from database
like select * from table where status="Pending" without reloading page.
can any one help me how can I get data from database without page refresh in a php file.
Thanks in Advance
You can use a get or post AJAX request like so:
jQuery.ajax({
url: '/path/to/file',
type: 'POST',
dataType: 'xml/html/script/json/jsonp', // I guess html will be do or JSON if you are returning in a JSON format
data: {param1: 'value1'}, // Here you can send any additional parameters like status ( pending etc.)
complete: function(xhr, textStatus) {
//called when complete
},
success: function(data, textStatus, xhr) {
//called when successful
// in the data variable you will receive the data from your PHP file if the request was succesfull
},
error: function(xhr, textStatus, errorThrown) {
//called when there is an error
}
});
Reference: https://api.jquery.com/jQuery.post/
You should use AJAX for this (as is said in comments). You have can use :
XmlHttpRequest,
jQuery : Less code than an ordinary XmlHttpRequest and easier to implement. Perfect for beginner but heavy if you are looking for performance (to my mind),
And some libraries that I don't know.
I am playing with Google API in javascript. I managed to get a list of my contact with the following code :
$.ajax({
url: 'https://www.google.com/m8/feeds/contacts/default/full?access_token=' + access_token + '&alt=json',
method: 'GET',
error: function(error) {
alert('An error has occured during contact creation.');
},
success: function(data, status){
console.log(data);
}
});
I tried to add a contact by changing GET to POST and adding my contact data in the request body. But as soon as I add a data attribute, or change GET to POST, the server answers me the really annoying "No 'Access-Control-Allow-Origin" error.
Any idea?
I am following this documentation : https://developers.google.com/google-apps/contacts/v3/?csw=1#creating_contacts
Thanks a lot
It is possible to do this from the browser, although not obvious at all.
Based on this SO answer, we learn that there is method called gapi.client.request that can be used for this (instead of jQuery's $.ajax).
Accordingly, for editing we can do:
gapi.client.request({
method : 'PUT',
path:'m8/feeds/contacts/default/full/<contactId>/<editRevisionFromGET>',
body : {"version":"1.0","encoding":"UTF-8","entry": ...},
callback : function(data) {
console.log(data);
}
});
The important parts for editing in here are:
send back the entire entry you got before from a read
use the current ID given at the end of the URL in the entry.link element with relation type edit (or you'll get a HTTP Status 409 - Conflict)
Side note:
Notice that these requests actually are done to https://content.googleapis.com/ ...
From some quick tests, it seems you can do ?all? requests just to that URL instead of google.com, and then CORS issues disappear.
This is my first time using AJAX. I'm trying to load one of my pages when a link is clicked (I know I can just do <a href="something.html"> but I am doing it just for the sake of using AJAX, and ran into an issue where my page loads but the javascript of the page doesn't. Is this a normal AJAX consequence? I'm guessing it has to do with dataType: html? Here's my code:
function getContent(filename) {
$.ajax({
url: filename,
type: "GET",
dataType: "html",
beforeSend: function(){
$('html').html('<img src="../images/loading.gif">');
},
success: function (data, textStatus, xhr) {
if (filename == "second.html") {
setTimeout(function (){
$('html').html(data);
}, 2000);
} else {
$('html').html(data);
}
},
error: function(xhr, textStatus, errorThrown) {
$('html').html(textStatus);
}
});
}
Can you check chrome's network monitor? First off, does anything get a 404? Is the file literally second.html? If so then there shouldn't be path issues. Next what is the "response" that appears for that item? Does that response look ok?
Next, why don't you try moving the JS from head into the body for the second page? JS should always be right before the closing body tag for performance reasons. Also, there may be an issue with JS being in head and it not getting executed for that reason.
You should be able to load anything on your domain without any issues via AJAX, but there are path issues to watch out for.
This is because the ajax page is only returning rendered content, but does not run like a normal page would. You can use PHP on the ajax page for example, the server renders it and then sends it through, because PHP is pre-render, javascript runs after the page is rendered, as far as I know.