Results dissapearing on refresh - javascript

After the user submits a form a new view for the results will be displayed. The results view will use the form fields to create a JSON object, send the JSON with an ajax request to the server and receive a JSON response that has all of the results. The results are then rendered with the view. This all works fine but when the results page is refreshed all of the results are gone. How would I make it so that my results will continue to show up after I refresh the page? What I'm trying to do now is alter the URL so that it will contain the query and then the results view will use the URL to form a request and send it to the server. Is this the recommended course of action for what I'm trying to achieve here? Thanks.

You will need to call the function which calls the ajax request on page load.. your values are getting lost as it will reset to default undefined/null etc when the user loads the page again.
If you want the onload method to take parameters, you can do something similar to this:
window.onload = function() {
// put something here so the function will not call if the ajax call has not been called beforee
yourFunction(param1, param2);
};
This onload will call the function for you therefore no matter what running the ajax call each time.
of course you will need validation so it does not call that function if the ajax request has not been used before.i.e. something in the query string when its successful etc.

Related

How do I send data to my ajax method from my controller?

I want to update a element based on things that are happening in the code server side.
For instance, when I invoke my "Start" function by clicking a button on my page it should change the text inside the element to "Downloading", and then once it's done it should change the text to "Done".
I have this script on my page which invokes a action and updates the text after making a successful request.
<script>
function StartDownload() {
$.ajax({
url: '#Url.Action("Start", "MyPage")', success: function (result) {
$("#badge").removeClass("badge-danger").addClass("badge-info").html("Downloading");
}});
};
</script>
as you can see, right now it's just making a request and on success it changes the class and it changes the text to "Downloading".
The goal is to change it to "Downloading" once it invokes the method, and then once the method finishes I want to change the text to "Done".
And I'm not sure how to do that, I need to some how listen for multiple calls in my ajax method but I have no idea how to do that.
What's the proper way of achieving this?
I was thinking of doing something like this but I'm not sure if that's valid
public ActionResult Start()
{
//Post data back to the ajax to tell it to change to "Downloading"
StartDownload();
//Post data back to the ajax to tell it to change to "Finished"
return View();
}
It is pretty simple in fact.
Except success $.ajax() has a lot of other "events", which you can use.
beforeSend for example may be your choice, because it executes just before ajax call
You can find more events here:
https://api.jquery.com/jquery.ajax/

Am having a problem with my JavaScript log out code

I am trying to logout a user using a JavaScript code but it keeps loading without logging out.What have I done wrong?
I have tried changing the function itself but it still wouldn't log out.The loader just keeps on running.
this is the code
logout.html(loader);
$.get("modules/"+role+"/"+role+".php",{
},function(pagedata){
logout.show().html(pagedata);
});
I'm expecting the code to logout and take me back to the login page.
The
$.get()
method requests data from the server with an HTTP GET request.
The required URL parameter specifies the URL you wish to request.
The optional callback parameter is the name of a function to be executed if the request succeeds.
$.get(URL,callback);
so change your code :
logout.html(loader);
$.get("modules/"+role+"/"+role+".php",function(pagedata){
logout.show().html(pagedata);
});

Ajax sending response back to php after ajax call

Suppose I have a page called form.php. I then clicked a button called "add button". This button triggers an event that got detected by a jquery function. The jquery function makes an ajax call to add.php.
Inside add.php, there is code that checks if a particular record exist in the database. If it does find that the record exists, I want to do the following.
Send a response string "exist" to ajax.
The ajax, inside the .done() function, will execute a prompt that says "This record already exist, do you wish to overright"?
If the user canceled the prompt, nothing more should happened and the ajax call should be done.
If the user clicks "ok", I would like the php script to be notified of this and execute an update statement using the data from form.php.
I suspect this is impossible because after receiving a response from php, AFAIK there is no way for ajax to respond back to the php script that is currently executing.
Am I correct or there is a way to do this?
You have to add a parameter to your ajax request, like override with true and false. By default/first request you set it to false. Then the add.php does it's default and returns exists.
The the user makes his decision. If he want to override, you send the ajax request again with the override parameter to true. Your add.php will notice the parameter and does whatever it has to do.
Wrap your ajax handler in an own function with a done callback. So you can reuse the request as often as you want. Pretty easy, no double code needed as well ...
The .done() function of your first ajax call executes when the ajax call has finished successfully, so when your php script has finished completely.
If you want to do something else, you would need to make a new ajax request. That could be to the same or another script, sending in different / new / additional parameters.
Note that you have to make sure that the second script cannot be called without the first one finishing, for example by setting and checking an expiring session variable.
you can do something like this.
$.post('add.php',$(this).serialize())
.done(function(result){
var r = confirm("This record already exist, do you wish to overright");
if(result == 'exist'){
if (r == true) {
$.post('update.php',$(this).serialize()).done(function(r){
console.log(r);
});
} else {
return false;
}
}else{
console.log(result)
}
});

