Retrieve data from mysql using ajax and populate input fields - php

I have a page with a lot of input fields. I am using Jquery to get all of the values of the form at once using data: $("#profile").serialize().
Since my MySQL columns have the same name as my input fields. Is there an easy to select * from my db and load the results into the appropriate fields using jquery / ajax? Perhaps an example or a link?
Thanks,
Scott
Edit: Ok thanks for the help, but I am still a bit lost and not getting it to work, here is what I have so far:
<script type="text/javascript">
$(window).load(function(){
$.ajax({
url: "/profile_functions/profile_about_retrieve.php",
type: 'POST',
data: allFormFields,
success: function(){
//console.log('done');
}
});
jQuery(#profile).find(":input").each(function(key, val) {
fieldName = jQuery(this).attr("name");
if(fieldName != "" && fieldName != undefined) {
allFormFields[fieldName] = jQuery(this).val();
}
});
});
</script>
And a little test data from my db being echo'ed via json_encode
[{"key":"test","value":"9"}]
And html
<form id="profile" method="post">
<input type="text" name="test"
</form>

jQuery(formId).find(":input").each(function(key, val) {
fieldName = jQuery(this).attr("name");
if(fieldName != "" && fieldName != undefined) {
allFormFields[fieldName] = jQuery(this).val();
}
});
Use the allFormFields array to send to the PHP endpoint
$.ajax({
url: url,
type: 'POST',
data: allFormFields,
success: function(){
console.log('done');
}
});

Related

ajax post method in php

I am trying to send ajax post javascript variable to php. My code php will only be executed if I press submit in another form.
My code is in one index.php file.
The console shows that this value has been sent, but my php code does not want to pick it up and does not execute the query. Why?
<?php
if (isset($_POST['imie2'])) {
...
if(isset($_POST['item_id']) && !empty($_POST['item_id'])){
$value = $_POST['item_id'];
if ($polaczenie->query("INSERT INTO zamowienia VALUES ('$value')")) {
...
?>
<form method="post">
<input type="text" name="imie2">
...
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
var value = localStorage.getItem('sumalist');
console.log(value);
$.ajax({
url:"index.php",
method:"POST",
data:{
item_id: value,
},
success:function(response) {
console.log('ok'); // console shows ok
},
error:function(){
alert("error");
}
});
});
</script>
You said:
if (isset($_POST['imie2'])) {
but your data looks like this:
data:{
item_id: value,
},
There's no imie2 field so your test will always fail.

Filter out data with AJAX

I retrireve data from my MySQL database into a simple table. Above this table I should have a text-input. On entering a keyword into this input, I want to cancel all showing data in the table and display data, found by %LIKE% operator, matching the keyword entered.Something similar does jQueryUi Autcomplete, FooTable and a couple of Yii extensions, but I wanna do it all from scratch. Any ideas on how to do it? Links?
My knowledge:
$.ajax({
url: 'ajax/test.html',
success: function(){
alert('Load was performed.');
}
});
What I am going to give you is not the complete code.
You want to do it yourself so here is only the logic.
In you index.php file
<input type="text" name="autocoplete" id="autocomplete"/>
<div id="result"></div>
<script type="text/javascript">
$(document).on('keyup', '#autocompelte', function(){
var text = $('#autocomplete').val();
$.post('process.php', {text:text}, function(resultData){
//Treat your resultData and convert into HTML for example
$('#result').html(myHTMLResult);
}, 'json'); //I want my result as JSON
});
</script>
process.php
if(true === isset($_GET['text']) && false === empty($_GET['text']))
{
//Do your query where you field is like %$_GET['text']% : example : SELECT * FROM mytable WHERE myfield like %$_GET['text']%
//Store all your result in an array
//Format this array into json to be easy to treat with json
//Send this json back to your index.php file.
echo json_encode($listResult);
}
#ThinkTank thank you very much for the help. It works just fine. Here is my final code:
$(document).ready(function() {
$('#input').keyup(function(eventObject){
//cancel all displaying data in the table if keyword exists
if($(this).val()) {
//$("td").hide();
$("td").remove();
//data hid, now send data to server
var orgValue = $(this).val();
$.ajax({
url: '/products/RetrieveData',
data: 'term='+orgValue,
success: function(data) {
var jsondata=$.parseJSON(data);
$.each(jsondata, function(i, d) {
var row='<tr>';
$.each(d, function(j, e) {
row+='<td>'+e+'</td>';
});
row+='</tr>';
$('#table tbody').append(row);
});
}
});
} else {
$("td").show();
}
});
} );
Just some ideas:
1. Once I find (filter out) what I need, I clear the input with backspace. How do I set the table to the initial state with the data?

Trouble POSTing form with AJAX

edit - the info appears to be posting, but on form_data.php it doesn't seem to be retrieving the posted values
Here's the AJAX
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$("#submit_boxes").submit(function() { return false; });
$('input[type=submit]').click(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: $(this).serialize(),
success: function(data) {
$('#view_inputs').html(data); //view_inputs contains a PHP generated table with data that is processed from the post. Is this doable or does it have to be javascript?
});
return false;
});
};
</script>
</head>
Here is the form I'm trying to submit
<form action="#" id = "submit_boxes">
<input type= "submit" name="submit_value"/>
<input type="textbox" name="new_input">
</form>
Here is the form_data page that gets the info posted to
<?php
if($_POST['new_input']){
echo "submitted";
$value = $_POST['new_input'];
$add_to_box = new dynamic_box();
array_push($add_to_box->box_values,$value);
print_r($add_to_box->box_values);
}
?>
Your form is submitting because you have errors which prevents the code that stops the form from submiting from running. Specifically dataType: dataType and this.html(data) . Firstly dataType is undefined, if you don't know what to set the data type to then leave it out. Secondly this refers to the form element which has no html method, you probably meant $(this).html(data) although this is unlikely what you wanted, most likely its $(this).serialize() you want. So your code should look like
$('form#submit_boxes').submit(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: $(this).serialize(),
success: success
})
return false;
});
Additionally if you have to debug ajax in a form submit handler the first thing you do is prevent the form from submitting(returning false can only be done at the end) so you can see what errors occurred.
$('form#submit_boxes').submit(function(event) {
event.preventDefault();
...
});
You can use jQuery's .serialize() method to send form data
Some nice links below for you to understand that
jquery form.serialize and other parameters
http://www.tutorialspoint.com/jquery/ajax-serialize.htm
http://api.jquery.com/serialize/
One way to handle it...
Cancel the usual form submit:
$("#submit_boxes").submit(function() { return false; });
Then assign a click handler to your button:
$('input[type=submit]').click(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: this.html(data),
success: success,
dataType: dataType
})
return false;
});

