Getting data from form.serializaArray() - javascript

i need help..why does my code not working?what is the proper way to get the data from a form.serialize? mines not working.. also am doing it right when passing it to php? also my php code looks awful and does not look like a good oop
html
<form action="" name="frm" id="frm" method="post">
<input type="text" name="title_val" value="" id="title_val"/>
post topic
</form>
<div id="test">
</div>
Javascript
$( document ).ready(function() {
$('#save').click(function() {
var form = $('#frm');
$.ajax({
url: 'topic.php',
type:'get',
data: form.serializeArray(),
success: function(response) {
$('#test').html(response);
}
});
});
});
Php
<?php
class test{
public function test2($val){
return $val;
}
}
$test = new test();
echo $test->test2($_POST['title_val']);
?>
OUTPUT

You're telling your ajax call to send the variables as GET variables, then trying to access them with the $_POST hyperglobal. Change GET to POST:
type:'post',
Also, it should be noted that you are binding your ajax call to the click on your submit button, so your form will still be posting. You should bind on the form's submit function instead and use preventDefault to prevent the form posting.
$('#frm').submit(function(e) {
e.preventDefault(); // stop form processing normally
$.ajax({
url: 'topic.php',
type: 'post',
data: $(this).serializeArray(),
success: function(response) {
$('#test').html(response);
}
});
});

Related

Getting data sent with Ajax from php?

sorry if this has been asked many times but I can't get it to work.
I'm trying to build a restful website, I have a simple form:
<form action="/my/path" method="post" id="myformid">
Name <input type="text" name="name">
<input type="submit" value="Test">
</form>
I convert the data the user inputs using Javascript and I send them to my php file using Ajax:
function postData() {
$('#myformid').on('submit', function(event) {
event.preventDefault();
const json = JSON.stringify($("#myformid").serializeArray());
$.ajax({
type: "POST",
url: "/my/path",
data: json,
success: function(){},
dataType: "json",
contentType : "application/json"
});
});
}
And I tried reading the data on php like:
$data = json_decode(file_get_contents('php://input'), true);
$name = $data["name"];
The code works perfectly if I send a JSON in the request body using a tool like Postman, but from what I tested using Ajax the json data arrives as POST data, and I can read it using $_POST["name"], but non with the 'php://input' as I did.
How can I fix it so the JSON gets accepted even sent via Javascript?
Hi you can try like this:
First I use an id attribute for each input i dont really like to serialize stuff but thats me you can do it your way here are the files.
your index.php:
<form method="post" id="myformid">
Name :<input type="text" id="name" name="name">
<input type="submit" value="Test">
</form>
<br>
<div id="myDiv">
</div>
your javascript:
//ajax function return a deferred object
function _ajax(action,data){
return $.ajax({
url: 'request.php',
type: 'POST',
dataType: 'JSON',
data: {action: action, data: data}
})
}
//your form submit event
$("#myformid").on('submit', function(event) {
//prevent post
event.preventDefault();
//validate that name is not empty
if ($("name").val() != "") {
//parameters INS is insert data is the array of data yous end to the server
var action = 'INS';
var data = {
name: $("#name").val()
};
console.log(data);
//run the function and done handle the function
_ajax(action,data)
.done(function(response){
console.log(response);
//anppend name to the div
$("#myDiv").append("<p>"+response.name+"</p>");
});
}
});
your request.php file:
<?php
//includes and session start here
//validate that request parameters are set
if (isset($_POST["action"]) && isset($_POST["data"])) {
//getters
$action = $_POST["action"];
$data = $_POST["data"];
//switch to handle the action to perfom maybe you want to update with the form too ?
switch ($action) {
case 'INS':
// database insert here..
//return a json object
echo json_encode(array("name"=>$data["name"]));
break;
}
}
?>
Results:
Hope it helps =)
From the documentation of .serializeArray().
The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string.
And in the example given in the same page, it is clear that you will get an array in php,
to access an element, you should try-
`$data[0]['name']`
Also, have you tried print_r($data), is it NULL??
Change your ajax codes
$('#btnSubmit').on('click', function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "/new.php",
data: $("#myformid").serialize(),
dataType: "json",
success: function(response) {
console.log(response);
}
});
});
Also you need some changes in form
<form action="new.php" method="post" id="myformid">
Name <input type="text" name="name">
<input id="btnSubmit" type="button" value="Test">
And you can get POST data in php file like $_POST['name']
You can set directly form serialize in ajax request to send params
function postData() {
$('#myformid').on('submit', function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "/my/path",
data: $("#myformid").serialize(),
success: function(){},
dataType: "json",
contentType : "application/json"
});
});
}
And you can get POST in your PHP using $_POST
print_r($_POST);

