Avoid form action call to php file from loading new page - php

I have a form that's calling a Post a .php file, which i though was the basis of ajax pushing (as opposed to retrieving data with ajax). Unfortunately, my browser will always load my called .php file instead of staying on the page containing the form. I' thinking there's a specific line of code I'm forgetting somewhere. What should I be looking for?
<form id="form-upload" enctype="multipart/form-data" action="_scripts/ajax/cropImage.php" method="post" onsubmit="return checkCoords();" style="min-height:450px; position:relative;">
<input type="hidden" id="x" name="x" />
<input type="hidden" id="y" name="y" />
<input type="hidden" id="w" name="w" />
<input type="hidden" id="h" name="h" />
<input type="hidden" id="ht" name="ht" />
<input type="hidden" id="wt" name="wt" />
<div style="position:absolute">
<h2>Upload a picture</h2>
<input id="input-upload" name="input-upload" type='file' onchange="readURL(this);" /><br/>
<img id="upload-preview" src="" alt="" />
<div style="position:absolute; bottom:0;">
<input type="submit" value="Upload" />
<input type="button" value="Cancel" onclick="$('#fancybox-close').trigger('click');"/>
</div>
</div>
<img id="spinner" style="position:absolute; background-color:transparent; left:49%; top:50%;" src="_images/uploads/ajax-loader.gif" height="32" width="32"/>
</form>

Seems that your understanding of AJAX is a little wrong, don't take me wrong, I suggest you to read more about it and try to implment it using Jquery libraries for Ajax. Those functions are very well documented and have great examples.
I would not use form tag while using ajax.
This is an example function you would use when use "submit" the data:
$.post("_scripts/ajax/cropImage.php", {
"y": yValue,
"x": xValue,
"h": hValue,
...
"input-upload": inputUploadValue
});
Explaining: You will send all values at the object ("y", "x", etc) to "_scripts/ajax/cropImage.php", as POST variables. You can also create a callback function, to receive data from the URL you sended those values, and validate if everything ran well.
It seems you're using the action attribute of your Form and submiting it. Show us all your related code, please. (Text before showing the code)

You can post data the same way you can retrieve data with jquery's ajax library.
See the .post() method.
You can get the contents of your input fields and then send them with ajax. If you want to keep your current form structure, you can use doSubmit(); return false; in an onsubmit event to cancel the original submit, and use your ajax method.

You are using a submit type button.
Change the type to "button", and make the onclick event something like:
onclick="sendData();"
Your sendData() function should contain the proper AJAX.
I see you are using jQuery, so just use the built-in ajax functions:
$.ajax({
url: "_scripts/ajax/cropImage.php",
context: document.body,
success: function(html){
alert(html);
}
});

$('#btnSubmit').click(function() {
// we want to store the values from the form input box, then send via ajax below
var comment = $('#comments').val();
var name = $('#Name').val();
$.ajax({
type: "POST",
url: "contactus.php",
// data: "fname="+ fname +"& lname="+ lname,
data: "name="+ name +"& comment="+ comment,
success: function(response){
$('#mail_sent').html(response);
}
});
});

Related

Sending a FormData object to server with Ajax (contains files)

