express.js - dynamic pageloads via ajax - javascript

ok i'm that far:
app.get('/mypartial', function (req. res) {
res.render('mypartial', {layout: false, data: data});
});
this renders out my jade with the data and sends it as html to the client
now i need to fetch this via js and to render it out using
$('#idofparentelementofyourpartial').html(responseHTML);
so i would need something like:
//// Pseudocode
var locat = window.location.pathname;
on locat change{
prevent default // because i want to use the ajax call (not standart browser call)
ajax({
url: locat,
type: "GET",
dataType: "json",
success: $('#idofparentelementofyourpartial').html(data);
});
}
the strange thing is that "layout: false" still trys to render something: i would expect that it just puts stuff into the dom

You may have a look at jQuery load() to load partial html into a defined container.
ajax({
url: locat,
type: "GET",
dataType: "json",
success: $('#idofparentelementofyourpartial').html(data);
});
Datatype JSON is not what you want.

Related

Ajax: conflict in client between two functions

For a university homework, I have to create a little e-commerce website.
After the login, the user is redirected to the homepage. In this homepage, the client will recive a JSON object from the server (containing some product to be loaded) to generate the DOM of the homepage dynamically.
Note: I must use AJAX and JSON
I have this client.js file:
$(document).ready(function() {
// AJAX request on submit
$("#login_form").submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "submit.php",
data: {
Email: document.getElementById('login_email').value, // Email in the form
Password: document.getElementById('login_password').value // // Password in the form
},
cache: false,
success: function(){
window.location.href = "home.php"; // load the home.php page in the default folder
}
});
});
});
$(document).ready(function() {
// AJAX request to open a channel between php and client
function (e) {
e.preventDefault();
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
var data = JSON.parse(data);
alert(data); // debug
showProducts(data);
});
});
});
});
function showProducts(data){
alert(data);
// Insert object into the page DOM
}
I don't know why, but I can't access after the login if the second Ajax request (the AJAX request to open a channel between php and client) is not commented, and I don't know why, because the code seems right... Any suggestion?
after login action you need to set to cookie token in response
success: function(response){
console.log(response)
// then set to cookie response.token
window.location.href = "home.php";
}
after set token to cookie, you need to send this token to next ajax request url: "queries.php",
You need to wrap your anonymous function in parenthesis and add () at the end if you want to execute it:
(function (e) {
// I don't know why you need this:
e.preventDefault();
// etc.
})();
You should also check the contents of that function as you seem to have too many closing parentheses and you don't need to parse the returned value if you set the dataType to json.
In the end I think this is about all you need for that function:
(function () {
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
console.log(data); // debug
showProducts(data);
}
});
})();
or just:
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
console.log(data); // debug
showProducts(data);
}
});
To get it directly on page load.

Using AJAX call in MVC5

