I have big problem to use AJAX...
I don't want anything after ajax, but GET 304 page after success ajax...
here is my ajax code
$.ajax({
url: "/crawling/list",
type: "POST",
dataType: "json",
cache: false,
// ifModified: true,
async: false,
data: {
'query': input
},
success: (data) => {
...
},
fail: () => {
...
}
})
during about 0.00001 milisecond posted page is loaded and back to original get page..... my nodejs express console like this
my express console...
What's the problem? TT
I find HTML button element issue!
If I don't select button type, page should reload page.
If I use
there is no reload.
Good Good
Related
I trying to render a view using an AJAX call:
let data = {}
data.ph_user = ph_user
data.nav_destination ='bids_review'
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: '/users/navigation',
});
The router's code is:
router.post('/navigation', (req, res) => {
try {
var fname = req.body['ph_user']
var main_block = req.body['nav_destination']
if(main_block='bids_review'){
console.log(fname, main_block, 'zzzz')
res.render('bids_review', {ph_user: fname, main_block: 'dashboard'});
}
}catch(err){
console.log(err)
}
})
It looks like route is called properly but new view is not rendered. I don't get any errors on either server or client side.
I know i can do via form but would like to know if there is a way to accomplish this with AJAX call. Any guidance is greatly appreciated.
Your route returns rendered HTML to the AJAX call. If you want to render HTML directly from the server, do not use AJAX, just redirect to the route (i.e. use a form to post the data, or change the route to .get and redirect to the location).
To keep using AJAX, you probably want to return JSON from the route, and render it on the client.
I had the same problem. I did an Ajax call for modifying data. After the update the partial page had to be displayed again but now with information that the data has been updated. The code is just sample code but the important part is in the response the response.body is a stream. If you stream that to the partial (innerHTML), then your page is updated with the res.render data. Extra note: you could put that code in a separate function and then you could work with PUG with partials too :-)
// get form data, save history and post data to database
await this.serializeForm(form)
.then(data =>
this.replaceState(form.action).then( () =>
fetch(form.action, {
method: "POST",
headers: { 'x-requested-with': 'XMLHttpRequest',
"Content-Type": "application/json" },
body: JSON.stringify(data)
}).then( (response) =>
response
.body
.getReader()
.read()
.then( ({value}) => {
let html = new TextDecoder('utf-8').decode(value);
this.partialPage.innerHTML = html;
})
)));
I have a rest server running locally and a front end server running locally aswell. The rest server uses restify and session-cookie with passportjs. This all seems to be working fine as im using Postman app to test the API where cookies are being found and saved:
Postman app image
But when i use ajax on my front end app to login, i do not receive the cookie. Or at least it does not seem to save. This is the ajax code:
$("form#login-form").submit(function(){
var data ={
email: $(this).find("input[name='email']").val(),
password: $(this).find("input[name='password']").val()
};
var data = JSON.stringify(data);
$.ajax({
type: 'POST',
url: URL + "/login",
data: data,
contentType: "application/json",
dataType: "json",
xhrFields: {
withCredentials: true
},
success: function(data) {
console.log(data);
if(data.error){
console.log("logged in error:" + data.error);
}
else {
console.log("logged in:" + data.LoggedIn);
window.location.replace("/");
}
}
});
But the front end acts like it does log me in with each page displaying the right user info and logging out works perfectly too, but i cannot find a stored session for the page anywhere in chrome or firefox dev tools.
What could be causing this?
A Cross-domain request bothered me. I want to use ajax request jsonp data from a third-party data-bank. But some works, some not, maybe the callback jsonp-data is not supported, how can I fix it if the data-bank only return json?
function newcreateElement(url) {
$.ajax({
type: "get",
async: false,
url: url,
dataType: "jsonp",
jsonp: "callback",
jsonpCallback: "jsonpcallback",
success: function (json) {
$("#div pre code").html(JSON.stringify(json));
},
error: function (XMLHttpRequest, textStatus, readyState, status) {
alert(textStatus);
alert(XMLHttpRequest);
alert(readyState);
alert(status);
}
})
}
I have a simple ajax call and when I debug on server side (node) I alays get 2 calls...
I thought it was becuase of favicon but I dont think it is because I
app.use(express.favicon('public/assets/favicon.ico'));
I even tried to just do a catch all for favicon so I am pretty sure its the not the issue:
app.post('/_html/favicon.ico', function (req, res) {
console.log('2222');
res.send('{"serverName": 1}');
});
here is the ajax code:
$.ajax({
url: some_url.html,
type: "POST",
crossDomain: true,
data: '{a: 1}',
dataType: "json",
contentType: "application/json",
success: function (res) {
alert(res.serverName);
console.log(res.serverName);
},
error: function (res) {
alert("Bad thing happend! " + res.statusText);
console.log("Bad thing happend! " + res.statusText);
}
});
and for some reason when I debug on node server side, I always get 2 calls from ajax
:(
why?
Thanks,
Sean.
It's preflighted request.
Cause you yse non-standard content type browser first send OPTIONS request and then real POST request with your data.
BTW, {a: 1} is invalid JSON. It must be {"a": 1}.
I have already get the response json data from server to browser, but it is confused that the data can not be displayed in the browser and I found the error in the console that told me 'Uncaught SyntaxError: Unexpected token :'. Here is my code in node js.
function callFacebook(){
$.ajax({
url: "http://192.168.37.179:8888/facebook/connect?callback_=[TIMESTAMP]",
type: "GET",
dataType: "jsonp",
jsonp:"jsonp",
cache: true,
timeout: 5000,
success: function(data) {
execute(data);
},
error:function() { console.log('Uh Oh!'); }
});
}
and here is the response json data:
res.header('Content-Type','application/json');
res.header('Charset','utf-8');
res.send({"something": "father"});
From the server you are sending just normal JSON data, but on client you are expecting JSONP.
The response from server is not JSONP and browser does throw exception as syntax is wrong.
If you need to send JSONP from server, then if you are using express add extra use:
app.configure(function() {
app.set('jsonp callback', true);
});
Then to send JSONP just slightly change res. You don't need to set any header anymore, as they will be automatically detected:
res.jsonp({ hello: 'world' });
On client side, jQuery will add callback it self, so use just this simplified way:
$.ajax({
url: "http://192.168.37.179:8888/facebook/connect",
type: 'GET',
dataType: 'jsonp',
cache: true,
timeout: 5000,
success: function(data) {
console.log(data)
},
error: function(xhr, status, error) {
console.log('error[' + status + '] jsonp');
}
});
As well if your node is proxied through nginx or any other web platform, don't forget to enable utf8 encoding there.