It was working before and I do not remember changing anything. I have a form and it sends the info to a "processing" php file and should get a response back. Instead, it just goes to the "processing" php and echoes the JSON data on a new page. Jquery is including from google and the form page and "process" page are both in the same directory.
$data = array(
'status' => $status,
'message' => $errorMsg
);
echo json_encode($data);
if ($status == "success"){
session_destroy();
}
exit();
So that is what it does at the end of all the processing (making sure data is good and all that which works just fine). This is the javascript used:
$(document).ready(function(){
$('#signupForm').submit(function(){
//various client side checks to keep form from submitting easy to see garbage
if($(this).data('formstatus') !== 'submitting'){
var responseMsg = $('#response');
responseMsg.hide()
.addClass('response-waiting')
.text('Signing Up...')
.fadeIn(200);
var dataString = //the data
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
success: function(data) {
var responseData = jQuery.parseJSON(data),
messageClass = '';
switch(responseData.status){
case 'error':
messageClass = 'response-error';
break;
case 'success':
messageClass = 'response-success';
break;
}
responseMsg.fadeOut(200,function(){
$(this).removeClass('response-waiting')
.addClass(messageClass)
.text(responseData.message)
.fadeIn(200,function(){
setTimeout(function(){
responseMsg.fadeOut(200,function(){
$(this).removeClass(messageClass);
});
},5000);
});
});
}
});
}
return false;
});
})
If there is something specific I should look for please let me know and I will update. qand like I said, I had it working (yesterday) and I do not remember changing anything except taking out a client side check at the top which I know should not matter at all.
A few things might help is solving this.
The first is that it's recommended not to use return false to stop usual on click events from happening.
It's best practice to at the top of the function do
preventDefault();
see http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/
This should stop the form from submitting and therefore loading the post page instead of doing the ajax call.
The second issue is that you have a return false call which is obviously not being hit. The above fix will stop the form from submitting no matter what but I'd guess that you have a javascript error in the code between the start and the return false. This will throw an exception and therefore return false will never be called. Once the above fix is put in and it stops redirecting, check your console in your browser for the exception.
Cheers
I assume your form action is heading process.php and you are not returning false on submit.
It should be like this
<form name='myForm' action='nonjspage.php' method='post' onsubmit='return false;'></form>
If the error still continues, then its not your form but an error in the javascript. Depending on what browser you are using there is an error console.
In firefox you head to the menu -> web developer -> web console.
Once you have opened this, reload the page and press the submit button again, it should give you information about your javascript error.
Related
I've seen a lot of examples of the same but it just doesn't work for me! I really don't know what is wrong with my code. When I perform a post via
window.location.href = "teste.php?name=" + javascriptVariable;
it work perfectly, but sadly, reloads the page, and I really don't want it.
So the only solution I've seen was to do it via jQuery. So here is what I am doing.
<script>
function opa() {
//var javascriptVariable = "John";
//window.location.href = "teste.php?name=" + javascriptVariable;
//alert (dataString);return false;
var dataString = "axius";
$.ajax({
type: "POST",
url: "http://localhost/teste.php",
data: {
name : dataString
},
success: function() {
alert("postado!");
}
});
return false;
}
function opa2() {
alert("<?php
if(isset($_POST['name'])){
$value = $_POST['name'];
} else {
$value = "NotWorking";
}
echo $value;
?>");
}
</script>
<button onclick="opa();"> AperteOpa1 </button>
<button onclick="opa2();"> AprteOpa2 </button>
The POST works PERFECTLY, when i see it at the web console at Firefox, it happens pretty well, and i can see the values at the parametters. I think the problem is with the PHP that don't recognize the data. I've tried to perform POST request trough
xmlhttp.open();
but it didn't worked too, same problem, the post happen, but the php don't recognize...
what's wrong with the code?
Your code does work, But it never gets called.
The ajax call doesnt reload the page, So when the page was processed, there was no $_POST['name'] there.
The ajax version of the page will have that variable set, but the one your currently running in does not.
Your process is
GET PAGE => => show post name
AJAX Request => Post =>
It should be
GET PAGE =>
AJAX Request => post => show post name
As you can see, The Ajax request doesnt touch the post name in your version. You need to get the data from the ajax request and then do something with that. Not the original page version
Your post should return something javascript can parse, Either plain text or JSON
The problem is that the page is generated by PHP first while the POST variable isn't set. The ajax request does not cause the page to reload, so it doesn't get regenerated, so this code never sees the submitted data.
I'm not sure what you're really trying to accomplish, so I can't suggest the proper way to fix this, but it seems you have an incomplete understanding of how and when server side and client side processing happen.
The problem is that you are posting to a different script (teste.php) and not the same script you are trying to run the javascript from.
While some say that you can't mix PHP and Javascript, I disagree. PHP happens before (on the server side) so your intuition was ok. The only problem is that the $_POST will not contain any value (unless you access it from teste.php).
You need to send the data back from the php file to the success function:
success: function(response) {
alert(response);
}
Also, just for general information, I'd rather replacing
if(isset($_POST['name'])){
$value = $_POST['name'];
} else {
$value = "NotWorking";
with
$value = isset($_POST['name']) ? $_POST['name'] : 'NotWorking';
It is much cleaner!
Hope this helps!
I have the following function that is called when I click on a button to submit a form:
function dadosFormularios(preenchimentoForm){
//var path = document.location.pathname;
//alert(path);
alert(preenchimentoForm);
//window.location.href = 'wp-content/themes/template/index.php';
var qstringA = '';
//dados dos campos
var nome=document.getElementById("nome").value;
qstringA = 'nome='+ nome;
//alert(qstringA);
if(preenchimentoForm==false){
alert('Please correct the errors in the Form');
}
else{
if(preenchimentoForm==true){
window.location.href = 'index.php?'+qstringA;
return false;
}
}
}
Since I'm using this way of processing the data, how can I alert my page index.php that the data sent by the function arrived on the index? I can't use a if (isset($_POST['button']..) since I send the information by the function and not through the button of the form, right?
window.location.href = 'index.php?'+qstringA;
This line is just redirecting to index.php with a query string ?nome=nome_value.
For example. index.php?nome=nome_value
So, in your index.php You can simply get everything posted with $_GET.
Check it by doing a print_r($_GET); there.
In index.php, you can simply check
if(isset($_GET["nome"])){
//Nome is set
//Do something here
}
P.S. Although, without knowing the other circumstances or reasons behind usage of this function, it can be said that this function is just doing what a simple <form action=index.php> would have done.
P.P.S. Although you have mentioned jQuery in title and also tagged it, I am not sure this function is using any of the jQuery code. I think it is just a simple Javascript function.
If you're using jQuery, check out .ajax(). Just remember, it's asynchronous, so the results may not be what you think they are. You don't need to reload the whole page (which is what your window.location.href = 'index.php?'+qstringA; would do) just to submit information.
If you want to alert or something when the ajax call completes, you can define a function to call on a successful ajax call.
Use ajax() like :
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
http://api.jquery.com/jQuery.ajax/
I am sending an email in jQuery and PHP, i need to tell the page to submit if the ajax was successful and don't submit if not.
I have tried to place the return values in the success and error attributes, but that did not work, so i want to see if i could set the form to not send by returning false but if it was successful letting it submit the page for some server side work.
In the example below i have tried to set a variable and used a conditional to read it. I get an error message because the value does not seem to get passed globally, so when the conditional reads sendMe, it says it is undefined.
Is there a way to do this correctly?
$.ajax({
type: "POST",
url: "send.php",
data: data,
success: function(){
var sendMe = 'true';
},
error: function(){
alert('Error: Message could not be sent');
}
});
if (sendMe == 'true'){
//Submit the page...
}
else {
return false;
}
just create a sendMe() function, and call that function from success:
That should do the trick.
The reason your code does not work is because the javascript is not waiting for the ajax call to come back, right after the ajax call it evaluates sendMe which at that point is still false.
You could consider doing this call synchronously of course to prevent that, but I am not sure that is the right way to go. ( async : false is deprecated as of jQuery 1.8 )
When is your conditional
if(sendMe == 'true') ...
ever getting called?
make a little function like this:
function sendMe(){
// whatever your form's id is, put it in place of myForm
$("#myForm").submit();
return true;
}
and in your ajax success block call the function
Try using this setup:
var form = this;
$.ajax({
type: "POST",
url: "send.php",
data: data,
success: function(){
form.submit(); // submit form, bypassing jQuery events
},
error: function(){
alert('Error: Message could not be sent');
}
});
return false; // prevent submit
By returning false after the ajax request, we prevent the submit, then we directly submit the form bypassing all of jQuery's submit handlers using form.submit();
Set the form to go through a validator method on submit event:
<form onSubmit='return checkForm();'>
</form>
In this method - checkForm() - perform your ajax post normally. If the ajax post returns as 'success' proceed with the submit else use return false; to cancel submit and notify the user accordingly.
Here is what I'm trying to do,
Capture my form submission post it to my ajax processing for form validation (without a page reload obviously)
then if the ajax server side doesn't return an array of errors (data in the code below) go ahead with the actual form submission. The 'return false' at the bottom of the snippet should prevent the jquery default behavior (which is to submit the form)
I've tried just return true if we don't get any errors but that doesn't work.
Any suggestions?
Here is what I got so far:
$('.submit').click(function(e) {
$.ajax({
type: "POST",
url: "/processform_ajax",
data: $(':input').serializeArray(),
dataType: "json",
success: function(data) {
if (data != '') {
$("#response span").html("");
$('.highlightbox').removeClass('highlightbox');
} else {
$('#myform').submit();
}
},
error: function(error, txt) {
alert("Error: " + error.status);
}
});
return false;
});
I handle this two different ways:
First, do front end validation with the wonderful Jquery Inline validation tool This step knocks out 95% of the problems before having to get tricky with PHP and Jquery.
Second, I submit my values from the form to the script. Let the PHP (in my case) do the "thinking" on validation. If it's incorrect, I return that information in a json_encoded string for the success function. I build a case (if data.valid == true for example) then display error flags. Else, do success steps and notify the user in the UI.
I think the key in your case is to ensure that the data coming back is json_encoded. FYI, I've noticed some very random issues with json_encode sometimes causing issues with the data return function due to square brackets, which are entirely valid but sometimes cause non-erroring faults.
Good Luck.
In my app, a user must be signed in to submit form info.
After a user clicks on the form submit button, my jQuery checks if a user is signed in.
If not signed in, then an error message pops up, requesting sign in/up.
I can now successfully stop the default action (submit).
However, how do I also allow the default action if the user is already signed in?
With my current code, the default action is also blocked if the user is signed in.
Here's my code:
jQuery('.member-only').click(function(event) {
var $element = jQuery(this);
var SignedIn;
jQuery.ajax({
type: 'POST',
url: '/ajax/member',
dataType: 'json',
success: function(data) {
var $err = jQuery('<div></div>')
.addClass('member-check')
.html(data.msg)
.css('left', $element.position().left);
SignedIn = data.SignedIn;
if (!(data.SignedIn)) { // not signed in
$element.after($err);
$err.fadeIn('slow');
return false;
}
}
});
jQuery('.member-check').live('click', function() {
jQuery(this).fadeOut('slow', function() {jQuery(this).remove(); });
});
if (!SignedIn) {
event.preventDefault();
event.stopImmediatePropagation();
return false; // block default submit
}
});
Thanks.
You need to let your JS function return false; to block the event's default action.
However, this doesn't cover users who have JS disabled or are capable to spoof it. So you should handle this gracefully in the server side as well :)
Update: As per your update, please add
alert(typeof Signedin);
alert(Signedin);
right before if(!Signedin) and tell what you get for both cases. It might be of the wrong type and/or value which is causing that you're always entering the if block and thus always returning false.
For example, a type of undefined will always cause !Signedin to evaluate true. You'd like it to be a boolean type all the time with values true or false.
This is a Moo question. Your not loged in user should have never seen a form that he can't submit in the first place.
Fix your PHP so as to not write a form that a non-logged in user can't submit.
$(form_id).submit(function(){ //triggered when user submits form
var signed_in = check_if_user_is_signed_in(); //checking
if(signed_in){ //singed in
//Do stuff
return true; //submit form
} else{ //user not signed in
//Do stuff
return false; //prevent form from being submitted
}
})
See if there is any user logged in . keep a flag for it. If flag is not set just disable the submit button . or just set the form action part using jquery only if flag is set.
Use event.preventDefault(); in your event handler. Return false only works in some cases (it's more of a workaround).
http://api.jquery.com/event.preventDefault/
https://developer.mozilla.org/en/DOM/event.preventDefault
I would also add an ajax request to check if user is logged in if your website often is opened in multiple windows.
Please review my modifications to your code. Let me know the datatype of the returned data.SignedIn; I added a console.log to return it to firebug.
My example takes action on the document being ready, as opposed to waiting for the user to interact, thus preventing the usability problem of showing the user that an ansynchronous call is happening in the background (the ajax spinner):
$(document).ready(function($){
var memberStatus;
jQuery.ajax({
type: 'POST',
url: '/ajax/member',
dataType: 'json',
success: function(data) {
console.log(data.SignedIn) //I need to know what format this is returned (Boolean: True/False?)
memberStatus = data.SignedIn;
}
});
if (memberStatus) { //if true, that means they are a member
//draw member box
} else {
$("#submitButtonID").attr('disabled',true);
}
});