POST using XMLHttpRequest with existing source - javascript

What I am trying to do only using XMLHttpRequest, is this:
The script downloads a web page, that has only one form in it.
The script inserts text into a field.
The script submits the form, while keeping all details about input tags.
I did the first part, but I have no idea how to finish with the next two steps.
Note: I do not have control over the page downloaded, and it is not well-formed XML/HTML.
Could someone explain to me how I can get this done?
This is for a Google Chrome extension, so I have all permissions needed.
EDIT: this is my current code:
$.ajax({ url: "http://www.mysite.com/my/testpage.aspx",
type: "POST",
data: {
html: http0.responseText.between("<body>", "</body>")
},
success: function(data) {
var dom = $(data),
form = dom.filter('form');
form.attr('onsubmit', 'document.getElementById("error").value = "I\'m done!"; document.getElementById("helpmebutton").disabled = false;');
form.attr('action', 'http://www.mysite.com/my/testpage.aspx');
$('#tempdiv').append(form);
form.find('input[name="ctl00$ctl00$cphSite$cphMySiteContent$linkLocation"]').val(document.getElementById("result").value);
form.submit();
}
});

I would really use jQuery to save yourself time and headaches.
Create a temporary div with id tempdiv and put everything in that div. Then, fill in appropriate elements and submit the form, like this:
$.ajax({ url: "http://...",
success: function(data) {
var dom = $(data),
form = dom.filter('form');
$('#tempdiv').append(form);
form.find('input:text').val(123);
// all input[type=text] get value 123
form.submit();
}
});

Related

Is it possible to set an arbitrary form id before submitting manually with AJAX?

I made this really interesting piece of code that submits a form via AJAX only if the form carries an ID.
$(document).delegate('form', 'submit', function(event) {
var $form = $(this);
var id = $form.attr('id');
//if form does not have an id, then submit it without ajax!
if(typeof id == 'undefined'){
$form.submit();
}else{
$.post($form.attr("action"), $form.serialize(), function(response) {
//response stuff
});
event.preventDefault();
}
});
But the problem now is when i manually make an ajax form submit call from a different function, and pass the values manually, it submits the form regularly without Ajax. How can i add an ID to this ajax call before submitting the form to TestServlet if the form does not exist in the html?
//is it possible to add a form id before doing the ajax call below?
$.ajax({
// Maybe possible to add form id here?
url: 'TestServlet',
data: {
commentID: commentID,
comment: "lol"
},
type: 'post',
success: function(data){
window.location = data.url;
}
});
Your first piece of code tells me the following:
When your form has an html id attribute you submit it with AJAX using the url from action attribute.
When your form have no html id attribute, you make a normal submit, which uses the url from action attribute also.
So no matter which way you submit, you use a single action, it has nothing to do with your form id.
Then why within your second piece of code would you set a form id if there is no form at all?
Just work on creating a right url like below, for example:
$.ajax({
url: 'TestServlet/{possibleID}',
data: {
commentID: commentID,
comment: "lol"
},
type: 'post',
success: function(data){
window.location = data.url;
}
});

ContentEditable doesn't allow to send php strings

