PHP $_POST not working as expected - javascript

In one of my form i have a dropdownlist control on whose "onchange" event i am populating two textbox controls as shown below:
function pop_mli_n_murl(){
var wd_pid = document.getElementById("ddlUnder").value;
var dataString = 'wdpid='+ wd_pid;
$.ajax({
type: "POST",
url: "ldd_pop_wd_pdata.php",
data: dataString,
cache: false,
success: function(result){
var v1= result.substring(0,result.indexOf('='));
var v2= result.substring(result.indexOf('=')+1);
$("#txtMLI").val(v1);
$("#txtMLIURL").val(v2);
}
});
}
Up until here everything works fine. However when i submit the form, $_POST['txtMLI'] and $_POST['txtMLIURL'] is not set while the others are. Can you tell what could be the problem??

You probably forgot to prevent the NORMAL form submission, so your ajax request gets terminated. If the ajax call was succeeding, the ONLY form value you should ever receive would be $_POST['wdpid'], because that's the only thing your ajax code tries to send.
Getting the OTHER form values means the normal form submission occurred, NOT the ajax call.
That means you need something like
<form ... onsubmit="return pop_mli_n_murl()">
...
function pop_mi_n_murl() {
... ajax stuff ...
return false; // return false to onsubmit handler, terminating the normal submit
}

When you submit the ajax you're not posting txtMLI or xtMLIURL, you're only sending wdpid.
The data in the ajax should be something like
{
'wdpid': 'value here',
'txtMLI': 'value here',
'xtMLIURL': 'value here',
}
Then on the server side you'll be able to access those variables from the ldd_pop_wd_pdata.php script.

Related

pages keep refreshing after call javascript function returned from ajax response

I have tried most answers about call javascript function returned from ajax response. Every answer worked but I must call alert to show the ajax response to see the result.(If not use alert in the function refreshResults, sometime the result will show but disappear immediately) It seems the page keep refreshing.
Here is the screenshot.
I already tested the browser can receive data successfully from the server. The problem is how to show the data from the browser side.
Here is the code related to receive data from the server and how the server return data.
ajax
function sendAjaxQuery(url, data) {
$.ajax({
type: 'POST',
url: url,
data: data,
success: function (data) {
//eval(document.getElementById("refreshResults").innerHTML);
refreshResults(data);
//$("#firstname").text(data);
// alert('success '+data);
}
});
}
This is how I send data to server.
sendAjaxQuery('http://localhost:3000/results.html',JSON.stringify($('form').serializeObject()));
js
<script type="text/javascript">
function refreshResults(data){
$("#firstname").text(data);
alert(data);
}
</script>
The server side is nodejs. (The server side return a string. Status is 200). The http header is
"Content-Type": "text/plain",'Access-Control-Allow-Origin': '*'
This is the click handler.
function sendData() {
var form = document.getElementById('myform');
sendAjaxQuery('http://localhost:3000/results.html',JSON.stringify($('form').serializeObject()));
}
var sendButton = document.getElementById('sendButton');
sendButton.onclick = sendData;
This is the according html
<form id="myform">
<input type="text" name="Search" value="">
<button id="sendButton" >Search</button>
What is the whole point of the sendAjaxQuery method ?
It just recreates what the $.post does
Just use
// url and data should be whatever you pass to sendAjaxQuery now
$.post(url, data, refreshResults);
whenever you want to make an ajax call..
Update Seeing that you are submitting the contents of a form, the problem might be that you allow the form to be submitted the normal way as well (which causes a refresh of the page).
You will need to cancel the normal action of the button that started this action..
Since you are using jQuery, it is better to use that for binding the event handlers
change
var sendButton = document.getElementById('sendButton');
sendButton.onclick = sendData;
to
$('#sendButton').on('click', function(e){
e.preventDefault();
sendData();
});

Posting to same page with jquery.ajax, no vars passing.

