I'm passing some variable from one file to another php file that contains a form via jQuery ajax. On The form page where data is being passed to have the following code in it, The values are getting passed in properly and and fields are getting populated with the correct entries, i'm able to very this with firebug response, but page is not automatically submitting. Is their anything i should be looking for that is preventing form from auto submitting. If i access the form page directly, i can see auto submit works.
<?php
$title = $_POST['title'];
$wrapper = $_POST['wrapper'];?>
<form action="test.php" method="post" id="publish">
<input type="text" value="<?php echo $title ?>" name="title">
<textarea name="wrapper"><?php echo $wrapper?></textarea>
<input type="submit" value="Submit">
</form>
<script>
window.onload = function(){
document.getElementById('publish').submit();
}
</script>
ajax code that is sending the values looks like this
$.ajax({
type: "POST",
url: "process.php",
data: {
title: 'test',
wrapper: 'testing123'
},
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Spot the difference:
getElementById('publishForm')
id="publish"
From what I see the auto submit is linked to the 'publishForm'
However, your form Id is "publish"
This is probably the cause of the code not working.
Perhaps you should show us the caller code instead of the handler code. Most likely what you're dealing with is the JS not being run during the AJAX call - the PHP page processing is server side.
You could look into sending the form using PHP Curl instead of JS? That would probably address the issue where it works loaded directly, but fails when called from another page.
As far as I understood, that HTML is being loaded through AJAX, right? If so, then window.onload will not be fired since the page was already loaded (AJAX doesn't count). Just do this:
<script type="text/javascript">
document.getElementById('publish').submit();
</script>
EDIT
To break this down:
Your code on SourcePage.php(I made up this name for reference) is posting data to process.php via an AJAX request
process.php then injects "title" & "wrapper" into the html markup and returns html with some javascript to SourcePage.php
You're then expecting that displaying the resulting string (msg) of the returned html on SourcePage.php will get the javascript in that string to execute.
To get this working, you'll need to do a few things.
Parse out the incoming javascript from the html.
Inject the incoming parsed HTML into SourcePage.php's markup.
Pass the parsed out JavaScript into JavaScript's eval function.
Doing this should bring the page from the process.php and successfully execute the JavaScript code on SourcePage.php.
If you were expecting that the JavaScript would run on the server, then I'm afraid you're mistaken as the server(php runtime) will not execute the JavaScript on the server. Perhaps a redirect on the server will accomplish your goal (whatever that may be).
Original
Try this out: http://jsfiddle.net/NiceGuy4263/eJLMS/
Related
I have a form on a page that needs to call a php script on my website's server (it's below web root), and it also needs to call an external jsp script hosted on another website's server. I know I can't just put two items into the <form action="..." but I can't figure out a way to get this done. Both scripts need to receive the variables submitted by the form.
Edit: I've made a mistake here. I'm sorry, but I thought it was javascript, and it's actually JSP. I've modified my post to fix all the places where I mentioned javascript.
you don't post to a "javascript file". javascript needs to be hosted in html. So I don't know if you need to INCLUDE the js file in your html file, and call a function, or if you actually meant post to another hmtl file on another server.
to specifically answer, you can make 2 forms and submit each one of them.
with jquery you can create a form dynamically and submit it. use post as the method, not get.
$('<form>', {
"id": "getInvoiceImage",
"html": '<input type="text" id="componentInvoicId" name="componentInvoicId" value="' + componentInvoiceId + '" />',
"action": window.siteRoot + 'ComponentInvoice/GetInvoiceImage/'
}).appendTo(document.body).submit();
you can add onclick event handler to the submit button, and include there all the javascript you need to perform before submission.
hope that helps.
UPDATE:
after you modified your question i realise you want to post to 2 server endpoints from the same client / webpage at the same time.
in this case i suggest you to:
not using a <form>
include jQuery
as following:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(function(){
$('#btnSubmit').click(function(){
// set urls
var url1 = 'http://php.url.com',
url2 = 'http://jsp.url.com';
// prepare data
var data = {
'field1' : 'val1',
'field2' : 2
}
// prepare callback (one callback for both requests)
var callback = function(data) {
console.log('request ended with data: ' + data);
}
// send post requests to both servers with the same data payload
$.post(url1, data, callback);
$.post(url2, data, callback);
});
});
</script>
<input type="button" id="btnSubmit" value="Submit" />
with this approach, click on button will send 2 async post requests, one to each server endpoint you set.
hope that helps.
I am trying to create a button on my chat that will allow someone to print the conversation. So I made the button that runs a PHP script that creates a new file, writes the conversation to file, and also writes the following jQuery.
jQuery AJAX Call
function OnBeforeUnLoad () {
$.ajax({
type: 'GET',
url: 'deleteFile.php',
data: {
pageName: ".$pageName."
},
dataType: 'text',
success: function(data){alert('Good bye 1!');}
});
return;
}
HTML Put into page
<br/><br/><form method="get" action="deleteFile.php"> <input type="submit" value="Close this Window"/>
<input type="text" value="'.$pageName.'" name="pageName" style="visibility:hidden"/></form>
deleteFile.php
<?php
$pageName = $_GET['pageName'];
$fullURL = 'PrintPage'.$pageName.'.php';
unlink($fullURL);
echo '<script>window.close();</script>';
?>
When the page shows up and I click the "Close this Window" button it does exactly what I want. It deletes the file and closes the window. But I do not get the same results when I close the window (aka OnBeforeUnLoad()). I even tried triggering submit by giving the form an id of deleteFiles and then doing $('#deleteFiles').submit() and it still didn't work.
How do I get the AJAX to work within the OnBeforeUnLoad function?
The form calls the data pageName but the ajax calls it url.
You probably don't want to prefix and suffix the value with . characters either.
Feel like a dummy.... After making all those changes... I found out all I needed to do was add
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
to the header.
Because I was dynamically creating the page in php, I forgot I needed to readd the jQuery.
Always the small things.. Thanks everyone for the help.
I have a working PHP registration form that goes through $_POST[] requests to check user inputs.
Username length (3-20)
Username availability
Username /^[A-Za-z0-9_]+$/
etc.
Rather than have it take you to a whole new page to display errors, I want a live request to call for the errors from register.php so they will appear in a div on the registration.
<div id="errors">" . $usernameErrors . "</div>
I've been trying to read up on AJAX but have noticed most codes involve utilizing $_GET[].
What will I have to do to get my current forms integrated with AJAX?
My Current Basic Registration Form Logic:
<form method="post" action="register.php">
<input type="text" name="username" id="username" required />
$usernameErrors
</form>
And register.php contains all of the checks already.
If you're using jQuery, it's pretty simple.
<script type='text/javascript'>
$.post('/register.php',
{username: $('#username').val()
// insert values of other fields here
},
function(response) {
// update your div with errors
$('#errors').html(response);
})
</script>
You should invoke this code, for example, when user changes username in registration form. It will happen in background and update page asynchronously.
Your register.php script should, in this case, emit only errors, not the whole page, or you will see unexpected results. :-)
In order to simplify ajax, you can use jQuery (a very powerful JS lib).
Add jquery***.js to your project and refer it on your page:
<< script type="text/javascript" src="#js/jquery-ui-1.8.16.custom.min.js" />
Then, you create the javascript function that will make the ajax call.
On the ajax call, you specify the php file to call and the function to handle the return of php(callback). On this callback function, you add the error message to body.
function verifyForm(){
$.ajax({
type: "POST",
url: "register.php",
data: "username=NAME_GOT_FROM_FORM_&location=Boston"
}).done(function( returned ) { //the callback
$('#errors').html(returned); // add the string returned to div id=errors
});
}
So, the crux of the problem as you're asking it seems to be that you're (correctly) using a POST request on your register form, but your tutorials all want to use GET. Here's a discussion about the difference between the two methods:
http://thinkvitamin.com/code/the-definitive-guide-to-get-vs-post/
If you're actually registering the user with AJAX (rather than just validating) you should be submitting the AJAX request as a POST. If you're using jQuery, the answer has already been given. If you're not using jQuery, then look for the XMLHttpRequest object in your tutorial, and where its "open" method is called (reference here: http://www.w3.org/TR/XMLHttpRequest/). The first parameter of that function is a request method--change it to "post" rather than "get", and the request will be treated like a POST, which register.php expects.
That being said, it sounds like you just want AJAX to validate the form. In that case, GET is the correct verb to use--all you want to do with AJAX is check data against the database, not actually make a change to data. I would suggest that you actually write a new PHP script like validate_registration.php that will perform only the validation logic in register.php, and then return a JSON array of errors (which would be empty if no errors occurred). You can activate/deactivate your form submit button based on that return value, and let the user submit the form just like your old workflow if everything is okay.
The tl;dr here is that you should read up on what makes $_GET and $_POST different, and then write an AJAX-specific validation script so that you're separating the data-retrieval part of your process from the data-insertion part. Once you understand the difference, the rest should follow.
I am using php/ajax to submit a form without page refresh. Here are my files-
coupon.js
jQuery(document).ready(function(){
jQuery(".appnitro").submit( function(e) {
$.ajax({
url : "sms.php",
type : "post",
dataType: "json",
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
//return false or
e.preventDefault();
});
});
sms.php
<?php
//process form
$res = "Message successfully delivered";
$arr = array( 'mess' => $res );
echo json_encode( $arr );//end sms processing
unset ($_POST);
?>
and here is code for my html page -
<form id="smsform" class="appnitro" action="sms.php" method="post">
...
</form>
<div id="mess" style="background:green;"></div>
Now instead of submitting form through ajax without page refreshing what is happening is that page gets redirected to
baseurl/sms.php and the only thing visible on page is
{"mess":"Message successfully delivered"}
My guess is that php script is not returning back successfully to the jquery and hence the echo in last part of sms.php is getting displayed. How should i make the php script return successfully?
ANY IDEAS HOW TO DEBUG THIS.I HAVE TRIED USING return false at the end of coupon.js but no results.
When i click on submit firebug gives following results -
POST http://174.132.194.155/~kunal17/devbuzzr/wp-content/themes/street/sms.php
404 Not Found 1.29s `jquery.min.js (line 130)`
Response
Firebug needs to POST to the server to get this information for url:
http://174.132.194.155/~kunal17/devbuzzr/wp-content/themes/street/sms.php
This second POST can interfere with some sites. If you want to send the POST again, open a new tab in Firefox, use URL 'about:config', set boolean value 'extensions.firebug.allowDoublePost' to true
This value is reset every time you restart Firefox This problem will disappear when https://bugzilla.mozilla.org/show_bug.cgi?id=430155 is shipped
#Fanis It's irrelevant whether he uses '$' or 'jQuery', they are synonyms.
#Ayush
As Fanis says, you should try Firebug if you don't use it already.
I've checked the example at my server, works OK, and I don't know
what's the problem at Your side.
You can use onsubmit="return false" to disable form submission:
<form id="..." class="..." ... onsubmit="return false">
Also check if javascript is enabled, for example do "alert('something')"
at $(document).ready
Edit:
// instead of
url: "sms.php"
// try
url: "/~kunal17/devbuzzr/wp-content/themes/street/sms.php"
// although I don't really know if it will help
If you're being redirected to sms.php instead of doing an ajax call, it probably means that there's something wrong with your jQuery code, probably the event binding itself.
I'm not sure without testing it, but shouldn't that code be:
$(document).ready(function(){
$(".appnitro").submit( function(e) {
$.ajax({
...
?
Check the javascript console, either in Firefox/Firebug or Chrome-IE/Developer Tools. Does it show any errors in those lines?
Fanis and Michal Kluczka are probably right about the issue with event binding , I tried your code myself as well, and it works for me.
Put an alert('X') as the first statements in your jQuery(document).ready() and jQuery(".appnitro").submit() functions and see if both are displayed (first one upon document load, second one upon form submission).
One more thing: I suggest you include a
header('Content-Type: application/json');
into your sms.php file before printing your JSON data to protect against cross-site-scripting (XSS) attacks. See also Don’t serve JSON as text/html for details.
i am using the following jquery to post comments to user_submit.php
var submit = document.getElementById("submit_js");
var comment = document.getElementById("comment");
$("#submit").bind('click', function(){
$.post("user_submit.php", {
comment: $("#comment").text()
});
});
the user_submit.php listens like:
$comment = htmlspecialchars($_POST["comment"]);
i can see in the Firebug console that there is no POST happening. only a single GET that i use for a different function (can this be the culprit?)
Assuming:
<input type="text" id="comment">
<input type="button" id="submit_js">
you want:
$(function() {
$("#submit_js").click(function() {
$.post("user_submit.php", {
comment: $("#comment").val()
});
});
});
PHP:
<?php
$comment = $_POST['comment'];
//...
echo htmlspecialchars($comment); // nothing catches this currently
?>
You also seem to be confusing "submit" and "submit_js" in your code. I'd advise against mixing Javascript and jQuery code unnecessarily too (the "getElementById()" business). You should familiarize yourself with jQuery selectors. For example:
$("#submit_js")
will create a jQuery object with all the elements (which should only be zero or one elements) with the ID of submit_js.
Remember that you're posting via AJAX, so even if you're echoing back the field value, it won't show on your screen unless you're listening for it in the $.post callback.
To check what the problem may be, submit the form normally without jQuery. If your PHP script is echoing back the field value, then the PHP script is working - check your JavaScript. If the you're getting blank, or empty array when using print_r(), then make sure the field name in your form is the same as what you're using in the PHP script.
Don't want you to have to rewrite your code, but here's what I recommend to do.
<form class="comments" method="post" action="user_submit.php">
<input type="text" name="comment" />
<input type="submit" value="Submit" />
</form>
JavaScript:
$('.comments').submit(function() {
var $form = $(this);
$.post(
$form.attr('action'),
$form.serialize(),
function(data, status) {
console.log(data);
}
);
return false;
}
This will submit your form to the PHP script. In the callback function, "data" is the returned data from the PHP script. So if you echo the field value back, the Firebug console will display the value.
In the event the user's browser has JavaScript disabled, the form will still submit properly. Of course your PHP script would have to check if the form was submitted via AJAX so that it can process properly depending on the request method. An easy way to test is to check for the X-Requested-With header. If it was sent via AJAX, the value would be XMLHttpRequest.