I wonder whether someone may be able to help me please
Firstly, my apologies as this may be a very simple problem to the more seasoned developer, but this is my first website I'm building so please bear with me.
For my site I have a number of forms which all fit around a template I've created. Most forms require the user to click a submit button which then calls a PHP script to save the data into a MySQL database.
An example of code that I use to do this, is as follows:
<form id="addfinds" name="addfinds" method="post" action="savefinds.php">
When the form has been submitted, a line in my addfinds.php script then echoes either Find saved or There was a problem.
I'm working separately on some form validation to cleanse the data before submission, but what I'd like to be able to do is rather than the message being echoed from the PHP script, I'd like a pop up message to appear on screen in it's place, and if the submission is successful for the fields to clear and the page refresh.
I've done quite a bit of reading on this, and I'm a little unsure on how to progress this. I just wondered whether someone, perhaps with a greater experience than I could offer some guidance please or point me in the direction of a good tutorial.
function FUNCTIONNAME() {
$.ajax({
type: "POST",
url: "YOUR METHOD NAME WHICH IS CALLED",
data: "{PARAMETER VALUES TO BE PASSED}",
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function () {
},
success: function (msg) {
alert("YOUR SUCCESS MESSAGE HERE");
},
error: function (msg) {
alert("Error " + msg.d.toString());
}
});
}
Related
This question already has an answer here:
Wordpress: call to plugin php file via ajax
(1 answer)
Closed 6 years ago.
So I'm making a Wordpress site and want to send data (css styles dynamically created by jQuery) to PHP. The reason for this (not fully relevant to this question) is to write the data as a .css file that is loaded at the beginning of every page--making it so there's no visible 'change' of styles when js executes (well, only the first time the page is loaded). I'm sure there's probably a better way to do this.
But back to the main part (sending data from jQuery to a .php). I'm executing a js script (on "front-page.php") that does this:
jQuery(function($){
$(window).on("load", function() {
$.ajax({
type: "POST",
url: "create-style.php",
data: { style : styleString },
dataType: "json",
success: function () {
console.log("success");
}
});
});
});
The console says 'success', so I assume data is getting passed to create-style.php.
create-style.php's write function does this
$file = 'new-style.css';
$style = $_POST['style'];
file_put_contents($file, $style, LOCK_EX);
Now the first thing I tried was having the function included in Wordpress's functions.php. I don't know a lot about Wordpress or web development in general, but it seems intuitive that this wouldn't work since probably the php files get executed before the js (so how could it get the data?)
In an attempt to solve this I rewrite the create-style.php as a cron using wp_schedule_single_event to fire when someone visits the site, with a slight delay:
add_action('write_style_cron', function(){
// the above writing function
});
wp_schedule_single_event(time() + 10, 'write_style_cron'); // give it a slight delay to make sure jQuery happens
However, no $_POST data gets written to the file and doing any tests shows it's empty. I've done a lot of tests and know that:
cron functionality is basically working
the writing function works with test values
$_POST is showing as completely empty and I get an "Undefined index" error in the /wp-cron.php?doing_wp_cron
$.ajax is firing success
there are no other php / js errors
Thanks for reading this very long post. Been searching the internet all day for solutions and decided it might be best to just ask. I'd much appreciate any ideas.
Try using this code:
jQuery(function(){
$('#yourFormName').on('submit', function (e) { //on submit function
e.preventDefault();
$.ajax({
type: 'post', //method POST
url: 'create-style.php', //URL of page where to pass values
data: $('#yourFormName').serialize(), //seriallize is passing all inputs values of form
success: function(){
console.log("success");
},
});
}
});
I'm incredibly new to PHP, so I'll try and be as clear as possible. Through a bit of trial and error, I created a simple form on a website I manage where people can provide a few bits of information (about four lines total). In turn, I will receive an email using ()mail with the information, which I intend to use for remarketing purposes.
The problem? It takes a good 20-30 seconds for the person who filled out their info to be taken to the Thank You page. I still end up receiving the email, but people are definitely not going to wait around for the Thank You page to load before closing the window. This is obviously not good if I'm planning on tracking conversions.
Any suggestions? A friend suggested I set up a MySQL database to collect the info, but that's way beyond my level of expertise. Are there alternatives that can help?
Many thanks.
If the form submits to PHP you could use an AJAX script of which runs the PHP page. You can setup BeforeSend to show a div that simply says "Loading please wait..." and the user is more likely to wait. I'm not saying this is the best solution but its one.
AJAX Script:
<script>
$(document).ready(function() {
$('#submitBtn').click(function() {
var variable1=$("#variable1").val();
var variable2=$("#variable2").val();
var dataStr = 'variable1='+variable1+'&variable2='+variable2;
if($.trim(variable1).length>0 && $.trim(variable2).length>0) {
$.ajax({
type: "POST",
url: "process.php",
data: dataStr,
beforeSend: function(){ $("#submitBtn").val('Loading Please wait...');},
success: function(data){
if (data!="success") {
$("#submitBtn").val('Submit')
} else {
window.location.href = "http://example.com/thankyou";
}
}
});
} return false;
});
});
</script>
I've provided you with an AJAX example above. In the PHP script you simply need to get it to echo "success" if the email is sent. If the script ends and nothing is sent back or something else is echo'd then it will set the submit button back to "Submit".
I recommend you create a div below the submit button of which is empty by default or not visible but if the AJAX fails it is shown.
I want to begin by saying sorry for asking this question because I know this has been asked a lot on here already. I've search through the site and used Google, and looked at other examples but I can't figure out what's wrong. Running the script with FireBug running shows the POST is sent but nothing gets received. I've posted the code below.
Jquery Code:
$('#studio').submit(function (event) {
$('#formLaunch').click();
$.ajax({
url: 'test.php',
type: 'POST',
data: {
search_var: 'test'
},
dataType: 'html',
success: function (data) {
//$('#result').html(data);
alert(data);
}
});
event.preventDefault();
});
PHP Code:
<?php
$term = $_POST['search_var'];
echo $term;
?>
The end result of the code (once the AJAX request starts working) will process sent variables and echo an image which I want displayed in a DIV box on the page. For starters though just trying to get this basic 'shell' to work properly.
Thanks in advance for any help or direction.
Jeff
Always provide an error function, especially when in development. I suspect you have an error for a response (404, 500, etc). Providing an error function for debugging purposes will help you see this more quickly.
try this
$.post('test.php',{'search_var': 'test'},function(data){
alert(data);
});
Many websites have an "check availability" button. And I want to have this to. But this seems to be only available when using Ajax and Jquery. Is there any way for me to do this using only PHP and Javascript. Because i'm a starting programmer, which does not have the skills to work with Ajax or Jquery.
What I want, I have a username field. I typ in a username, and I want to check if the name is available. If the person clicks on the check availability button, I want a pop-up that says "This username is available" or "This username has already been taken".
If any knows how to do this in just PHP and Javscript, I would be very obliged to know.
Using ajax (and jquery) is easier than it seems. on your client-side you have a request like this:
$.ajax({
url: 'usernameChecker.php',
dataType: 'GET',
data: 'username=' + $("#yourUserNameFieldID").val(),
success: function(result)
{
alert(result);
}
});
Of course you need to include jquery to implement this. jQuery makes it easy to make ajax-calls.
On your serverside you can use something like this:
<?php
if(isset($_GET["username"]))
{
// check username
if(username_is_free)
// of course this needs to be a bit different, but you'll get the idea
{
echo "Username is free!";
}
else echo "Username is taken!";
}
?>
$(document).ready(function(){
// available-button is the ID of the check availability button
//checkAvailability.php is the file which gets the username param and checks if its available
// user is the id of the input text field where the user enter the username
// available-message is the id of a div which displays the availability message. Use this instead of alert
$('#available-button').click(function() {
$.ajax({
type : 'POST',
url : 'checkAvailability.php',
data: {
username : $('#user').val()
},
success : function(data){
$('#available-message').text(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("Some Error occured. Try again")
}
});
return false;
});
});
Use jQuery ajax, that is the best & easy way to do it.
Using Ajax send a request to a php page which will take username as parameter (get or post method, you can specify in ajax call) and then on server side search for uniqueness of username in database & return appropriate response.
Is there any way for me to do this using only PHP and Javascript.
Because i'm a starting programmer, which does not have the skills to
work with Ajax or Jquery.
I think you'll find making an AJAX request in jQuery a lot more simple than writing one in pure javascript.
As jQuery is an extension on Javascript, you can use minimal jQuery to make the request to the server, and then deal with the response using pure javascript.
Look into using jQuery AJAX:
http://api.jquery.com/jQuery.ajax/
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
Here you would change the success part to something like:
success: function(data){
if (data == 1){
$(".message").html("Available");
}
else {
$(".message").html("Already Taken");
}
}
I would recommend using jQuery for this task.
jQuery (or another Javascript library) will make the task simple to complete compared trying to do it without using one of them.
jQuery docs are good and for there are plenty of online tutorials matching what you want to do.
You will benefit from putting in the time to learn about the jQuery library.
I can't for the life of me figure out why this is happening.
This is kind of a repost, so forgive me, but I have new data.
I am running a javascript log out function called logOut() that has make a jQuery ajax call to a php script...
function logOut(){
var data = new Object;
data.log_out = true;
$.ajax({
type: 'POST',
url: 'http://www.mydomain.com/functions.php',
data: data,
success: function() {
alert('done');
}
});
}
the php function it calls is here:
if(isset($_POST['log_out'])){
$query = "INSERT INTO `token_manager` (`ip_address`) VALUES('logOutSuccess')";
$connection->runQuery($query); // <-- my own database class...
// omitted code that clears session etc...
die();
}
Now, 18 hours out of the day this works, but for some reason, every once in a while, the POST data will not trigger my query. (this will last about an hour or so).
I figured out the post data is not being set by adding this at the end of my script...
$query = "INSERT INTO `token_manager` (`ip_address`) VALUES('POST FAIL')";
$connection->runQuery($query);
So, now I know for certain my log out function is being skipped because in my database is the following data:
alt text http://img535.imageshack.us/img535/2025/screenshot20100519at125h.png
if it were NOT being skipped, my data would show up like this:
alt text http://img25.imageshack.us/img25/8104/screenshot20100519at125.png
I know it is being skipped for two reasons, one the die() at the end of my first function, and two, if it were a success a "logOutSuccess" would be registered in the table.
Any thoughts? One friend says it's a janky hosting company (hostgator.com). I personally like them because they are cheap and I'm a fan of cpanel. But, if that's the case???
Thanks in advance.
-J
Ok, for those interested.
I removed the full URL http://www.mydomain.com/functions.php
and replaced it with the local path functions.php and that did the trick.
Apparently AJAX has issues with cross domain ajax calls and I'm not on a dedicated server, so I imagine what's happening is every couple hours (or minutes) I am somehow hitting my script from a different location causing AJAX to dismiss the POST data.
-J
Try enabling error reporting on the jquery $.ajax function, your code would look something like
function logOut(){
var data = new Object;
data.log_out = true;
$.ajax({
type: 'POST',
url: 'http://www.mydomain.com/functions.php',
data: data,
success: function() {
alert('done');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus+" - "+errorThrown);
}
});
}
See if that sheds light on your situation.
I have a strong feeling that it's more of a server side issue rather than the client's.
The odd thing is that you see the problem for a period of time. If the client works at all, then at the minimum refreshing the page or restarting the browser should fix it.
The die() at the end of the function is suspicious, but I am not quite sure how it will affect it.
Btw you can see http headers in FireBug's Net tab, to know whether those parameters has been sent properly.