AJAX not posting values with $(form).serialize() - javascript

I have a form that I'm trying to submit via AJAX. The easiest way for me to pass the data would be using $("#myForm").serialize(), however, when doing so, the page to which I'm posting to doesn't receive the data.
Here's my form:
<form id="myForm">
<input name="field" id="field">
<button id="submitBtn" type="button">
</form>
And this is my function:
$("#submitBtn").click(function(){
alert($("#myForm").serialize()) //For testing – does alert "field=value"
var post = $.post("actions.php", $("#myForm").serialize());
post.done(function(d){alert(d)}); //Only alerts [PHPSESSID]
var post = $.post("actions.php", {field:"fieldVal"});
post.done(function(d){alert(d)}); //Alerts [PHPSESSID] and ['field']
});
This is my whole actions.php file:
<?php
print_r($_REQUEST);
exit();
Why is passing the values as JSON working but .serialize() isn't??

Looks like I just had to pass the serialized form as a variable instead of serializing it inside the $.post() function. As so:
var postData = $("#myForm").serialize()
var post = $.post("actions.php", postData);
post.done(function(d){alert(d)});
Not sure why it works when established outside and not inside the function, maybe a conflict issue. Thanks to everyone anyway

Use serializeArray() instead: https://api.jquery.com/serializeArray/

Related

AJAX - my simple ajax request does not work

