PHP never receives nested jQuery $.post data - php

I'm trying to send simple form data from my index page to a PHP function, checklogin.php. What I'm finding is that no data, serialized or even direct input, is getting through to the PHP function. I know for a fact that the jQuery function is getting called, and I also know that the PHP file is called because I've put various post functions in.
When I submit data directly from the form using action="checklogin.php" the $_POST data is correctly received and I can process it. However when using jQuery to intercept the form submit, no data is received.
One thing to note is that the actual login form HTML is inserted from another page, to allow me to work on multiple pages instead of one big index file.
Form - login.php
<form id="loginform" name="loginform" method="post">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Member Login</strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="username" type="text" id="username"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="password" type="text" id="password"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
Submit event hook - Index.php
$( document ).ready(function() {
$.post("login.php", function(data) { // retrieve login form from other page.
$("#page5").html(data);
$('#loginform').submit(function () {
event.preventDefault();
var formData = $(this).serialize();
console.log("Form Data: " + formData); // this is not blank
$.post("checklogin.php", formData, function(data) {
// post-login actions
})
});
});
})
});
checklogin.php (temporary until is problem resolved)
<?php
print_r($_POST);
?>
As I said, even direct input such as "username=test$password=blah" instead of 'formData' results in an empty $_POST array. I've also tried using the ajax equivalent post call with no luck.
JavaScript Console Output
// console.log line above $.post
Form Data: username=test&password=blah
// Result from PHP print_r
Array
(
)

