php ajax display data from database in multiple textboxes - php

Every one am new to php and ajax.
Am writing a code to fetch data from mysql database
and display them in textboxes but is not working.
Here is my code.
I need your help please.
Thanks in advance
$('#btn_get').on('click', function(){
$.ajax({
type : "get",
url : '/path/to/php/file',
success : function(data)
{
$('#input-box1').val(data);
$('#input-box2').val(data);
}
});
});
<input type="text" id="input-box1">
<input type="text" id="input-box2">
<button type="button" id="btn_get">Click</button>
//get data from db here
$textbox1 = 'foo';
$textbox2 = 'deen';
echo $textbox1;
echo $textbox2;

Here are some approaches, maybe them can help you:
The first approach would be to check your console to make sure that the jQuery version allows you to use the $.ajax() resource. Some jQuery versions like the "slim" doesn't provide ajax calls.
Once you have checked that put the property error within your ajax call:
$('#btn_get').on('click', function(){
$.ajax({
type : "get",
url : '/path/to/php/file',
success : function(data)
{
$('#input-box1').val(data);
$('#input-box2').val(data);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
});
If you have a error response you will be able to identify it checking your browser's console tool (F12).
Check your /path/to/php/file to make sure that your file really exists.
Remember that the success callback gets your echo command as a string. So probably your return will be something like this:
foodeen
A good approach would be to return a json response:
$textbox1 = 'foo';
$textbox2 = 'deen';
echo json_encode(array($textbox1 ,"textBox1"));
Finally when your response is executed in the success callback you'll be able to convert it from plain string to a json format:
$('#btn_get').on('click', function(){
$.ajax({
type : "get",
url : '/path/to/php/file',
success : function(data)
{
var response = JSON.stringify(data);
$('#input-box1').val(response[0]);
$('#input-box2').val(response[1]);
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
});

Related

Issues with Jquery/PHP ajax form submission

I am using the following code to post form data to a php file..
jQuery("#form-submit").click(function(data){
var url = "save-data.php";
jQuery.ajax({
type: "POST",
data: jQuery('#my-form').serialize(),
url: url,
cache : "false",
success: function(data){
jQuery("#dl-message").html(data);
jQuery("#dl-message").css('background-color', '#0C3');
jQuery('#dl-message').slideToggle('slow', function() {
jQuery('#dl-message').delay(2000).slideToggle('slow', function() {
//Animation Complete
});
});
},
error: function ( jqXHR, textStatus, errorThrown){
jQuery("#dl-message").html('There was an error saving your form: ' + errorThrown);
jQuery("#dl-message").css('background-color', '#F33');
jQuery('#dl-message').slideToggle('slow', function() {
jQuery('#dl-message').delay(2000).slideToggle('slow', function() {
//Animation Complete
});
});
}
});
return false;
});
and then in my php file I am simply looking for $_POST['field-name'] to see if the contents of the form were posted. The ajax call returns successful, however no data from the form seems to be posted to the PHP file. When I call...
$name = $_POST['name'];
echo "Your name is: " . $name;
I get nothing.... Does anyone see anything wrong with my ajax call at all?
Thanks so much for your time...
So it seems the post was empty at the first place (btw you can include your last three posts inside the question by editing it). Are you sure your form's id is 'my-form'?

Ajax Doesn't give me anything in the console?

Updated Question to better reflect the communities support
Based on community support I have changed the Ajax function to be as such:
(function($){
$(document).ready(function(){
$('a').click(function(e){
var el = $(this).prev('input[type="checkbox"]');
if(el.is(':checked')){
el.prop('checked',false);
}
$.ajax({
url : "http://localhost/wordpress/wp-content/themes/Aisis-Framework/CoreTheme/AdminPanel/Template/Helper/UncheckPackageThemeHelper.php",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
e.preventDefault();
});
});
})(jQuery);
The resulting PHP Class is as such:
class CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper{
private $_element_name = null;
public function __construct(){
if(isset($_GET['element_name'])){
$this->_element_name = $_GET['element_name'];
echo $this->_element_name;
}
}
}
The network tab shows that I have some out put from activating the Jquery which I have shown below:
The Console is spitting out no errors, yet not echoing the element name. I have read up on the Jquery Ajax API and everything I have been doing, thus far, seems to be correct. Yet I am not getting the desired out put.
Note: The response tab is empty.... In other words I am not getting a response back.
You're not passing in the event to your click handler.
Use.
$('a').click(function(e){
// Your code
});
$.ajax({
url : "<?php echo CORETHEME_ADMIN_TEMPLATE_HELPER_URL . 'UncheckPackageThemeHelper.php'; ?>",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(result) {
console.log(result)
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
Simplify the situation. Just for a moment, change your AJAX processor file (UncheckPackageThemeHelper.php) to read like this:
UncheckPackageThemeHelper.php
<?php
$test = $_POST['element_name'];
$r = 'PHP received: [' .$test. ']';
echo $r;
die();
Also, change your AJAX success function to read like this:
success: function(result) {
alert(result);
},
At least, this will show you that your AJAX is getting through.
Then, start adding things back into your AJAX processor file (one or two at a time) and keep echoing something out so that you can discover where the error is happening.
So I was doing a lot of things wrong. But this is the only way it works, for me - please post your comments if you have better solution.
In the class, I have to do this:
class CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper{
private $_element_name = null;
public function __construct(){
if(isset($_GET["element_name"])){
$this->_element_name = $_GET["element_name"];
echo json_encode($this->_element_name);
}
}
}
new CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper();
The class cannot be instantiated in the .phtml file with the resulting Ajax or the request is never sent back. Also notice the json_encode You cannot pass regular variables back to Ajax - when in a class (I think) - How ever when not in a class it seems to work - clarification is needed.
The Ajax then looks like this:
(function($){
$(document).ready(function(){
$('a').click(function(e){
var el = $(this).prev('input[type="checkbox"]');
if(el.is(':checked')){
el.prop('checked',false);
}
$.ajax({
url : "http://localhost/wordpress/wp-content/themes/Aisis-Framework/CoreTheme/AdminPanel/Template/Helper/UncheckPackageThemeHelper.php",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
e.preventDefault();
});
});
})(jQuery);
The Data that comes back is what I expect: "aisis_options[package_RelatedPosts]"
There ar a couple of issues with this answer - One I dont understand why I have to instantiate the class inside the file its written in, and two not sure why I have to encode the response in a class, but not when its just a "script kiddy" file.

Jquery or Ajax if load fails

When you use Jquery or Ajax to call a page or script, which loads into a div,
or example
$.post('pagename.php', $(#cpay'.$id.'").serialize(), function(data) { $('#conSupp".$id."').html(data);
is there a way to display an error message in the div if the page fails to load
Many thanks
If you are using jquery 1.5 or above, the post will return a jqXhr object. If so, you could do something like this:
$.post('pagename.php', data, function(data) {
//success, do stuff with the data object
}).fail(function(jqXhr, ajaxOptions, thrownError){
//something went wrong
alert('Error: ' + thrownError);
});
Yes, bind an error handler, by calling the .fail() function on the jqXhr object returned by the call to $.post():
$.post(url, data, function(data) {
...
}).fail(function(jqXhr, textStatus, errorThrown) {
// an error occurred - do something here
});
I prefer just doing:
$.ajax({
type: 'POST',
url : 'pagename.php',
data: $(#cpay'.$id.').serialize()
}).done(function(data {
$('#conSupp".$id."').html(data);
}).fail(function() {
$('#conSupp".$id."').html('An error occured');
});
It's a little longer, but I find it much easier to read an change to whatever I need, and it's exactly what $.post does internally anyway, so saves me a function call?

JQuery AJAX Issue without error

So I am adding a list of stores to a web page via a jQuery AJAX request. This little utility is not dynamic, just database driven. I have decided to use jQuery/AJAX to transfer the data because when I try to embed PHP in our current PHP CMS, I get a bunch of conflicting errors.
The problem I am having is that I am getting a jQuery AJAX error when trying to make the request to the PHP script, and I am not sure why.
Here is my AJAX request
$(document).ready(function(){
$.ajax({
type:"POST",
url:"getStores.php",
dataType: "json",
success:function(data){
results(data);
},
error: function(data) {
console.log(data.error);
}
});
});
The cryptic console error i am getting is this
function (){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this}
Here is my PHP code if it will be helpful:
//database connection
$return_arr = array();
$sql = mysql_query("SELECT * FROM where_to_buy");
while($row = mysql_fetch_array($sql, MYSQL_ASSOC))
{
$row_array['store_name'] = $row['store_name'];
$row_array['store_url'] = $row['store_url'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
I think the problem might be because I wrapping my JSON in an array?
EDIT:: JSON output from php script as requested
[{"store_name":"Example 1","store_url":"http:\/\/www.example1.com"},{"store_name":"Example 2","store_url":"http:\/\/www.example2.com"}]
Thanks for any help!
The reason you are getting that weird error message is that the error callback for the jQuery ajax function takes 3 arguments instead of 1, as described in the docs here: http://api.jquery.com/jQuery.ajax/
The first argument is a jQuery-special XMLHttpRequest object, which has a property called error that contains the function you are seeing logged to your console. The actual error that occurred during execution of your ajax call is the passed in to the error callback as the 3rd argument.
To see it, you should do something like:
$(document).ready(function(){
$.ajax({
type:"POST",
url:"getStores.php",
dataType: "json",
success:function(data){
results(data);
},
error: function(jqXHR, text, error) {
console.log(error);
}
});
});
That will get you closer to the real problem.
UPDATE:
Please show the output from your php script. It may be that it is not returning valid json. As noted in the php docs ( http://php.net/manual/en/function.json-encode.php ), [json_encode] only works with UTF-8 encoded data.
You might also check in to json_last_error ( http://php.net/manual/en/function.json-last-error.php ) to see if the encoding failed for some reason.
UPDATE 3:
It seems like your problem may be the path to the php script.
try it with:
$(document).ready(function(){
$.ajax({
type:"POST",
url:"/getStores.php", // <-- notice the leading slash!!!
//dataType: "json",
success:function(data){
//results(data);
console.log(data);
},
error: function(jqXHR, text, error) {
console.log(error);
}
});
});
or, putting it all back together if the above logs the correct json output to the console...
$(document).ready(function(){
$.ajax({
type:"POST",
url:"/getStores.php",
dataType: "json",
success:function(data){
results(data);
},
error: function(jqXHR, text, error) {
console.log(error);
}
});
});

Trying to make AJAX work on simple login form

I have been trying for hours to make this work but I am not getting anything back when doing the ajax call. I am new to Ajax and it could probably be something you will see but that I am unable to. I would appreciate you help. Here is my code.
HTML
<script>
$("#submitlogin").click(function() {
inputs = {
"logInUsername" : $('input[name=logInUsername]').val(),
"logInPassword" : $('input[name=logInPassword]').val()
};
// since this is a username and password combo you will probably want to use $.post
$.ajax ({
type: "POST",
url: "loggnow.php",
data: inputs,
success: function() {
$("#login").html("You are now logged in!");
}
});
});
</script>
loggnow.php
<?php
extract($_POST);
if($_POST)
{
echo 'Yes the ajax posted';
}
?>
Try this :
$(document).ready(function(){
$("#submitlogin").click(function() {
inputs = {
"logInUsername" : $('input[name=logInUsername]').val(),
"logInPassword" : $('input[name=logInPassword]').val()
};
// since this is a username and password combo you will probably want to use $.post
$.ajax ({
type: "POST",
url: "loggnow.php",
data: inputs,
success: function() {
$("#login").html("You are now logged in!");
},
error : function(jqXHR, textStatus, errorThrown){
alert("error " + textStatus + ": " + errorThrown);
}
});
});
});
This will give you an alert if an error occurs in AJAX with details
EDIT:
As Leo pointed it out, your code might be executing too fast, try the modified code above so that you make sure it runs after all the page has loaded
Try to put your function inside
$(function(){
//attach the button click here
});
this way your code will only run after the body loaded (so you are sure that you button exists) - look here
you just need a web server host looks like this:http://127.0.0.1:8084/xxx

Categories