Enter ID in html form and load related data from MySQL database in same page

I have a form with an input field for a userID. Based on the entered UID I want to load data on the same page related to that userID when the user clicks btnLoad. The data is stored in a MySQL database. I tried several approaches, but I can't manage to make it work. The problem is not fetching the data from the database, but getting the value from the input field into my php script to use in my statement/query.
What I did so far:
I have a form with input field txtTest and a button btnLoad to trigger an ajax call that launches the php script and pass the value of txtTest.
I have a div on the same page in which the result of the php script will be echoed.
When I click the button, nothing happens...
Test.html
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script>
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
</script>
</head>
<body>
<form name="testForm" id="testForm" action="" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" name="txtTest" id="txtTest"/>
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
<input type="submit" name="SubmitButton" id="SubmitButton" value="TEST"/>
</form>
<div id="testDiv" name="testDiv">
</div>
</body>
The submit button is to insert updated data into the DB. I know I have to add the "action". But I leave it out at this point to focus on my current problem.
testpassvariable.php
<?php
$player = $_POST['userID'];
echo $player;
?>
For the purpose of this script (testing if I can pass a value to php and return it in the current page), I left all script related to fetching data from the DB out.
As the documentation says 'A page can't be manipulated safely until the document is ready.' Try this:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
You need to correct two things:
1) Need to add $(document).ready().
When you include jQuery in your page, it automatically traverses through all HTML elements (forms, form elements, images, etc...) and binds them.
So that we can fire any event of them further.
If you do not include $(document).ready(), this traversing will not be done, thus no events will be fired.
Corrected Code:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
$(document).ready() can also be written as:
$(function(){
// Your code
});
2) The button's HTML is improper:
Change:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
To:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
$.ajax({
url: "testpassvariable.php",
type: "POST",
data: {
userID: $("#txtTest").val(),
},
dataType: text, //<-add
success: function (response) {
$('#testDiv').html(response);
}
});
add dataType:text, you should be ok.
You need to specify the response from the php page since you are returning a string you should expect a string. Adding dataType: text tells ajax that you are expecting text response from php
This is very basic but should see you through.
Change
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
Change AJAX to pass JSON Array.
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "action.php",
data: data,
....
// action.php
header('Content-type: application/json; charset=utf-8');
echo json_encode(array(
'a' => $b[5]
));
//Connect to DB
$db = mysql_connect("localhst","user","pass") or die("Database Error");
mysql_select_db("db_name",$db);
//Get ID from request
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
//Check id is valid
if($id > 0)
{
//Query the DB
$resource = mysql_query("SELECT * FROM table WHERE id = " . $id);
if($resource === false)
{
die("Database Error");
}
if(mysql_num_rows($resource) == 0)
{
die("No User Exists");
}
$user = mysql_fetch_assoc($resource);
echo "Hello User, your number is" . $user['number'];
}
try this:- for more info go here
$(document).ready(function(){
$("#btnLoad").click(function(){
$.post({"testpassvariable.php",{{'userID':$("#txtTest").val()},function(response){
$('#testDiv').html(response);
}
});
});
});
and i think that the error is here:-(you wrote it like this)
data:{userID:$("#txtTest").val(),}
but it should be like this:-
data:{userID:$("#txtTest").val()}
happy coding :-)