I have tried to use AJAX call in an MVC5 project as many similar examples on the web, but every time there is an error i.e. antiforgerytoken, 500, etc. I am looking at a proper AJAX call method with Controller Action method that has all the necessary properties and sending model data from View to Controller Action. Here are the methods I used:
View:
#using (Html.BeginForm("Insert", "Account", FormMethod.Post, new { id = "frmRegister" }))
{
#Html.AntiForgeryToken()
//code omitted for brevity
}
<script>
AddAntiForgeryToken = function (data) {
data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val();
return data;
};
$('form').submit(function (event) {
event.preventDefault();
//var formdata = JSON.stringify(#Model); //NOT WORKING???
var formdata = new FormData($('#frmRegister').get(0));
//var token = $('[name=__RequestVerificationToken]').val(); //I also tried to use this instead of "AddAntiForgeryToken" method but I encounter another error
$.ajax({
type: "POST",
url: "/Account/Insert",
data: AddAntiForgeryToken({ model: formdata }),
//data: { data: formdata, __RequestVerificationToken: token },
//contentType: "application/json",
processData: false,
contentType: false,
datatype: "json",
success: function (data) {
$('#result').html(data);
}
});
});
</script>
Controller: Code cannot hit to this Action method due to antiforgerytoken or similar problem.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public JsonResult Insert(RegisterViewModel model)
{
try
{
//...
//code omitted for brevity
}
}
I just need a proper AJAX and Action methods that can be used for CRUD operations in MVC5. Any help would be appreciated.
UPDATE: Here is some points about which I need to be clarified:
1) We did not use "__RequestVerificationToken" and I am not sure if we send it to the Controller properly (it seems to be as cookie in the Request Headers of Firebug, but I am not sure if it is OK or not). Any idea?
2) Should I use var formdata = new FormData($('#frmRegister').get(0)); when I upload files?
3) Why do I have to avoid using processData and contentType in this scenario?
4) Is the Controller method and error part of the AJAX method are OK? Or is there any missing or extra part there?
If the model in your view is RegisterViewModel and you have generated the form controls correctly using the strongly typed HtmlHelper methods, then using either new FormData($('#frmRegister').get(0)) or $('#frmRegister').serialize() will correctly send the values of all form controls within the <form> tags, including the token, and it is not necessary to add the token again.
If your form does not include a file input, then the code should be
$('form').submit(function (event) {
event.preventDefault();
var formData = $('#frmRegister').serialize();
$.ajax({
type: "POST",
url: '#Url.Action("Insert", "Account")', // do not hard code your url's
data: formData,
datatype: "json", // refer notes below
success: function (data) {
$('#result').html(data);
}
});
});
or more simply
$.post('#Url.Action("Insert", "Account")', $('#frmRegister').serialize(), function(data) {
$('#result').html(data);
});
If you are uploading files, then you need you need to use FormData and the code needs to be (refer also this answer and
$('form').submit(function (event) {
event.preventDefault();
var formData = new FormData($('#frmRegister').get(0));
$.ajax({
type: "POST",
url: '#Url.Action("Insert", "Account")',
data: formData,
processData: false,
contentType: false,
datatype: "json", // refer notes below
success: function (data) {
$('#result').html(data);
}
});
});
Note that you must set both processData and contentType to false when using jQuery with FormData.
If you getting a 500(Internal Server Error), it almost always means that your controller method is throwing an exception. In your case, I suspect this is because your method is returning a partial view (as suggested by the $('#result').html(data); line of code in you success callback) but you have specified that the return type should be json (your use of the datatype: "json", option). Note that it is not necessary to specify the dataType option (the .ajax() method will work it out if its not specified)
If that is not the cause of the 500(Internal Server Error), then you need to debug your code to determine what is causing the expection. You can use your browser developer tools to assist that process. Open the Network tab, run the function, (the name of the function will be highlighted), click on it, and then inspect the Response. It will include the details of the expection that was thrown.
contentType should be application/x-www-form-urlencoded
Try this code
<script>
$('form').submit(function (event) {
event.preventDefault();
$.ajax({
method: "POST",
url: "/Account/Insert",
data: $(this).serialize(),
contentType:"application/x-www-form-urlencoded",
success: function (data) {
$('#result').html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
});
</script>

Post data don't send using jQuery Ajax request

how to send large base64 data Array using jQuery Ajax. Here is my code :
$.ajax({
type: "POST",
url: "addPhoto.php",
data:{photosArray:photosArray},
dataType: "json",
success: function(data) {
$(data).each(function(){
...
});
}
});
photosArray contains between 3 and 12 very long strings like :
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAMAAAC6V+0...
Is there any limit for POST data size in Ajax?
Open your php.ini file and find the line stating upload_max_filesize. The default it set to 2M, which is 2MB. Try increasing it to 3MB and see if you are still receiving the error.
And use
"cache": false
Is your data properly declared ? It can be either String, object or array. try following
$.ajax({
type: "POST",
url: "addPhoto.php",
data:"{photosArray:photosArray}",
dataType: "json",
success: function(data) {
$(data).each(function(){
...
});
}
});

Sending ASP.NET Model through AJAX

I'm trying to send part of a model through an ajax call, but doing it simply like my code below, doesn't work. How could I pass this object along?
$.ajax({
url: "/Controller/Action",
type: "GET",
data: #Model.Company,
success: function (result) {
$('#myDiv').html(data);
}
});
This is what my JS puts outs:
MyProj.Domain.Entities.Company
This is my error:
Uncaught ReferenceError: MyProj is not defined
Your syntax would work fine for a primitive variable, but you should serialize your object to Json before sending. And also make sure that script stays in cshtml or aspx page, else '#Html' helper will not work.
$.ajax({
url: "/Controller/Action",
type: "GET",
data: #Html.Raw(Json.Encode(Model.Company)),
success: function (result) {
$('#myDiv').html(data);
}
});

unable to get json response coming from REST web service in html using jQuery

I have a JSON response coming from REST web service and want to bind that data to html using jQuery. Looks like its not even hitting web service url which I have provided in my jquery.
Url is working fine which gives me JSON data in browser but jQuery I am using unable to get any content from this. I am pasting my code here, plz let me know if some one can help.
While debugging script its directly going on error section in ajax call.
<script type="text/javascript">
$(document).ready(function () {
GetData();
});
function GetData() {
// alert(textblock.value);
$.ajax({
type: "GET",
url: "http://localhost:8092/api/Employees",
data: "{'employeeId'= '" + 1234 + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var results = $.parseJSON(msg.d);
alert(msg);
alert(results);
},
error: function (result) {
alert('here');
var tt = result.text;
alert(tt);
}
});
}
</script>
finally i am able to get data now.
I added below properties in $.ajax:
processData: false,
async: false,

Categories