I have a problem with contenteditable .
Before i used textarea for sending posts for text. I want to change it now to use contenteditable.
So contenteditable doesn't allow to send php strings from data. For example
DEMO
In this demo i will show you my html and ajax codes. That is working perfectly, if user send normal text. But if user want to share php codes from his friends like (<?php echo 'Hi There.';?>) then problem will be come here. If user write normal text like (Hi There.) then not have any problem.
Normaly we are using val(); if we use textarea like this
var updateText = $('#post-text-area').val();
I think problem will be come here but i am not sure.
use with encodeURIComponent() .it will prevent the tag's passing from html to php .And retrieve the data from php use with decodeURIComponent()
$(document).ready(function() {
$("body").on("click", ".sendPost", function() {
var updateText = $('#post-text-area').html();
var dataString = 'update=' + encodeURIComponent(updateText);
$.ajax({
type: 'POST',
url: '/posttext.php',
data: dataString,
beforeSend: function() {},
success: function(html) {
decodeURIComponent(html);
}
});
});

My Ajax Form Submission script isn't working

I've got all my form areas setup correctly and my Javascript received them. I've tested this with "alert", but for some reason, I don't know why, my form either isn't submitting or the PHP is wrong.
Here's my JavaScript:
//Main Content
var ed = tinyMCE.get('content');
var doc = document.getElementById("docid").value;
//Post Area
ed.setProgressState(1); // Show progress
$.ajax({
type: 'POST',
data: {'docid':document.getElementById("docid").value, 'content':tinyMCE.get('content').getContent()},
url: 'save.php',
success: function () {
ed.setProgressState(0);
$("#notice").fadeIn("slow").fadeOut(3000);
}
});
return false;
Here's save.php:
$id = $_POST['docid'];
$cn = $_POST['content'];
require_once("scripts/php/rq/connect.docs.php");
mysqli_query=($con, "UPDATE wordit_documents SET main_document='".$cn."' WHERE id='".$id."'");
1. ensure client is sending correct data.
Try using the inspector in Google Chrome, and activate the network tab.
Under form data you can see the data sent to the server (the picture shows the text of this answer being sent to stackoverflow to be saved as a draft.).
If not:
Make sure your script is wrapped in a jQuery.ready function.
jQuery(document).ready(function($){
// goes in here
});
Test the output of
console.log(document.getElementById("docid"));
console.log(tinyMCE.get('content'));
console.log(tinyMCE.get('content').getContent());
I Found The Problem it was because of an "=" In The mysqli_query, Thanks For Answers

Ajax request 'onError' handler

There is one feature on my site: delete without page refresh. The user just presses 'delete' and the browser will send Ajax-request. It will load 'delete' script with id parameter.
All work well. But it is not very good because of referential integrity of the database. For example, It is possible to delete street, where some people are living.
I want to upgrade my script. I want to add a check to delete script and don't let delete data if some 'people' are connected to 'street' table.
jQuery handler of button click:
$('body').on('click', '.deleteStreet', function()
{
var id = $(this).attr('id');
var hideMe = $(this).parent().parent();
var dataString = 'id=' + id;
if(confirm("Are you sure you want to delete street? It is possible some people living there!"))
{
$.ajax({
type: "GET",
url: "/index.pl?mode=streets&action=delete",
data: dataString,
cache: false,
success: function(e)
{
hideMe.hide();
}
});
return false;
}
});
It will call script anyway and now will delete data anyway. I can add some checks to delete script now and it wouldn't delete, but jquery script would work anyway and will hide table row anyway (because request was send ok, without 404, etc)
1) Is it possible to see delete script result and hide or not hide row depending on it? For example, it will return true or false, js script will catch it and show message about deleting or not deleting of data depending on it.
2) This problem caused by structure of my site. There are some switches on index.pl and load appropriate scripts loading depending on query (mode=street then load street.pl, mode=user then load users.pl etc). So it will show all data loaded before delete.pl script and it will be impossible to check script returned true or false.
Any help? :) Thank you!
P.S.: I am very sorry for my awful english.
You can have the result of your ajax call in the first parameter of the success callback. ex:
$.ajax({
type: "POST",
url: "/index.pl?mode=streets&action=delete",
data: dataString,
cache: false,
success: function(e)
{
if(e === '1'){
hideMe.hide();
}
}
});
try to log your result in the console for tests: console.log(e).
For deleting data you should use a POST request ( or DELETE but not supported by all browsers).
I dont know how your datas (streets) looks like but an other way could it be to return all your existing streets in a json object on the delete request result. And refresh all lines.

How to remember a variable in JQuery for next AJAX load?

I load data set by Jquery AJAX as
$(function(){
$('#next').submit(function(e){
e.preventDefault();
var form = $(this);
var page = form.attr("action")
$.ajax({
type: 'POST',
url: page,
success: function(html){
$("#results").append(html);
}
});
});
});
The form is a single button with action="load.php?page=2".
When pressing submit button of the form, it will load data from load.php?page=2. How can I remember this action to load data from load.php?page=3 upon next click? and reading subsequent pages?
In fact, I want to introduce a new variable for the page number will be increased upon every click.
I would use an RegEx to slice the number from the end of the action attribute and replace the action in the success handler with the incremented page number.
I've also changed the line b.attr("action") to form.attr("action") as I think that is a typo in your version. If not stay with the original version of that line :)
$(function(){
$("#next").submit(function(e){
e.preventDefault();
var form = $(this),
page = form.attr("action"),
page_nr = (/\d+$/.exec(page) || ["2"])[0];
$.ajax({
type: 'POST',
url: page,
success: function(html){
form.attr("action", page.substring(0, (page.length - page_nr.length)) + (+page_nr + 1));
$("#results").append(html);
}
});
});
});
Example: http://jsfiddle.net/WfrU7/
you could just set a javascript var to represent page and then increment it on submit...
var page = 1;
$(function(){
$('#next').submit(function(e){
e.preventDefault();
var form = $(this);
$.ajax({
type: 'POST',
url: page,
success: function(html){
$("#results").append(html);
page += 1;
}
});
});
});
I don't know what your original page var had in it, but obviously you would tailor this response to fit your needs. your url param would not just be a single number, obviously, so update that part as you need.
The best way to handle these "need to keep history of" is, believe it or not, a dom element. We get so tied to programming, variables, and literals that we just forget the simple side of things. And, apparently, simple is what no one has in mind.
So, the "simple" solution is on the script of the page being loaded, save your querystring parameter (page=2 ... the 2) on a
<span id='curPageNumber' style='display:none; '>
in the loaded page. In the next call, all you have to to is, for example, onSubmit='functionSubmit(); ' and
function functionSubmit() {
var action="load.php?page="+$('#curPageNumber').text()*1+1;
$('#formID').attr('action',action);
$('#formID').submit();
}

Categories

Resources