How do I use AJAX to print out data inside a div?

I have two files. One file is named index.php and another file is named process.php.
I have a form that submits to process.php in index.php:
<form class="form" action="process.php" method="POST" name="checkaddress" id="checkaddress">
<table>
<tr class="element">
<td><label>Address</label></td>
<td class="input"><input type="text" name="address" /></td>
</tr>
</table>
<input type="submit" id="submit" value="Submit"/>
</form>
<div class="done"></div>
I also have a process in process.php to echo some data based off of the input. How would I be able to use AJAX to submit the form without leaving the page?
Is it something like:
$.ajax({
url: "process.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
$('.done').fadeIn('slow');
}
});
What page would I put the above code on if it was right?
Also, how do I change the above code to say what the process.php outputted? For example, if I echo "Hello" on process.php, how do I make it say it in the done div?
I have seen many responses regarding AJAX, but they all rely on data that is pre-made like APIs. I need to do a database query and fetch the data dependent on the address entered and print the data out.
You need to collect the data in the form so that you can submit them to the process page, and you need to run your code when submitting the form (and cancel the default form submission)
$('#checkaddress').on('submit', function(e){
// get formdata in a variable that is passed to the ajax request
var dataToPassToAjax = $(this).serialize();
$.ajax({
url: "process.php",
type: "GET",
data: dataToPassToAjax,
cache: false,
success: function (resultHtml) {
// add the returned data to the .done element
$('.done').html( resultHtml ).fadeIn('slow');
}
});
// cancel the default form submit
return false;
});
[update]
If you want to modify the data before submitting them, you will have to manually create the parameters to pass to the ajax
$('#checkaddress').on('submit', function(e){
// get formdata in a variable that is passed to the ajax request
var dataToPassToAjax = {};
var address = $('input[name="address"]', this).val();
// alter address here
address = 'something else';
dataToPassToAjax.address = address;
$.ajax({
url: "process.php",
type: "GET",
data: dataToPassToAjax,
cache: false,
success: function (resultHtml ) {
// add the returned data to the .done element
$('.done').html(resultHtml ).fadeIn('slow');
}
});
// cancel the default form submit
return false;
});
You could use the jQuery form plugin: http://jquery.malsup.com/form/
Let me know if you want example code.

Submit without leaving page

