Intercept and edit ajax data before submit - javascript

So I am trying to write a script that will go out and edit the html for all of my tumblr blogs, so i dont have to do it manually.
The problem is that tumblr doesnt really have a form that i can edit, and then submit through JS.. they have a very strange way of compiling the custom html and submitting an ajax request.
So, i was wondering if there was a way to intercept the ajax call before it goes out, edit a field in the data, and then make the submission my self?
I tried something like this:
var submitted = false
$("body").ajaxSuccess(function(evt, request, settings){
j = $.parseJSON(settings.data)
j.custom_theme = "PUT HTML HERE"
if (!submitted)
$.post(settings.url, j, function(data){
console.log(data);
submitted = true;
})
})
But i got a 403 forbidden error.
Does anyone have any ideas?

I'm not sure exactly what you're trying to do, but must this be done with a custom script? It sounds like this will only be used by you, so an extension should work. If so, there is a very useful Firefox extension, in the spirit of Firebug, called Tamper Data. This should be able to do what you want.
It allows you to monitor each request made by the browser, and you can turn on an option that allows you to look at, and edit, every single request before it gets sent.

Well, it's pretty obvious that ajaxSuccess isn't going to work in the way you want it to.
Assign the function which sends the AJAX request a new name and overwrite it. Call the previous function at the end of the new function, i.e. after manipulating the data the way you want.

Related

Typo3 jQuery OnClick Events