Typeahead input field and query passed to PHP with AJAX

I am using Twitter Bootstrap Typeahead for an autocomplete field.
End state goal: The user first enters details into field 1. When they enter details in field 2, ajax passes the query as it is written to a PHP file which queries a database based on what was also entered into field 1.
How do I pass both the query from field 2 and the contents of field 1 to the PHP file and access them.
Here is what I have so far:
HTML FILE:
<div class="field1">
<input type="text" id="field1" data-provide="typeahead" name="field1">
</div>
<div class="field2">
<input type="text" id="field2" data-provide="typeahead">
</div>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/bootstrap.js"></script>
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
PHP FILE:
if (isset($_POST['query'])) {
$db_server = mysql_connect("localhost", "root", "root");
mysql_select_db("db_test");
$query = $_POST['query'];
$other = '**This needs to be field 1**';
$sql = mysql_query("SELECT * FROM table WHERE row1 LIKE '%{$query}%' AND row2 = '$other'");
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
$array[] = $row['row1'];
}
echo json_encode($array);}
At the moment, the query part works perfectly and the results are returned (the console also displays the value from 'Field1'. Just need to get that value into the php file at the same time!
Any help would be great
If I understood this correctly, you want to parse both the values of field 1 and 2 to the same AJAX call. This is how you do it.
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query + '&field1=' + textVal,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
Now you just make another $_POST['field1'] in your PHP file.
var userQuery = $('#ID of query input element').val();
var field1 = $('#ID of input 1 element').val();
$.ajax({
type: "POST",
url: '',
data: {query: QueryVariable, input1: input1variable},
success: function(data) {
// code within this block
},
error: function() {
alert('System Error! Please try again.');
},
complete: function() {
console.log('completed')
}
}); // ***END $.ajax call

PHP: Problem submitting form in AJAX/JSON?

currently I have following code:
home.php
<form name='myformname' id='myformid'>
<input type='text' name='mytext1' value='abc'>
<input type='text' name='mytext2' value='123'>
<input type='submit' value='Submit'>
</form>
<div id='textone'></div><div id='texttwo'></div>
_home.php
$arr = array( 'textone' => $_POST['mytext1'], 'texttwo' => $_POST['mytext2'] );
echo json_encode( $arr );
ajax.js
jQuery('#myformid').live('submit',function(event) {
$.ajax({
url: '_home.php',
type: 'POST',
data: $('#myformid').serialize(),
success: function( data ) {
// TODO: write code here to get json data and load DIVs instead of alert
alert(data);
}
});
return false;
});
Output on submit:
{"textone":"abc","texttwo":"123"}
Question
I want to load mytext1 value in textone DIV and mytext2 value in texttwo DIV using json data in _home.php
Hint: I am using this answer to do the same task on link click event. But how to do this on form submission ?
Thanks
You just wanna parse that JSON and set the divs to the values it contains right?
var divs = JSON.parse(data);
for (var div in divs) {
document.getElementById(div).innerHTML = divs[div];
}
(Previous poster's syntax is probably more like what you're after, and maybe is more cross-browser compatible, but doesn't include the JSON parsing.)
Since JSON is just a subset of JavaScript, you can just eval() it. JSON.parse() basically does that, but gives you assurances that if 'data' contains some nasty code instead of a simple object, it won't be evaluated.
In the success function
for (prop in data){
$('#' + prop).html(data[prop]);
}
Here is my complete JS solution:
jQuery('#myformid').live('submit',function(event) {
$.ajax({
url: '_home.php',
type: 'POST',
dataType: 'json',
data: $('#myformid').serialize(),
success: function( data ) {
for(var id in data) {
//jQuery('#' + id).html(data[id]); // This will also work
document.getElementById(id).innerHTML = data[id];
}
}
});
return false;
});

Categories