Use .on()
As elements are added dynamically you can not bind events directly to them .So you have to use Event Delegation.
$(document).on('submit','#loginform',function () { //code here }
or better use
$('#page5').on('submit','#loginform',function () { //code here }
Syntax
$( elements ).on( events, selector, data, handler );

Related

PHP AJAX JSON - Convert Input to JSON and Other PHP File Get The Value

I noob and get mad when submit php form, convert input value to json, and other php file get it.
html
<form action="submit.php" method="post" name="form1" id="myform">
<table width="100%" border="0" style="font-size: 65px;">
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name"></td>
</tr>
<tr>
<tr>
<td></td>
<td><button id="submit">Submit</button></td>
</tr>
</table>
</form>
<script src="script.js"></script>
script.js
$('#myform').submit(function (event) {
name = $('#name').val();
var data = {
name: name
}
$.ajax({
type: "POST",
url: 'submit.php',
contentType: 'application/json',
data: JSON.stringify(data),
dataType: 'json'
});
return false
});
php file
header('Content-Type: application/json');
$name_dirty = json_decode($_POST['name']);
echo $name_dirty;
Can someone help me? submit.php got blank, I cant get the value that I submit from html page. Big Thanks
Your Html
<table width="100%" border="0" style="font-size: 65px;">
<tr>
<td>Name</td>
<td><input type="text" name="name" id="name"></td>
</tr>
<tr>
<tr>
<td></td>
<td><button id="submit">Submit</button></td>
</tr>
</table>
<script src="script.js"></script>
Your JS
$('#submit').click(function() {
name = $('#name').val()
var data = {
name: name
}
$.ajax({
type: "POST",
url: 'submit.php',
data: data
dataType: 'json'
complete: function (resultData) {
alert('data has been send')
})
})
In your php:
<?php
print_r($_POST['data'])
A few notes. Make sure you check your paths. In my answer i assumed that the problem is in the code and not in wrong paths. Also when you use form tag you can use a submit button like <input type="submit" value="Submit"> to submit your form without using Javascript. It would work in your case but it's just another way to tackle your issue.
In my answer i removed your form tags and triggered the action on button click. There will be no redirect to the page but you can set a redirect inside the js if it is important to you, on success function of the ajax that i added. At the moment i just throw an alert message when it works successfully.

data received through JQuery, php, mysql is not working

On entering the customer name in textbox it searches for customer info. I have generated successfully using JQuery by passing the entire table through Json variable, as I dont want any page refresh. Now I want to select the customer id generated from mysql db (php) through radio button, but the radio button event is not working. For testing purpose I have put a static table having the same radio button properties in that particular div(place for dynamic record generation using JQuery) and working fine. Hence I found that the data received through JQuery got some problem. Hope I am clear. Please find a way. Thanks in advance.
below is the code
abc.php
<input type="text" placeholder="full name" id="fullName" name="fullName" class="txt" style="width: 250px" /> 
<input type="button" id="btSelect" value="Select" class="button-crystal" />
<div id="disp"></div>
script.js
$('#btSelect').click(function () {
var form_data = {
genCustDetails: $('#fullName').val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: "xyz.php",
data: form_data,
dataType: "json",
success: function (response)
{
$('#disp').html(response);
}
});
return false;
});
xyz.php
if (isset($_POST['genCustDetails'])) {
$out="";
$result = mysql_query("select * from dbcustdetails where name like '$_POST[genCustDetails]%'");
while ($row = mysql_fetch_assoc($result)) {
$out.='
<table style="background-color:#eee; margin-bottom:5px;">
<tr>
<th class="td3">Customer ID</th>
<td class="td4">
'.$row["custID"].' <input type="radio" id="cust_ID" name="cust_ID" value="'.$row["custID"].'" />
</td>
</tr>
<tr>
<th class="td3">Name</th>
<td class="td4">'.$row["name"].'</td>
</tr>
<tr>
<th class="td3">Phone No.</th>
<td class="td4">'.$row["phno"].'</td>
</tr>
<tr>
<th class="td3">Email</th>
<td class="td4">'.$row["email"].'</td>
</tr>
<tr>
<td colspan="2" style="padding:0;">
<b>Address</b><br/>'.$row["addr"].'
</td>
</tr>
</table>';
}
echo json_encode($out);
}
Maybe You should'nt bind the event properly for the dynamic elements in the DOM.
Try Like this
$('body').on('change','.radiobuttonClassorID',function(){
//actions
});
that is because your newly generated radio button is not having any event handler assigned to it.
you have to assign an event handler after the ajax call (on ajax success).
something like
$('input[type="radio"]').unbind('click').click(function(){
//Your handler code
})

JQuery .submit() a FORM doesn't work

I'm increasing my system by entering the functionality of loading a page inside a div dynamically, in the other words, the central area of the page is updated. For this I am using the JQuery. But even I having a problem which is the following, when submitting the same FORM one has to load the next page via JQuery-Ajax to send the post to use the data on this second page.
The funny thing is that I'm not getting the pick. Submit() the FORM always and only in one case. I will post the HTML below the two situations:
In the html code below warning test that I created within the form.submit () is being displayed.
<form id="form" accept-charset="utf-8" name="frmPadrao" method="POST" action="HTTP://localhost/fwsibe/index.php/acesso/listarSistemasValidar">
<br>
<fieldset id="tabelainfo" style="width: 560px;">
<legend style="color: #083C06;">
<b>Dados</b>
</legend>
<br>
<table id="tabelainfo">
<tbody>
<tr>
<td>
<b>SIBE:* </b>
</td>
<td>
<select name="slSibe">
</td>
</tr>
<tr>
<td>
<br>
</td>
</tr>
<tr>
<td colspan="2">
<input class="button" type="submit" value="Confirmar" name="btConfirmar">
</td>
</tr>
</tbody>
</table>
</fieldset>
<br>
<br>
</form>
In the second code warning. Submit () is not displayed, or is not recognized submission form:
<form id="form" accept-charset="utf-8" name="frmPadrao" method="POST" action="HTTP://localhost/sibe/index.php/almembal/motivoajustealm/pesquisar">
<br>
<fieldset id="tabelainfo" style="width: 560px;">
<legend style="color: #083C06;">
<b>Filtrar por:</b>
</legend>
<br>
<table id="tabelainfo">
<tbody>
<tr>
<td>
<b>SubTipo Produto:* </b>
</td>
<td>
<select name="slSubTipo">
</td>
</tr>
<tr>
<td>
<br>
</td>
</tr>
<tr>
<td colspan="2">
<input class="button" type="submit" value="Confirmar" name="btConfirmar">
</td>
</tr>
</tbody>
</table>
</fieldset>
<br>
<br>
<div>
<a title="" onclick="window.open('HTTP://localhost/sibe/index.php/almembal/motivoajustealm/incluir', '_blank', 'width=800,height=600,scrollbars=yes,status=yes,resizable=yes,screenx=0,screeny=0');" href="javascript:void(0);">Incluir</a>
</div>
<br>
<table id="tabelainfo">
<tbody>
<tr id="corpotabela">
<td align="center">Não existem Motivos de Ajuste cadastrados para esta pesquisa.</td>
</tr>
</tbody>
</table>
</form>
Below the JQuery script that is already properly initialized in the HEAD of the page, in addition, already tested for other enventos as $ (this). Click and everything is ok.
$(document).ready(function() {
$("#form").submit(function() {
alert("SUBMIT FORM");
// alert($(this));
// console.log($(this));
// $.post($(this).attr("action"), $(this).serialize(), function(data) {
// $("#divCentral").html(data);
// });
// return false;
});
});
Could you help me find the bug that causes. Submit () is not recognized by JQuery?
Edited:
I already discovered the source of the problem. Looks like that when the component is drawn for a page loaded by jquery-ajax, the event .submit() doesn't works, but when the page is loaded for default away, the event works.
The problem is that the is loaded by Ajax, and the JQuery function don't recognize it. I'am creating the function for load the central page of the template by a ajax request to a file. I have two functions, the first just for test, and the second I'am creating for works with the $_POST. The JQuery function for now is well:
function carregaUrl(url) {
//alert("carregaUrl=" + url);
$("#divCentral").load(url);
console.log($('form').attr('name'));
}
function carregaUrl2(url) {
var data = $("form").serialize();
$.ajax({
type: "POST",
url: url,
data: data
}).done(function(data) {
$("#divCentral").html(data);
});
}
What is happening here, is that the handler fires, starts the alert, and then form submit occurs, effectively reloading your page.
You need your event handler to return false if you want to prevent this submit and stay on your current page, or add an alert to the page you're going with this submit.
If you want to stay on your current page, try this:
jQuery(function($){
function formSubmit(form) {
$.post(form.attr('action'), form.serialize(), function(data){
$("#some-outer-container-with-form").html(data);
});
$("#form").submit(function(){ return formSubmit(form) }); //we need to rebind
return false;
}
$("#form").submit(function(){ return formSubmit( $(this) ) });
});

Script catching image

I have this script,so it goes to ../AdsCreate/CreateCar.php reads the form and inserts into databse and loads page into a certain div which all works fine.
I have one problem one part of the form is to upload an image,now that it does not do I have been told it's because that script below serialize the data and does not do that for file based.
Here is the script.
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#Submit").click(function() {
var url = "../AdsCreate/CreateCar.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#myForm").serialize(), // serializes the form's elements.
success: function(html){ $("#right").html(html); }
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
Here is my form
<form method="post" enctype="multipart/form-data" id="myForm">
<table class="default1" style="width: 100%" align="center">
<tr>
<td class="content1" colspan="3"><h3><b>Car Ads</b></h3></td>
</tr>
<tr>
<td class="content1" width="70%">Make: <input type="text" name="name"></td>
<td class="content1" width="15%">Model: <input type="text" name = "email"></td>
<td class="content1" width="15%">Year: <input type="text" name = "phone"></td>
</tr>
<tr>
<td class="content1" colspan="3">Main Photo: <input type="file" name="photo"></td>
</tr>
<tr>
<td class="content1" colspan="3"><input type="submit" value="Upload" id="Submit"></td>
</tr>
</table>
</form>
How can I change the script so I can upload a form that also has a file upload??
You can upload file separately using this plugin:
http://blueimp.github.com/jQuery-File-Upload/
You can also use jQuery Forms to upload File:
http://www.malsup.com/jquery/form/#file-upload
Make sure to disable submit button once a file is selected so it will upload the image first before the user can submit the form.

mootools form json post request

i want to to a request.JSON on a dynamic form.
is it possible to POST the complete form via a form id ?
<table>
<form id="form">
<tr>
<td>username</td>
<td><input type="text" id="username"></td>
</tr>
<tr>
<td>password</td>
<td><input type="password" id="password"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" id="go" value="go"/></td>
</tr>
</table>
and on the script side:
$('go').addEvent('click',function( event )
{
event.stop();
var myForm = document.id('form');
var request= new Request.JSON (
{
url: 'check_login.php',
method: 'post',
data:
{
form: myForm
},
onSuccess: function( response )
{
if ( response.status )
{
document.location = "home.php"
}
else
{
$('response').addClass('error');
$('response').set('html', response.message);
}
},
});
request.send();
and in the php script i want to check via the $_POST variable.
but i cannot find a method to do it like this. actually im gettinh nothing.
greetz
Sure, look at this link where it shows how to do it:
http://demos111.mootools.net/Ajax.Form
It basically selects the form via your ID, add a listener to submit event and when it comes it sends all the form the way you are looking for :-)

Categories