I'm currently learning how to use Ajax but i already have a problem :
1 HTML :
<body>
<form>
Nom d'utilisateur : <input type="text" id="username" name="username"/>
<input type="submit" id="submit" />
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="script.js"></script>
JS :
$(document).ready(function(){
$("form").submit(function(e){
e.preventDefault();
var don=$('#username').val();
$.ajax({
url:'test.php',
type:'post',
data:don,
success: function(html){
alert(html);
}
});
});
});
PHP :
<?php
if(!empty($_POST['username'])){
$response="yep";
}
else{
$response="nope";
}
echo $response;
?>
As you can see, it is really simple. But it drives me crazy, i didn't understand why i always have the response "nope".
Can you help me ?
Thank you
PHP requires you to submit key=value constructs to properly build $_POST/$_GET with. No key, no value. You haven't provided a key, just a value.
Try
data: {"username":don}
instead. Or have your PHP script read the raw POST data via php://input.
You are just sending a string. You need to send a JSON object:
var don = {"username" : $('#username').val()};
jQuery will turn this into a string and send it (I'm assuming, otherwise you need to JSON.stringify it), and then you'll need to call json_decode on it server-side before you query it.
If you want to continue using your current serverside code, you need to use a GET request and submit to url: "test.php?username="+encodeURIComponent($('#username').val()) and then check the _GET variable on PHP side.

Post hidden field containing javascript variable or function?

I feel like I must be missing something, or I'm just too clueless to search for the right question, so please pardon me (and redirect) if this is a duplicate. My issue is probably much harder than I think it should be.
I have a page with a rather lengthy block of php code (mainly MySQL queries) which generate variables that are eventually passed into JavaScript as strings. The data is then used to create some interactive form elements. The end result is a textarea field which contains a JS string which I'd like to carry into to a new page. I will also be POSTing php variables to that new page.
Sample code:
<?php //Get data from MySQL, define variables, etc.?>
<script> //Move php strings into JavaScript Strings;
//put JS vars into textareas; etc
var foo = document.getElementById('bar').value </script>
<form action="newpage.php" method="post">
<input type="hidden" id="id" name = "name" value="**JAVASCRIPT foo INFO HERE**"/>
<input type = "hidden" id="id2" name = "name2" value = "<?php echo $foo; ?>" />
<input type="submit" name="Submit" value="Submit!" />
Calling JS functions in the right order is a little sticky because they depend on php variables which aren't defined until queries are complete, so I can't do much with an onload function. I'm literate in php. I'm a novice in JavaScript. I'm fairly inept with JQuery and I've never used AJAX. I'd also really rather not use cookies.
It would be great to see an example of what the original and new page code might look like. I know I can receive the php on the new page info via
$foo = $_POST['name2'];
beyond that, I'm lost. Security isn't really a concern, as the form captures information which is in no way sensitive. Help?
If you don't need to use the failure function, you can skip the AJAX method (which is a bit heavier), so I would recommend you make use of the $.post or $.get syntax of jQuery.
Pre-defined syntax: jQuery.post( url [, data ] [, success ] [, dataType ] )
Here is the example for jQuery:
$.post('../controllerMethod', { field1: $("#id").val(), field2 : $("#id2").val()},
function(returnedData){
console.log(returnedData);
});
Otherwise, you could use the AJAX method:
function yourJavaScriptFunction() {
$.ajax({
url: "../controllerMethod", //URL to controller method you are calling.
type: "POST", //Specify if this is a POST or GET method.
dataType: "html",
data: { //Data goes here, make sure the names on the left match the names of the parameters of your method you are calling.
'field1': $("#id").val(), //Use jQuery to get value of 'name', like this.
'field2': $("#id2").val() //Use jQuery to get value of 'name2', like this.
},
success: function (result) {
//Do something here when it succeeds, and there was no redirect.
}
});
}
function init()
{
var str1 = <?php echo varname; ?> //to access the php variable use this code//
document.getElementById('id').value= str1;
}
<body onload="init()">//make sure you call the function init()`
did you try something like this

Returning ajax response from django

I have exhausted my brain trying to get something simple to work. I want to change the behavior of a form from post reload to ajax with django. I just can't get it to work.
The form is something like:
<form id="form1" action="/myurl/" method="post" onsubmit="doexchange">
<input id="input1" type="hidden" name="serializedData" value=""/>
<button id="button1" type="submit">render<button/>
</form>
Using jquery, I have something like:
function doexchange(){
var dataBuffer = new Object();
dataBuffer = myCollecter(dataBuffer);
$("#input1").attr("value", JSON.stringify(dataBuffer));
$.get($("#form1").attr("action"),
{serializedData: $("#input1").attr("value")},
function(data){
alert('yes' + data);
});
return false;
}
Now the return false is to prevent the original form from doing a POST of its own.
On the server side, I have something really simple like:
def handler(request, data):
return HttpResponse('{}', 'application/json')
The client successfully sends the data to the server through an ajax request. The server also returns the {} empty bracket to the client. But instead of the callback function getting called and seeing and alert, the whole page reloads and I see only {} on a new page.
As I said I have tried so many different things, but I think I am missing something elephant big... Any ideas? Oh, and I am using the latest Mozilla firefox, but I don't think this is a browser specific issue...
I don't think a solution needs to be very convoluted to achieve the outcome you're going for. Consider something on the lines of:
A page that looks like:
<a class="btn" onclick="doexchange">render</a>
An JavaScript that looks like the following:
function doexchange(){
var dataBuffer = myCollecter(dataBuffer);
$.get('/myurl/', {serializedData: JSON.stringify(dataBuffer)}, function(data) {
alert('yes' + data);
});
}
Try binding to the form submit in your javascript.
$('#form1').bind('submit', function( e ){
e.preventDefault();
var form=$(this),
input=form.find('input[name="serializedData"]');
$.ajax({
//
});

In PHP how to use $_REQUEST to retrieve an array of inputs to enter into a database

I am using AJAX to send inputs from a webpage to a PHP file to then be entered into a database. Here is my JavaScript file:
var pageLoaded = function () {
var submitButton = document.getElementById("submit");
if (submitButton) {
submitButton.addEventListener("click", submit, true);
}
};
var submit = function () {
var xhr, changeListener;
var form = document.getElementById('item_form');
var inputs = form.getElementsByTagName('input');
// create a request object
xhr = new XMLHttpRequest();
// initialise a request, specifying the HTTP method
// to be used and the URL to be connected to.
xhr.open("POST", "../php/add_item.php", true);
console.log(inputs[0].value); // debugging
// Sends the inputs to the add_item.php file
xhr.send(inputs);
};
window.onload = pageLoaded;
Here I am trying to send inputs from a form to a PHP file called add_item.php located "../php/add_item.php" in my file system.
I am pretty sure this code works and sends the inputs to the PHP file in an array.
My question is, how do I then use $_REQUEST within that file to be able to use the inputs within the array to send to a database? Or, what is the best way of doing this?
The xhr.send() method only accepts a string. If you want to send an array you have to flatten it into a string before posting. You can do this easily using the JSON.stringify() method in javascript, then use json_decode() function in PHP on receiving it.
Also for PHP to receive the data properly in the $_POST[] variable (or $_REQUEST if you must, but not recommended) you need to set a name for the POST variable and URL-encode your JSON text like this:
var json_array = JSON.stringify(inputs);
xhr.send('myJSONData=' + encodeURIComponent(json_array));
On the PHP side you shouldn't need to use urldecode() because the server stack expects to receive POSTed name-value pairs url-encoded. But you will need to use json_decode on the posted variable to get the array back, e.g.:
php_array = json_decode($_POST["myJSONData"]);
You will see other methods to do this, including setting the xhr POST content-type header to JSON, but in my experience this is the path of least resistance.
Also note whilst it is possible to send an "array" of objects in an HTML form like this:
<input type="text" name="myArray[]" value="val1">
<input type="text" name="myArray[]" value="val2">
<input type="text" name="myArray[]" value="val3">
<input type="text" name="myArray[]" value="val4">
which will result in an array being available within PHP in the variable $_POST["myArray"], there is no easy equivalent of this using the XHR object (AJAX method). JSON.stringify() is IMO the easiest way to go.
The variables inside the $_REQUEST are stored as an array. To access them you would do something similar to this:
echo $_REQUEST['input_1'];
To view all the variables (in a nice format) sent by the JS you could use this code:
echo "<pre>";
print_r($_REQUEST);
echo "</pre>";
You can't do it in the way you are doing it. You send "input" array which is incorrect. You should prepare array of input values. Morover, I'd recommend you to use JQuery.
$(function (){
$("#submit").click(function (){
//the way to get input values and names
var arr = [];
$("input").each(function (index,value){});
arr.push([$(value).attr('name'), $(value).val()];
});
// it can be replaced also via serialize() funciton
//ajax
$.post( "../php/add_item.php", arr)
.done(function( data ) {
//data has been send response is in data object
});
});
});
In PHP you can get these values via $_POST. $_REQUEST is not needed here because you use POST method. For example if you have input
<input name="xxx" value="test">
to print value of this input in PHP you need use this code
echo $_POST['xxx'];
If you don't want to use JQuery then you still need loop through inputs and prepare proper array to send it via XHR.

Call a PHP function after AJAX

When a user submits the form on my page I use AJAX to submit the information without refreshing the page. After the user submits the information I want to run a PHP function that I have already written that displays the information. Is this possible or do I need to run another ajax function to update after
$(function () {
$('add').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'submit.php',
data: $('this').serialize(),
success: function () {
alert('form was submitted');
}
});
e.preventDefault();
updateWords(); //PHP FUNCTION
});
});
You will need to run another AJAX call on success of the first one.
JavaScript cannot interact with PHP directly and therefore you can't call a PHP function from the success/complete function of the AJAX call.
in response of this.
I have multiple forms on the page and probably 5 different ajax calls
in which no more then 2 are called at the same time, if json is better
do you have a link to some reading material or additional stack
example similar to this so i can teach myself – user934902
first of all
jquery was made for old browsers to support basic functions that ie6 does not support
the use of jquery is good if you want to have full support on almost all browser
but there are also many bad sides:
it's 81kb code wich is insane (without plugins)
it's very slow compared to native functions.
it's used by ppl who don't know how to write simple javascript.
and much more if we start to talk about the plugins.
now we are in a era where most of the ppl use their mobile devices and modern browsers
which support standard javascript 1.7.Android,ios,safari,internet explorer 10,chrome,opera & firefox support javascript 1.7
http://caniuse.com/
the code below is supported by those browsers.
this is a ajax function written by me it handles post & get
you can read more about that function here
https://stackoverflow.com/a/18309057/2450730
function ajax(a,b,e,d,f,g,c){
c=new XMLHttpRequest;
!f||(c.upload.onprogress=f);
!g||(c.onprogress=g);
c.onload=b;
c.open(e||'get',a);
c.send(d||null)
}
// Params:
// Url,callback,method,formdata or {key:val},uploadFunc,downloadFunc,placeholder
a simple get request would be
ajax('example.php',responseFunction);
and a complex post function would be
ajax('example.php',responseFunction,'post',new FormData(form),uploadFunc,dlFunc);
you need that.
so if you have your form
<form id="myForm">
<input name="name"> Name
<input name="surname"> Surname
<input name="mail"> Email
<input name="file" type="file" multiple> File/Files
</form>
you just have to write a function like that
var form=document.getElementsById('myForm');
form.onsubmit=function(e){
e.preventDefault();
ajax('submit.php',SUCCESS,'post',new FormData(this));
}
and here we come to your question :
create the submit.php file for your needs
<?php
// do whatever you need with the posted info
// copy files to a specific folder
// insert/update/delete the database
// check for errors
// lets say no errors
$err=array();
// load extra info from database to an array called $extrainfo
// load some functions... (you can do what you want here)
// like executing the function you have already written and add that info to
// the $extrainfo.
$extrainfo=array('updated correctly','files copied');
$data=array('post'=>$_POST,'files'=>$_FILES,'info'=>$extrainfo,'errors'=>$err);
echo json_encode($data);
?>
this returns a json encoded array to use later in javascript.
now we need to elaborate this json. in the SUCCESS function
function SUCCESS(){
var data=JSON.parse(this.response);
if(data.errors.length>0){
// you have some errors
}else{
// no errors
// display your response in a proper way.
console.log(data);
}
}
inside this function you just have to display based on the response data.
data contains everything you need.
here is the whole code.
copy and past into a txt file and save it as submit.php.
i have tested only in chrome for now.
<?php
if($_POST){
$err=array();
$extrainfo=array('updated correctly','files copied');
$data=array('post'=>$_POST,'files'=>$_FILES,'info'=>$extrainfo,'errors'=>$err);
echo json_encode($data);
}else{
?><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>upload</title>
<script>
var form,result;
function ajax(a,b,e,d,f,g,c){
c=new XMLHttpRequest;
!f||(c.upload.onprogress=f);
!g||(c.onprogress=g);
c.onload=b;
c.open(e||'get',a);
c.send(d||null)
}
function SUCCESS(){
console.log(JSON.parse(this.response));
var data=JSON.parse(this.response);
if(data.errors.length>0){
result.textContent='you have some errors:'+data.errors[0];
}else{
result.textContent=JSON.stringify(data, null, '\t');
}
}
window.onload=function(){
form=document.getElementById('myForm');
result=document.getElementById('response');
form.onsubmit=function(e){
e.preventDefault();
ajax('submit.php',SUCCESS,'post',new FormData(this));
}
}
</script>
</head>
<body>
<form id="myForm">
<input name="name"> Name
<input name="surname"> Surname
<input name="mail"> Email
<input name="file[]" type="file" multiple> File/Files
<input type="submit" value="send">
</form>
<pre id="response"></pre>
</body>
</html>
<?php
}
?>
If the function is dependant on the AJAX call to submit.php finishing, then create a new AJAX call. If not, then just append the function to submit.php and call it at the end of the file.
You should use the ajax function that performs the update information to update the page itself at the same time.
Just return usable HTML as the return from the ajax, and use that as the HTML content of the page.
Example: test.php
<script>
function updateName() {
var url = './test.php?inpName=' + $('#inpName').val();
$.get( url, function( data ) {
$( "#frmDivUpdate" ).html( data );
alert( "Call was performed." );
});
}
</script>
<div id="frmDivUpdate">
<form>
Enter your name : <input name="inpName" id="inpName">
<br>
<input type="button" onClick="updateName();" value="Update">
</form>
</div>
<?php
if (isset($_GET))
{
$inpName = $_GET["inpName"];
echo "You updated your val to $inpName";
}
?>
PHP is serverside , javascript is clientside.
you can't call php from client if the page is already loaded.
so the easy way is ajax
in the submit.php add:
echo json_encode($_POST);
or the
PHP function that I have already written
... the information what you need.
and in the success function
success: function () {
// i don't use jquery but the response contains the json string
console.log('the words you wanna update:',JSON.parse(response));
// updateWords(JSON.parse(response));
}
EDIT
you also don't need more than one ajax function
you say you already wrote a script to display the next information to the client.
add that script to the submit.php
and the succes function will give you what you need as response.
i added echo json_encode($_POST); because most of the time as answer/update info you need is that one you just posted.

Categories

Resources