My form
<form id="reservationForm" action="sendmail.php" method="post">
...
.
.
.
.
<input type="image" src="images/res-button.png" alt="Submit" class="submit" width="251" height="51px">
My javascript
$("#reservationForm").submit(function () {
e.preventDefault();
var $form = $(this);
$.ajax({
type: 'POST',
url: 'sendmail.php',
data: $('#form').serialize(),
success: function(response) {
alert("Success");
$('#reservationForm').fadeOut("slow");
}
});
return false;
});
i don't want to run any validation because i have user 'required' in all types. i just want to send data to my php while staying at the same contact form. but this only load my php file and send the e-mail. looks like it dosen't run my javascript. please help
You haven't defined the event argument in the callback. Change this line as follows and it should work:
$("#reservationForm").submit(function (e) {
...
EDIT: BTW: The .submit event handler of jQuery short hand is deprecated. You should be using .on('submit', ...instead.

post multiple variables using jquery

I am trying to pass multiple variables from one php file to another via jquery but nothing is happening at all and i also can see that there is error in javascript code but i can not firgure out what is really wrong !
HTML Code :
<form id="edit" action="" method="POST">
<input type="text" name="name" value="wael">
<input type="text" name="phone" value="0103941454">
<input type="text" name="address" value="address">
<input type="submit" name="submit" value="Send">
</form>
<div style="display:none;" id="feedback"></div>
Jquery code :
$(document).ready(function(){
$('#edit').submit(function(){
$.ajax({
type:'POST',
url:'edit.php',
dataType:'json',
data:$('#edit').serialize(),
success:function(data) {
$('#feedback').html(data).fadeIn().delay(5000).fadeOut();
};
});
});
});
PHP Code :
<?php
echo "Just testing functionality!":
?>
Please I need help to figure out what is wrong with this code.
In your JS code, you have to stop the form from being submitted, use e.preventDefault(), and there was a syntax error at the end of the success callback. Try this -
$(document).ready(function(){
$('#edit').submit(function(e){
e.preventDefault();
//^^^^^^^^^^^^^^^^^^^ Added this.
$.ajax({
type:'POST',
url:'edit.php',
dataType:'json',
data:$('#edit').serialize(),
success:function(data) {
$('#feedback').html(data).fadeIn().delay(5000).fadeOut();
}
//^ There was a comma here. Remove it.
});
});
});
Now, with this, your code will execute without syntax errors, but your success callback will not called because, you have dataType:'json', so the return value from php will have to be valid json otherwise there will be a parsing error and your success callback will not be called.
To detect that, you need to use the error callback. This is a more complete AJAX call -
$(document).ready(function(){
$('#edit').submit(function(e){
e.preventDefault();
$.ajax({
type:'POST',
url:'edit.php',
dataType:'json',
data:$('#edit').serialize(),
success:function(data) {
console.log("success");
$('#feedback').html(data).fadeIn().delay(5000).fadeOut();
},
error: function( jqXHR,textStatus,errorThrown ){
console.log(textStatus);
}
});
});
});
With your PHP code, which returns invalid JSON, the parsing error will be thrown.Try using json_encode() in your PHP if you want to return JSON data.For example, try this in your edit.php file -
<?php
header("Content-Type: application/json");
echo json_encode("Just testing functionality!");
?>
For posting form data it is good to use JQuery Form plugin which provide easy way to send data and receive response.
http://malsup.com/jquery/form/
Check this, and check examples where you will find easy and simple examples.
Also, using this plugin, you will have no need to fetch the form data in your jquery or use the jquery ajax function. The data will be directly posted to the form action by ajax when submitted.
Hope this will help.
add return false; to the end of your .submit() function to prevent the form from submitting
$('#edit').submit(function(){
$.ajax({
type:'POST',
url:'edit.php',
dataType:'json',
data:$('#edit').serialize(),
success:function(data) {
$('#feedback').html(data).fadeIn().delay(5000).fadeOut();
}
});
return false; //here. otherwise the form will submit to its self not edit.php
});
try this code
$(document).ready(function(){
$('#edit').submit(function(event){
event.preventDefault();
$.ajax({
type:'POST',
url:'edit.php',
dataType:'json',
data:$('#edit').serialize(),
success:function(data) {
$('#feedback').html(data).fadeIn().delay(5000).fadeOut();
}
});
});
});
I have made two changes here .
1. event.preventDefault();
for prevent the default action.
2. success:function(data) {
$('#feedback').html(data).fadeIn().delay(5000).fadeOut();
}
instead of
success:function(data) {
$('#feedback').html(data).fadeIn().delay(5000).fadeOut();
};
apart from what Kamehameha and kanishka-panamaldeniya wrote down, you can achieve your goal in this way:
data: { name:wael ,phone:0103941454, address:address }
and
type:'post'
As said you need to call preventDeafult function on the event object; This function prevent the submit action to occur.
$('#edit').submit(function(event) {
event.preventDefault();
As a form of optimization you can also refer to $(this) inside your ajax call, instead to doing a new DOM traversing with $(#edit).serialize().
$.ajax({
type:'POST',
url:'edit.php',
dataType:'json',
data:$(this).serialize(), // <- modified here
success:function(data) {
$('#feedback').html(data).fadeIn().delay(5000).fadeOut();
}
});
and then yes, as #Kamehameha said, you need to return valid json from your edit.php, so
//edit.php
echo json_encode("Just testing functionality!");

Categories