i need some help for my fresh installed Typo3 Website.
I want to set new Values within my DataBase via jQuery onClick Event.
So i guess i need to make use of this class: TYPO3\CMS\Core\Database\ConnectionPool.
Can someone Guide me how i can make use of this class within JavaScript.
I already tried the following, but i can't get it to work
define(['jquery', 'TYPO3\CMS\Core\Database\ConnectionPool'], function($, conPool) {
if(conPool.foo == 'bar'){
conPool.init();
}
});
Typo3 source
I appreciating any Help. Thanks
Your frontend should not be allowed to communicate directly with the database of your TYPO3 instance.
If you allow it anyone can inspect your javascript and get credentials to access your database - and do anything they like. :(
The correct way is a server request with the data you want to change.
then some PHP can compute the data (verify, adapt, ...) and change the value in the database (as PHP has the local credentials to access the database). Then it's up to you to give a notice in the front end if that operation was successful or not.
Such a server-request could be a complete page request, but a simple AJAX-call would be enough. Though you does not need to rebuild the complete page. From the Return of that AJAX request you can show only a notice about failure or success as a flash-message or similar.

how to commuincate between php and JS?

I am new to web development and I am trying to build my first website.
I am having some troubles because web development is dependant on several programming languages like PHP and JS, and the most difficult part for me is to communicate between these languages.
For example, I am trying to create a function that compresses a folder and generate a download link to that new archive, this can be easily done by PHP. However, when the user clicks the zip button, I also wish to display a pop-up window that tells the user to wait while the folder is being compressed, and when the compression is done I want to change the text on that pop-up and display the download link, and this, of course, requires JS.
I've tried many solutions but none of them seemed perfect for me, and I feel like that these solutions are quick and dirty, which I don't want.
If there is a secret I do not know, please tell me about so I can finally work with these languages as if they are a single language.
Also, if you can help me with my current problem, I would be extra grateful.
I just want to know how to construct a form that can call the JS function that displays the pop-up, then calls the PHP Zip_Folder function, and once the PHP function is done, I want to display the download link on the pop-up window.
This is my form code: (It only calls the javascript function that displays the pop-up)
<input type = 'button' onclick = 'Show_PopUP(\"Folder_to_zip\")' value = 'Download Folder'>
And this is the Show_PopUP function code:
function Show_PopUP(folder) {
var e = document.getElementById('Folder_Download_PopUp');
if(e.style.display == 'block')
e.style.display = 'none';
else {
e.style.display = 'block';}}
I already have the PHP function that compresses and generate a download link for the archive, so what I need now is a way to call it after the pop-up is displayed, and a way to print the download link on the pop-up once the function is done.
This might not be the best approach since I am a beginner, so if you have suggestions on how to get my task done without this complexity, I would be very happy.
Sorry if my question is too long, and thanks in advance for your help.
What you need to do is use these things called XHRs, or XMLHttpRequest (Google it), from within JavaScript to php, which basically is kind of like an invisible browser going to the php page behind the scenes and "loading" whatever the php page gives back, only this is all happening within JavaScript itself, so you can read that this "invisible page" loaded, which is from php, and do stuff with that, without actually refreshing the page. This process is known as AJAX (look it up)
What you can do is, when you set up this "invisible page", you can also send certain kinds of information along with it that the php page can read, and when it's done the php page can echo something back to the invisible page, which can then be read with JavaScript. This easy you can communicate between php and JavaScript, by sending certain values, in JavaScript, along with this invisible page, and waiting for php to echo something back to it, then reading that with JavaScript
So how do we actually do this?
First on the JavaScript side, we need to make this "invisible page", which is really not technically a page, it just does the sane thing as what is done to display any other web page, which is technically called a "request" since it's like asking the server for some data, it's basically "requesting" it, then when the server echoes something back, that's called he "response" to what was requested
So to make this new request in JavaScript we can do the following
var asking= new XMLHttpRequest ()
now that it as if an invisible page was created, but not yet navigated to anything, but we have to now metaphorically "enter in the URL" to this invisible page (without actually "navigating" to it yet) to do that we do
asking.open("GET", "pathToPHPpage.php?hi=there")
So the first part is called "GET" because we want to simply get a response back, without actually sending anything (if we were sending a file though, we would instead use "POST" then put the file date in the next step), then we enter in the URL to the php page that you want to get. If it's the same as the JavaScript page just put location.href instead, but it's important to add at least something to the end of the URL, notice the "?hi=there", you can call it anything, but it's important to have a question mark immediately following the .php page, then the name of something (in this case"hi") followed by it's value (in this case "there"), because the php page is able to read that, and give a different response back depending on what it says
Ok so now we have to actually "send" that request to the server, which is like metaphorically "navigating" to the URL on the invisible page, to do that
asking.send()
(And if you put "POST" before, you can add the date you want to send in between the parenthesis, usually in the form of a string but it can be different depending on the data, look it up for more reference)
Now, before we continue in the JS side, let's quickly switch over to PHP (doesn't have to be in this order though) to see what happened
We need to listen for any "requests" on the php page, that contain the name "hi" (since that's what we at the end of the URL before), to do that, around the top of PHP (technically anywhere in php though) we do
$isHi = $_GET["hi"];
if(isset ($isHi)) {
//Do some php code
echo "hi back!".$isHi;
}
Basically we just looked for the *hi" name in our "GET" request that was sent to PHP, we checked if it is "set", meaning not nulll, then we echoed some message back to JS, now let's listen for that message on the JavaScript side
Back to JS, after the .send line (or before), we need to listen for when the page echoes back.
To do that we check if it successfully loaded, because sometimes there can be errors, so let's do
asking.onreadstatechange= function () {
if(asking.readyState == 4 && asking.status==200) {
alert(asking.responseText)
} else alert("ooh something happened")
}
Now we have access to the response the php code gave us
You can extend this to other forms of communication, let me know if you have any questions

Spring MVC - RequestParamException parameter is not present

I've got an issue that occurs eventually in my website. It uses AJAX requests to get data from the server, which uses Spring MVC.
What happens (intermittently) is that sometimes we got an exception like this one:
org.springframework.web.bind.MissingServletRequestParameterException: Required Integer parameter 'page' is not present
at
This kind of exception occurs in some AJAX POST calls (not only for this case!!) and we still cannot reproduce it to understand what is happening.
For example, in one of the cases the parameter 'page' (used to load content while the user scrolls the page - so it's a required variable) is being sent through an AJAX call that has a 'data' field with the page parameter coming from a form like this:
<input type="hidden" name="page" id="page" value="1">
And a ajax call like this one (both $("#filter") and url are ok):
$.ajax({
type: "POST",
data: $("#filter").serialize(), // serializes the form's elements.
url: _ctx + URL_FILTER,
cache: false
})
The only way we got to reproduce that is by changing its property 'name' to something other than "page". But I guess this is not the case (most users don't even open the developer console...)
I've googled it a lot and I checked every possibility. The enconding is ok:
(Content-Type: application/x-www-form-urlencoded; charset=UTF-8)
The parameters are ok, the AJAX looks ok, everything seems ok... But we cannot find what is going on. We have tried a lot of possibilities but we still couldn't force these exceptions to happen.
One hypothesis we have is that sometimes the AJAX may send empty data blocks, with none of the parameters. But we don't even know whether it's true or not and how to check its veracity.
What are the possibilities? How can it be tested?
EDIT:
We could reproduce one of the ways to get the Exception: Reloading the page repeatedly for some seconds (keeping the reload key pressed for a while). Is there a way to prevent the exception for this case?!
Make the below change to controller's class method for page parameter
#RequestParam(defaultValue = 0) int page.
Or paste the controller method here.
If you are not been able to figure out what is reason behind missing parameter, so you can add
public void controllerMethodName (#RequestParam(required = false) int page)
code in your controller definition which will not throw any exception if parameter is not present in your ajax request.
Are you sure your form isn't being modified at the same time? For example, if your library used to handle the scrolling of the page tries to send the same form in a very short time (the first call updates the form while the second call is serializing it). This might be only on some browsers, not all of them, given that you can't easily reproduce it.
The way data is put back in the form might also be responsible for your problem.
Logging HTTP requests / using analytics would help you identify which requests / user agents are causing issues.

How do you make a link perform an action without reloading a page?

The clearest example of this I could think of is the Reddit Upvote/downvote buttons how when you click the button, the value for upvotes is updated, the upvote button lights up, and the page DOES NOT reload, you just stay exactly where you are on the page.
I am trying to make a feature similar to this and I can totally figure out how to do it with reloading, but I want it to not reload so the user experience isn't disrupted.
Is it possible to do this with php? or would I need to use javascript or something?
The action I would need it to perform would be a basic update query in the database.
This would be done with an Ajax call to your php script. Ajax is designed for these asynchronous updates and/or reloads.
Another way you can do this is with HTML5 WebSockets. You could have the client send a trigger to the server when the user clicks the upvote, and then the server could update and push back the data. It would, however, be a bit overfill for this.
If what you want to do is to contact a server to either send it some state or to retrieve some state from the server (or both), then you would use AJAX with javascript in order to contact the server without reloading the page. You can then also use javascript to update the state of your page after the operation. That is generally what the Reddit page you refer to is doing.
Conceptually, you'd set up your page like this:
Put the link on the page.
With javascript install an event handler so you are notified of a click on the link.
When the link is clicked, your event handler will be called.
Prevent the default behavior of the link so the browser doesn't navigate to a new page.
Then, in the event handler, send your data to the server using AJAX. You will obviously need a URL on your server and server process that can accept and process the data for you and return a value if you need to.
If you need the response from the server, then set up a callback function for when the AJAX call completes (this will be some indeterminate time in the future).
Then, if you need to change the current page in any way (like show one more upvote), then you can modify the current page with javascript to show that new state.
Ajax is easier to use with a library (like jQuery) that contains some ajax support code, but you can certainly implement it in plain javascript too.
Here's one example of ajax with plain javscript. You can find many other examples with Google.
This MDN tutorial on AJAX seems pretty helpful too to show you how it works.
You could use JavaScript to do this. Here's a quick sample:
Vote Up
Simple solution in JavaScript:
var el = document.getElementById("upvoteBtn");
el.addEventListener("click", onVoteClick);
function onVoteClick(e) {
e.preventDefault();
// do something
}
Here's a fiddle.
NOTE: I see you'd be updating the database. In that case, you would have to use AJAX in the onVoteClick function (or use XMLHttpRequest) for this. JavaScript is a client-side programming language and will not be able to communicate to the server without the use of AJAX or XMLHttpRequest. Using the jQuery library, you should be able to write AJAX pretty easy.
It's called AJAX.
With AJAX you can send a request in the background.
The easiest way is to use the jquery libary for this.
You can also output some data as JSON back to the script if you want to take some other actions depending on the result from that query.
A good tutorial is this one.
It also explains how this requests (called: XMLHttpRequest) work.
You need to use Javascript's XMLHttpRequest
You can use AJAX...
It allows you to use JavaScript (client side) to call server side functions. Here's a good example.

collecting output and form submission on a different page?

I'm looking for a way to gather the output(in text) on a webpage after a form submission.
Is there a way to maybe see the http response of a form submission in Javscript?
Otherwise, I would like to know if there's a nice way to somehow, say parse or collect outputs of multiple webpage(same page) form submissions. I know it's not possible (or too complicated) to save a file with the output in Firefox using Javascript.
So an option for me is to set up another webpage that will accept form submissions and somehow output the http response or webpage after submitting a form on a different page.
I was trying to do all this in Greasemonkey but I can't figure out a way to collect the output of multiple form submissions(of the same page) for analysis after finishing. What I have so far is filling out the right form and submitting(though it seems to keep going in a loop forever because every time you submit the form you land back on the same page and the Greasemonkey script executes the form submission over and over again), but I'm stumped at how to somehow collect the results.
I have not used macros like iMacros before so perhaps that might be a more suitable approach?
Thanks! Open to any suggestions and hope to hear any help! Muchhhh appreciated! :) Thanks again!
I've not any experience with Greasymonkey, but an AJAX call is relatively easy when using jQuery (but I don't know whether jQuery works with Greasemonkey).
http://jsfiddle.net/9peGW/
$.ajax({ url: "/",
type: "GET",
data: $('#theform').serialize(), // returns like '?test=val&test2=val2'
// using the elements of the form
success: function(text, state, xhr) {
alert(text.substring(0, 200));
// alert first 200 response characters
// (so that it fits in the alert box)
alert(xhr.getResponseHeader("Content-Type"));
// alert the Content-Type response header
}
});
Note though that AJAX requests only work for the same domain as it is called from, but perhaps this is not applicable through Greasymonkey (I really don't have experience with that).
İt is too easy at İmacros. You can search for a tag and extract information that you need. Do not try jQuery. It is too complicated for this job, I know :)

Categories