I have a form that has both text and file fields. I am trying to submit the whole thing to a php script hosted on the server, and return a validation message. My form looks like this:
<form id="ambassador" method="post" enctype="multipart/form-data">
<label for="name">Name: </label>
<input type="text" id="name"> <br />
<label for="age">Age: </label>
<input type="number" id="age"> <br />
<label for="igram">Instagram Account: </label>
<input type="text" id="igram"> <br />
<label for="photo">Photograph Upload: </label>
<input type="file" id="photo"><br />
<label for="why">Why should you represent Drip Cold Pressed Juice?</label>
<textarea id="why" width="300px"></textarea>
<button type="submit" class="btn">Apply!</button>
</form>
And my jQuery looks like:
jQuery("#ambassador").submit(function(event) {
event.preventDefault
var server = "http://getdripped.com/dev/ambassador.php";
var form = document.getElementById('#ambassador');
var formData = new FormData(form);
alert(formData);
jQuery.ajax({
url: server,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
The php contains just a print_r statement for the $_FILES array and another for the $_POST array. However both returned arrays are empty.
You have two problems.
Failing to pass a form to the FormData object
document.getElementById('#ambassador');
The getElementById method takes an id but you are passing it a selector. You need to remove the #. Currently you are passing null to new FormData (because there is no matching element so gEBId returns null).
There is no successful data in the form
<input type="number" id="age">
Form controls can only be successful if they have a name attribute and none of yours do.
Once you correct the ID, you populate the form data object with all the successful controls in the form: but there aren't any.
You need to add a name attribute to each of your inputs.
I would use an iframe as the target of the form.
<form id="ambassador" method="post" enctype="multipart/form-data" target="form_iframe" >
<iframe name="form_iframe" id="form_iframe" ></iframe>
See also How to make Asynchronous(AJAX) File Upload using iframe?
Ignore the downvote, and
Set async to true!
You set the async to false. This means that your success callback won't wait for the reply and finishes therefor long before PHP answers.
Also look at this SO Question as there is an answer already if you get into more trouble.
From the jQuery Documentation:
Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
Quentin was right about the serialize, I deleted the serialize option after further reading.

jQuery submit function doesn't send input submit

I was looking for answer for my question but I didn't found solution. Here is similar topic link but I have different code and I don't know how to fit answer from this topic to my code.
Here is my problem. I'm sending my form with id order_form to test.php.
Every form value is sending proper except input submit. My script is based on checking that <input id="sendform" type="submit" value="ORDER PRODUCT" name="sendform"/> is send.
Below is code that I use to send form.
$("#order_form").submit(function() {
$.ajax({
type: "POST",
url: "includes/test.php",
data: $("#order_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});
return false; // avoid to execute the actual submit of the form.
});
And here is content of test.php
echo '<pre>';
print_r($_POST);
echo '</pre>';
Here is examle form because my form is extremaly big.
<form id="order_form">
<input type="text" name="w2b" value="abc"/>
<input id="sendform" type="submit" value="ZAMAWIAM" name="sendform"/>
</form>
In HTML5 forms when you are passing through parameters and variables to the ajax functions the value data from "Submit Inputs" isn't passed through. So if you have a form set up as :
<form>
<input type="text" name="foo" value="bar">
<input type="submit" name="submitTest" value="Hello World!">
</form>
The value of "submitTest" isn't being sent through. The only thing that gets sent through is the parameter "foo" with the value of "bar". "submitTest" only submits the form and executes your ajax call in this case.
To fix this just add a hidden element in the form.
Now it would look this
<form>
<input type="text" name="foo" value="bar">
<input type="hidden" name="sendform" value="ZAMAWIAM">
<input type="submit" name="submitTest" value="Hello World!">
</form>
This will send through the value to your ajax call and you can use it for whatever you might need it for.
Make sure you wrap your jquery code in
$(function(){
//code here
});
Again Dont forget to prevent Default Event , Below is a rewrite of your jquery code
$(function(){
$("#order_form").submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "includes/test.php",
data: $("#order_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});//end ajax
});//end on submit
});//end jquery

how does method POST processes/excecutes in PHP

I am building a web application, I am having lots of confusion when ever I use POST method.
Lets say I have the below code
<?php
$abc = 'abc';
if(some condition){
$abc = 'xyz';
}
if(isset($_POST['submit'])){
header("Location:http://someexample.php/$abc");
die();
}
?>
<form method="POST">
<input type="text" name="textinput" />
<input type="submit" name="submit" value="submit" />
<input type="submit" name="clear" value="clear" />
</form>
so as per my understanding, If I am not wrong.
When I click the SUBMIT / CLEAR button. The PHP file reloads the self page first before redirecting it to the header location.
If I am right. Is there any other way to avoid multiple redirects when we are working on big PHP files. When I have multiple SUBMIT button.
thank you in advance
You are basically redirecting your request to another page. Instead of redirecting the page using header you should use the action attribute of the form.
<form method="POST" action="yourexample.php" id="myForm">
<input type="text" name="textinput" />
<input type="submit" name="submit" value="submit" />
<input type="submit" name="clear" value="clear" />
</form>
the form will redirect you to the second page. If you do not want to reload your page at all you should use ajax. You can use jquery and post your values to another page buy creating a function. In this case your form tag should not have the action attribute or you
should use preventDefault method.
$("#myForm").submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
});
url will be the name of the page to which you want to redirect the user.
The data will be your form. You can use the .serialize() method to get your form data.
var data = $("myForm").serialize();
In success you can define a function on what to do in case of successful result.
Nothing wrong with multiple redirects: this is how traditional web works.
You may get reduce the number of redirects by using AJAX calls though.
Some notes on your pseudo-code:
it is quite useless to echo anything before Location header: noone is supposed to read the message. Not to mention that no output is allowed before headers.
http:// in front of address allowed only in case of fully qualified URI.
so, the code actually have to be
<?php
if(isset($_POST['submit'])){
header("Location: someexample.php");
die();
}
?>
Forms always post to the "action" attribute in it. If you don't want it to post to self, put your form opening tag as <form action="someexample.php" method="post">. The result will be the POST data being sent to someexample.php instead of to the same page as the form.
If you're looking into multiple form options on one page without redirect, take a look into AJAX submits.
The idea would be to send over the form to your receiving file, process the POST data, and return whatever you wanted returned from that process. For example:
$("form").submit( function(event) {
event.preventDefault(); //prevent the file submitting
var formData = $(this).serialize(); //process the form into an array for submission
$.ajax({
url: "receiver.php", //the url of the receiving file
type: "post", //setting method to post
data: formData, //set the data being sent to the form contents
success: function(response) {
$("div").html(response); //set the receiving div to the html you echo'd in the php document
}
});
});
Your receiver.php file can look exactly the same as a normal PHP document receiving POST data, so <?php if(isset($_POST['submit'])) {} ?> will still work exactly as you're expecting, without the page redirects! This solution does require jQuery though.
Edit:
To deal with the questions update of if(criteria) { $abc = 'xyz'; } there are a couple of suggestions.
To keep the asynchronous approach, go with $_SESSION variables. You could set them using the receiver.php and deal with them in the starting document.
To go back to a standard submission method onto the same document, either break your multiple options into radio inputs, checkboxes, or separate forms.
So:
<input type="radio" name="method" value="submit" />
<input type="radio" name="method" value="clear" />
That way you can choose what method to submit there.
Or you can break them into forms:
<form method="post">
<input type="submit" name="submit" value="submit" />
</form>
<form method="post">
<input type="submit" name="clear" value="clear" />
</form>
Finally, you could change the value of a hidden input on click if you wanted to change between submit and clear, so:
The HTML:
<form method="post">
<input type="hidden" id="method" name="method" value="" />
<input type="submit" id="submit" value="submit" name="submit" />
<input type="submit" id="clear" value="clear" name="clear" />
</form>
The jQuery:
$("#submit").click( function(event) {
event.preventDefault();
$("#method").val("clear"); //set the method to clear
$("form").submit(); //submit the form normally
});
$("#clear").click( function(event) {
event.preventDefault();
$("#method").val("submit");
$("form").submit();
});
The PHP:
<?php
if(isset($_POST['submit'])) {
//do something
} elseif(isset($_POST['clear'])) {
//do something else
}

1 form 2 actions

<form name="ipladder" id="ipladder" action="/checkuser/master-check.php" method="post">
<input name="ipladder" type="text" id="ipladder" />
<input type="submit" name="submit" id="botton" value="Check" />
<input type="submit" name="geo" id="botton"/>
</input></form>
I have one input box and 2 submit buttons. When the first button is pressed (name="submit") I want it to go to master-check.php as specified in the action= parameter. However when the geo button is pressed, I want it to go through a different action which I haven't specified because I didn't know how to do so.
What can I do so I can have 1 input box and 2 buttons each processing through different action files?
Maybe you can try altering the "action" parameter of your form in an onclick method that, after changing, submits the form. Something like:
$('#btn1').click(function(){
$('#ipladder').attr('action', 'location1.php');
$('#ipladder').submit();
});
$('#btn2').click(function(){
$('#ipladder').attr('action', 'location2.php');
$('#ipladder').submit();
});
Another option of couse, is to post to 1 page...and handle the logic (some redirect or whatever) there.
Make a single PHP script that handles which button has been pressed and then redirects to correct PHP handling script (after correcting what Juhana commented of course).
Instead of using form action, I think you can use Ajax to achieve what you want. It will be something like this:
<form name="ipladder" id="ipladder" method="post">
<input type="text" id="ipladder2" name="ipladder2" />
<input type="button" id="button1" name="submit" value="Check" onclick="action1()" />
<input type="button" id="button2" name="geo" value="Something else" onclick="action2()" />
</form>
and in the header you can define 2 Ajax functions:
<script type="text/javascript">
function action1()
{
$.ajax({
type: "POST",
url: "/checkuser/master-check.php",
data: $("ipladder2").val(),
success: //do something,
dataType: //return dataType
});
}
function action2()
{
$.ajax({
type: "POST",
url: //other URL,
data: $("ipladder2").val(),
success: //do something else,
dataType: //return dataType
});
}
</script>
Well you can achieve your goal by single php page as well.
on mastercheck.php something like this can help you.
<?php
if($_POST['submit'])
{
//you code for master-check.php
}
else if(isset($_POST['geo']))
{
//you code for other page goes here
}
?>

Load php content with jQuery AJAX

My problem:
I have index.html:
<form action="toload.php" method="post">
Input: <input type="text" name="something" value="" /><br />
<input type="submit" value="Submit!" />
</form>
toload.php is something like:
<?php
echo "Your input was: " . $_POST["something"];
?>
The question is quite simple.
When I press the Submit! button, I would like to dynamically load the content toload.php in index.html without the need of a refresh.
Thanks in advance! please comment for any needed clarification.
EDIT, a more verbose explanation:
I'm not sure I'm being clear (or maybe I'm not understanding the answers do to my lack of technical skills) so I'll give it another go. (re-write)
I have an HTML for with a submit button that sends a variable through POST method.
This variable is used by a PHP file and after a certain process, it inserts and update a MySQL database and echoes out some other stuff.
This is working JUST FINE.
But now I want to improve it by avoiding the page "reload" (going to the .php).
I want the HTHL that comes as an output of my HTML file to be dynamically shown in my HTML page.
Is it more clear now?
something like this with jQuery!:
<form action="toload.php" method="post">
Input: <input type="text" id="something" name="something" value="" /><br />
<input type="submit" value="Submit!" onclick="submitme()" />
<div id="something2"></div>
</form>
and function to submit:
function submitme(){
var tosend=document.getElementById("something").value;
$.ajax({
type: 'POST',
url: 'toload.php',
data: 'something='+tosend,
success: function(msg){
if(msg){
document.getElementById("something2").innerHTML=msg;
}
else{
return;
}
}
});
}
You must use AJAX (XMLHttpRequest) for that - http://www.w3schools.com/XML/xml_http.asp.
(You've said simply - as long loading 100KB of jQuery is not simply IMHO, I suggested pure JavaScript solution)
In your case you can use $.post()DOCS. If you gave your form an id="myForm" then you could load the return data into the form's parent in the callback as follows:
$('#myForm').submit(function(e){
e.preventDefault();
$.post("toload.php", $("#myForm").serialize(), function(data) {
$(this).parent().html(data);
});
});

Categories