Using GET method to get href attribute of an object

What i'm trying to do is what i thought would be quite easy, but it doesnt seem to be working. I want to get the href of an object and all the function is returning is undefined.
This is the page that i'm requesting and what i'm trying to retrieve is the href held in the element of the first seller (who's ClassName is ui-link-inherit)
var buy = $.get(
"http://m.roblox.com/items/24826737/privatesales/",
function (data){
alert($(data).find(".ui-link-inherit:eq(0)").attr('href'));
}
);
I thought it was a permissions issue at first but it still wont work even if you run that on the page.
Did you tried to just alert the data you get?
If there is no .ui-link-inherit ofc it wont work and since .ui-link-inherit seems to be a class of jqueryUI which adds the classes after the page is loaded via javascript, you wont get this class via GET
//EDIT: I dont get all this "you cant access the data cause ajax is asynchronus". He is using the get-fukction completely right. He can access data since data IS the returned stuff from the server. Did I miss something that you all get this that way?
You cannot return a value from that function, it is executed asynchronously. Instead just wait for the AJAX to finish and then do something with the result
// don't do this
// var buy = $.get(... etc...);
// the variable buy will never have any value
// do this instead
function getHREF(){
$.get(
"http://m.roblox.com/items/24826737/privatesales/",
function (data){
var buy = $(data).find(".ui-link-inherit:eq(0)").attr('href');
doSomething(buy);
}
);
)};
function doSomething(buy) {
// in here do whatever you want with the ajax data
}
$(document).ready(function () {
getHREF();
});
The site does not allow Cross-site HTTP requests. Read here: HTTP access control

Any function with mixed functionality of .ajax() and .load()?

.ajax() can send a post request and get data in return where as .load() can get any element in the rendered page. How to create a form when submitted(asynchromously) instead of getting back some data should get the page element of the rendered page that would be generated had there been normal submission instead of ajax submission?
I dont want to write views(Django) for xhr, normal requests separately. So, When I submit a form by ajax I dont want to hijack default action but only want to get some element of the rendered post submission page instead of actually being redirected to that post submission page which would have happened hadn't it been an xhr request.
Update:
load will do a POST rather than a GET if you supply the data to send as an object rather than a string. From the docs:
Request Method
The POST method is used if data is provided as an object; otherwise, GET is assumed.
So:
$("#target").load("/path/to/resource selector_for_relevant_elements", {});
..should convert the load from GET to POST. Of course, you'd replace {} with the arguments you want to send.
Original answer:
You can do the POST directly with ajax and then process the returned HTML yourself. For instance, to turn this load:
$("#target").load("/path/to/resource selector_for_relevant_elements");
..into a POST:
$.ajax({
url: "/path/to/resource",
method: "POST",
dataType: "html",
success: function(html) {
// Build the elemnts of the result in a disconnected document
var page = $("<div>").append(html); // See note below
// Find the relevant elements and put them in target
$("#target").html(page.find("selector_for_relevant_elements"));
}
});
I've done the wrapper div because that's what jQuery's load function does. You may want to look at the source for load (that line number will rot, of course, but the filename is unlikely to change) to see if there are other tricks you need to replicate.

Categories

Resources