I'm grabbing the onclick event for a specific #id and then sending the relevant form data to the same page( to itself ), checking to see whether $_POST['submit'] is set, if it is I'm sending an email.
It I don't get any errors but I get no data sent via post it seems.
<script>
$(document).ready(function(){
$('#login').keyup(username_check);
$('#clickarea').click(submit_form);
});
function submit_form(){
var login = $('#login').val();
var comment = $('#message').val();
var spt = $('#spam_prevention_test').val();
var submit = #('submit').val();
alert('You got here'); <-- Yes i get the alert so its making it to the function
jQuery.ajax({
type:"POST",
url: "sign_up.php",
data: 'login='+ login+'message='+ comment+'spt='+ spt+'submit'+ submit,
cache: false
});
}
</script>
I tried setting submit to .val, to 1, to "1" thinking it just needed to be set to something.
I did a quick echo in the header to see if I'd get any of the var's and no I don't.
echo "Var" . $_POST['login']; <-- just returns blank
if(isset($_POST['submit'])) { <-- never makes it into here.
What am I missing here, is there something special I need to do to pass back to the same page?
You need a success handler function that will read the response to the HTTP request made by $.ajax and do something with it.

Post form to web2py function using ajax

The server is written in web2py, and hosted on google app engine. I can visit my index.html by entering domain.com/index and I can send form by entering domain.com/register where "register" is a function defined by default.py
However, in html, where I would like to send form to the server and get a response, I use ajax which has cross domain issues. So I use "register" as URL, and it does not work. Help?
$("#signup").click(function() {
$.ajax({
type: "POST",
url: "register",
data: $("#formsignup").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});
return false; // avoid to execute the actual submit of the form.
});
By typing domain.com/register, I can totally trigger the function. What is the problem here? And the form is sent to domain.com... In browser it appears as htt[://domain.com/?email=ada#ad.com&password=adsa
Its very possible register is looking for GET instead of POST
try changing the type in ajax
$("#signup").click(function() {
$.ajax({
type: "GET",
url: "register",
data: $("#formsignup").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});
return false; // avoid to execute the actual submit of the form.
});

How to continue form submission after an AJAX call?

I want to validate user entries on a WordPress post upon hitting the submit button, display an error message is there are problems, and submit the form if everything is OK. I have a PHP function that does the checking, returning true if data in form_data is OK, some error code otherwise. The following JavaScript issues the AJAX request, and was supposed to continue submitting the form upon successful checking, but it doesn't:
jQuery(document).ready(function() {
jQuery('#post').submit(function() {
var form_data = jQuery('#post').serializeArray();
var data = {
action: 'ep_pre_submit_validation',
security: '<?php echo wp_create_nonce( 'pre_publish_validation' ); ?>',
form_data: jQuery.param(form_data),
};
var proceed = false;
jQuery.post(ajaxurl, data, function(response) {
if (response.indexOf('true') > -1 || response == true) {
proceed = true;
} else {
alert("Error: " + response);
proceed = false;
}
});
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
return proceed; //breakpoint here makes the code run
});
});
The code is adapted from a WPSE question, which originally didn't work for me as the form didn't get submitted. I found out that if the jQuery function bound to .submit() returns true, the form should be submitted, so that's what I tried to implement. With the code above, it doesn't seem to work at first (form doesn't get submitted when there are no errors), but upon close inspection with Firebug proceed seems to get the right result if a breakpoint is inserted at the return proceed line. It works as intended with valid data only if I wait it out a bit upon hitting the breakpoint, and then continue execution. If there are errors, the alert is issued without a problem.
What is the best way to handle this?
EDIT
Based on #Linus answer below, the following code works with both valid and invalid data:
jQuery(document).ready(function() {
jQuery('#post').submit(function() {
if(jQuery(this).data("valid")) {
return true;
}
var form_data = jQuery('#post').serializeArray();
var data = {
action: 'ep_pre_submit_validation',
security: '<?php echo wp_create_nonce( 'pre_publish_validation' ); ?>',
form_data: jQuery.param(form_data),
};
jQuery.post(ajaxurl, data, function(response) {
if (response.indexOf('true') > -1 || response == true) {
jQuery("#post").data("valid", true).submit();
} else {
alert("Error: " + response);
jQuery("#post").data("valid", false);
}
//hide loading icon, return Publish button to normal
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
});
return false;
});
});
Short answer: You can't - not in this manner.
Some background: The callbacks you supply as arguments to functions such as $.post are executed asynchronously. This means that you will return proceed before your success callback has been executed, and proceed will always be false. With your breakpoint, if you wait until the success callback has executed, proceed will be true and all will be well.
So, if you want to submit the form after your ajax request has finished, you must submit it using javascript. This is pretty easy with jQuery, just do a jQuery $.post with data: $("yourForm").serialize() and url: yourForm.action.
This is basically what you already are doing, you just have to repeat that call to the URL to which you actually want to post the data.
EDIT:
Another way would be to set an attribute on your form, say valid, and in your submit handler check that:
jQuery("#post").submit(function() {
if($(this).data("valid")) {
return true;
}
// Rest of your code
});
And in the success callback for your validation ajax request you would set/clear that attribute, and then submit:
$("#post").data("valid", true).submit();
EDIT:
You also want to do your "ajax-loading"/button enabling inside the callback for $.post for the same reasons stated above - as it is, they will happen immediately, before your ajax call returns.
Bind your button to a validation function instead of submit. If it passes validation, call submit().
Wordpress has its own mechanism to process Ajax requests, using wp-admin/wp-ajax.php. This allows you to run arbitrary code on either side of the Ajax boundary without having to write the back and forth status-checking code and all that. Set up your callbacks and go....
The real question is - why are you doing validation server-side? Why can't you load in the validation criteria before - as the post is being written? Then your validation can happen real-time and not on-submit.
jquery.post is performed asynchronously, which means the JS will continue before it gets the reply. You're stuck with Diodeus's answer - bind the button to validtion which then submits the form (which makes it not degrade well), or change your $.post to ajax and turn off async, which will force it to wait for response before proceeding...possibly locking up JS on your page until it times out.
$.ajax({
type: 'POST',
url: ajaxurl,
async:false,
data: data,
timeout:3000,
success: function(){
}
});

How to send post with jquery onsubmit but still send form

I want to trigger this function, which uses the jquery's post method, when a form is submitted:
function update_point_session(){
$.post('/update_point_session/',
{session: true},
function(data){}
);
return true;
}
I uses the onsubmit to trigger it.
The problem is that it won't send it when the form is submitted. But if I return false; it will (though the form itself, of course, will not). It looks as if the $.post is not send before the page is directed to another one by the form..
So I think I somehow have to return true; AFTER the $.post. I tried to do this by putting it inside function(data){} but it did not work..
How can I send BOTH the post from jquery and from the form?
There are a couple of things you can do.
Make the AJAX synchronous
Since $.post is, according to the documentation, equivalent to
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
dataType: dataType
});
You can simply replace $.post with the equivalent $.ajax call, and also add async: false to the options. This will submit the form with AJAX and then, due to the return true; from the function, will also let the browser post the form normally.
Submit the form only after the AJAX completes
This involves some event handler juggling:
// attach submit event handler to the form
$("#myform").submit(function() {
// Handler immediately detaches itself, so that
// we don't have an infinite loop when we call
// $(this).submit() ourselves below
$(this).unbind('submit');
// Do the AJAX
$.post(
'/update_point_session/',
{session: true},
function(data){
// When the AJAX completes, tell the browser
// to re-submit the form
$(this).submit();
}
);
// Prevent the browser from submitting it NOW,
// because the AJAX is still running
return false;
});
You must wait for the asynchronous post to complete before unloading the page. You can send back a redirect url from the server as json something like this:
$('form').submit(function(e){
$.post(this.action || '/update_point_session/', $(this).serialize(), function(data){
// send back a redirect url from the server
if(data.url) location.href = data.url;
});
e.preventDefault()
});
I would do something like this.
$('form#myFormId').submit(function(evt){
var form = $(this);
evt.preventDefault(); // Prevents default submission
$.post('/update_point_session/', {session: true}, function(data){
form.unbind('submit'); //Unbind js submit event
form.get(0).submit(); //submit the form
});
});

Categories