Getting data sent with Ajax from php? - javascript

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);

Related

How can i post data and file by using ajax on event onclick

HTML here.
<form id="myForm">
<input type="text" name="name">
<input type="file" name="userImage">
<button onclick="post('./example.php')" type="button">Save</button>
</form>
Now i want to post it by using post() function
Java-script:
Function post(url){
$.ajax({
url:url,
type: 'POST',
data: $("#myform").serialize(),
success: function (data) {
alert("successfully posted.");
}
});
}
But not serialized file
My advice is: try to have apart html and js defining the event callback on "attacheventlistener" function or "on" jquery's function (this way is easier).
Your problem is that you are passing the string "url" when you need pass a valid url, so write the url directly on ajax url field or define a data attribute on your form tag, e.g. data-url="http://whatever", and catch this value from the event.
If you use jquery's "on" function is extremly easy, you could to get it data's value via jquery's "data" function over "this" var.
Something like ...
$("#myForm").on("click",
function() {
post(this.data("url"));
});
But probably you do not need url being a var.
If I understand correctly, the problem is that nothing is being posted.
The thing is is that you are trying to do a file upload via ajax, this is not wrong but it needs to be done differently shown here:
jQuery Ajax File Upload
You can add extra data with form data
use serializeArray and add the additional data:
var data = $('#myForm').serializeArray();
data.push({name: 'tienn2t', value: 'love'});
$.ajax({
type: "POST",
url: "your url.php",
data: data,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
});
First of all i need to say that, if you want to upload file, i mean if your form have file input then add the form attribute enctype="multipart/form-data" according to RFC-7578. you can also see the uses http://www.w3schools.com/tags/att_form_enctype.asp.
Then move to the html part again. Suppose you have a form input like
<form action="some_domain/example.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="fileId"/>
<input type="text" name="firstName" id="name">
<button onclick="post('some_domain/example.php')" type="button">Save</button>
</form>
Now post the file data using ajax:
function post(url){
$.ajax({
url:url,
type: 'POST',
processData:false,
contentType:false,
data: $('#fileId')[0].files[0],
success: function (data) {
alert("successfully posted.");
}
});
}
I think this should be worked fine.
UPDATE:
if you want to post text data as well then you should use FormData object.
function post(url){
var formData = new FormData();
var files = document.getElementById("fileId").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
formData.append('files[]', file, file.name);
}
formData.append('firstName',$('#name').val());
$.ajax({
url:url,
type: 'POST',
processData:false,
contentType:false,
data: formData,
success: function (data) {
alert("successfully posted.");
}
});
}

Retrieving data value from database from ajax function

I have a ajax function that would retrieve data from my database and display it in my textbox. I am using a JQuery Form Plugin to shorten the ajax process a little bit. Now what I want to do is to get the data back from the php script that I called from the ajax function.
The form markup is:
<form action="searchFunction.php" method="post" id="searchForm">
<input type="text" name="searchStudent" id="searchStudent" class="searchTextbox" />
<input type="submit" name="Search" id="Search" value="Search" class="searchButton" />
</form>
Server code in searchFunction.php
$cardid = $_POST['searchStudent'] ;
$cardid = mysql_real_escape_string($cardid);
$sql = mysql_query("SELECT * FROM `users` WHERE `card_id` = '$cardid'") or trigger_error(mysql_error().$sql);
$row = mysql_fetch_assoc($sql);
return $row;
The ajax script that processes the php is
$(document).ready(function() {
$('#searchForm').ajaxForm({
dataType: 'json',
success: processSearch
});
});
function processSearch(data) {
alert(data['username']); //Am I doing it right here?
}
In PHP, if I want to call the data, I would just simply create a function for the database and just for example echo $row['username'] it. But how do I do this with ajax? I'm fairly new to this so, please explain the process.
$('#Search').click(function (e) {
e.preventDefault(); // <------------------ stop default behaviour of button
var element = this;
$.ajax({
url: "/<SolutionName>/<MethodName>",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: processSearch,
});
});
function processSearch(data) {
var username= ($(data).find('#username'));
}
Change the input type submit to button. Submit will trigger the action in the form so the form will get reloaded. if you are performing an ajax call change it into button.
Everything seems to be fine, except this bit -
function processSearch(data) {
alert(data['username']); //Am I doing it right here?
}
You need to change it to -
function processSearch(data) {
// data is a JSON object. Need to access it with dot notation
alert(data.username);
}
UPDATE
You also need to return a JSON response from your PHP file. Something like -
// Set the Content Type to JSON
header('Content-Type: application/json');
$data = [
"key" => "value"
];
return json_encode($data);
In your case you can directly encode the $row like so -
return json_encode($row);

Ajax request fail - retrieve user id from server

I have form that has one text input field and a button. On submit form, I take the value from the text field user and make an ajax call to ajax.php to then have the server return the userID. The server is indeed returning a value as shown in the console. But I am not sure why the ajax call is failing on each request after submitting the form. What can I correct or change to have a success?
index.php
$('form').submit(function(e) {
var searchUser = $('input[name="user"]').val();
var getUser = $.ajax({
type: "GET",
url: "ajax.php",
data: {user: searchUser},
dataType:'text'
});
getUser.done(function( data ) {
alert(data);
});
getUser.fail(function( jqXHR, textStatus, data ) {
alert( "Request failed: " + textStatus );
});
});
<form id="search" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="GET">
<label for="user"> Username:</label><input type="text" name="user" id="user" value="<?php echo $user ?>"><br>
<button type="submit" id="search">Search</button>
</form>
ajax.php
if(!empty($_GET['user'])){
$user = $_GET['user'];
echo getInstaID($user); // this prints a numeric value like 2057821
}
Perhaps the data is being returned as json or jsonp? You have specified dataType: 'text'. If the return datatype is different it will error out. If you are using a fairly recent version (I think 2.0 or better) leaving out dataType or specifying dataType:"auto" will allow the call to succeed. Then you can debug to figure out how to handle the response.
You might try adding a success function like the following:
$('form').submit(function(e) {
var searchUser = $('input[name="user"]').val();
$.ajax({
type: "GET",
url: "ajax.php",
data: {user: searchUser},
success:function(data){//begin success function
//do something with the data returned from ajax.php file
alert(data);
}//end success function
});

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.

Getting data from form.serializaArray()

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);
}
});
});

Categories