Retrieving data value from database from ajax function - javascript

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

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

Post on native php (without framework) Into Code Igniter using AJAX

I'm trying to post data on my HTML code to CI with Ajax. But I got no response?
Here is my JS Code
$(document).ready(function(){
$("#simpan").click(function(){
nama_pelanggan = $("#nama_pelanggan").val();
telp = $("#telp").val();
jQuery.ajax({
type: "POST",
url: "http://192.168.100.100/booking_dev/booking/addBookingViaWeb/",
dataType: 'json',
data : {
"nama_pelanggan":nama_pelanggan,
"telp":telp,
},
success: function(res) {
if (res){
alert(msg);
}
}
});
});
});
And here is my form
<form>
Nama Pelanggan <br>
<input type="text" name="nama_pelanggan" id="nama_pelanggan"><br>
Telepon<br>
<input type="text" name="telp" id="telp"><br>
<input type="button" name="simpan" id="submit" value="Simpan">
</form>
and here is my contoller function code
public function addBookingViaWeb(){
$data = array(
'nama_pelanggan' => $this->input->post('nama_pelanggan'),
'telp'=>$this->input->post('telp')
);
echo json_encode($data);
}
Here is my post param
But I got no response
any idea?
add method in from if you use post then
<form method="post" action ="" >
Try using JQuery form serialize() to declare which data you want to post. It automatically put your form input into ajax data. Example :
first set ID to your form tag
<form id="form">
then
$.ajax({
type:'POST',
url : 'http://192.168.100.100/booking_dev/booking/addBookingViaWeb/',
data:$('#form').serialize(),
dataType:'JSON',
success:function(data){
console.log(data);
}
});
First problem I see is in your ajax submission code. Change
$("#simpan").click(function(){
to
$("#submit").click(function(event){
Notice that I added the event parameter. You now need to prevent the default submission behavior. On the first line of your click method add
event.preventDefault();
Now I'm assuming that your url endpoint http://192.168.100.100/booking_dev/booking/addBookingViaWeb/ can handle POST requests. Usually this is done with something like PHP or Ruby on Rails. If I was doing this in PHP I would write something like the following:
<?php
$arg1 = $_POST["nama_pelanggan"];
$arg2 = $_POST["telp"];
// do something with the arguments
$response = array("a" => $a, "b" => $b);
echo json_encode($response);
?>
I personally don't know anything about handling POST requests with js (as a backend) but what I've given you should get the data over there correctly.
I got solution for my problem from my friend xD
just add header("Access-Control-Allow-Origin: *"); on controller function
Thank you for helping answer my problem.

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

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.

Categories