I'm trying to populate a form with jquery's populate plugin, but using $.ajax
The idea is to retrieve data from my database according to the id in the links (ex of link: get_result_edit.php?id=34), reformulate it to json, return it to my page and fill up the form up with the populate plugin. But somehow i cannot get it to work. Any ideas:
here's the code:
$('a').click(function(){
$('#updatediv').hide('slow');
$.ajax({
type: "GET",
url: "get_result_edit.php",
success: function(data)
{
var $response=$(data);
$('#form1').populate($response);
}
});
$('#updatediv').fadeIn('slow');
return false;
whilst the php file states as follow:
<?php
$conn = new mysqli('localhost', 'XXXX', 'XXXXX', 'XXXXX');
#$query = 'Select * FROM news WHERE id ="'.$_GET['id'].'"';
$stmt = $conn->query($query) or die ($mysql->error());
if ($stmt)
{
$results = $stmt->fetch_object(); // get database data
$json = json_encode($results); // convert to JSON format
echo $json;
}
?>
Now first thing is that the mysql returns a null in this way: is there something wrong with he declaration of the sql statement in the $_GET part? Second is that even if i put a specific record to bring up, populate doesn't populate.
Update:
I changed the populate library with the one called "PHP jQuery helper functions" and the difference is that finally it says something. finally i get an error saying NO SUCH ELEMENT AS
i wen into the library to have a look and up comes the following function
function populateFormElement(form, name, value)
{
// check that the named element exists in the form
var name = name; // handle non-php naming
var element = form[name];
if(element == undefined)
{
debug('No such element as ' + name);
return false;
}
// debug options
if(options.debug)
{
_populate.elements.push(element);
}
}
Now looking at it one can see that it should print out also the name, but its not printing it out. so i'm guessing that retrieving the name form the json is not working correctly.
Link is at http://www.ocdmonline.org/michael/edit_news.php with username: Testing and pass:test123
Any ideas?
First you must set the dataType option for the .ajax call to json:
$.ajax({dataType: 'json', ...
and then in your success function the "data" parameter will already be a object so you just use it, no need to do anything with it (I don't know why you are converting it into a jQuery object in your code).
edit:
$( 'a' ).click ( function () {
$( '#updatediv' ).hide ( 'slow' );
$.ajax ( {
type: "GET",
url: "get_result_edit.php",
success: function ( data ) {
$( '#form1' ).populate ( data );
},
dataType: 'json'
} );
$( '#updatediv' ).fadeIn ( 'slow' );
return false;
}
also consider using $.getJSON instead of $.ajax so you don't have to bother with the dataType
Try imPagePopulate (another jquery plugin). It may be easier to use:
http://grasshopperpebbles.com/ajax/jquery-plugin-impagepopulate/
Related
I'm trying to push an array from jquery to a php function and I'm out of options to make it work. I've tried multiple options; $_request, $_post, with JSON.stringify, without JSON.stringify, ...
But I keep getting 'null'; can't figure out the right combination. Someone who's willing to explain me why it's not working and how to fix?
JQuery code:
var userIDs = [];
$( "tr.user-row" ).each(function() {
var userID = $(this).attr("data-userid");
userIDs.push(userID);
});
var jsonIDs = JSON.stringify(userIDs);
$.ajax({
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'built_ranking', // This is our PHP function below
'data' : {data:jsonIDs},
},
dataType:"json",
success:function(data){
// This outputs the result of the ajax request (The Callback)
//$("tr[data-userid='"+userID+"'] td.punten").html(data.punten);
//$("tr[data-userid='"+userID+"'] td.afstand").html(data.afstand);
console.log(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
PHP code:
function built_ranking(){
if ( isset($_REQUEST) ) {
$data = json_decode(stripslashes($_REQUEST['data']));
foreach($data as $d){
echo $d;
}
print json_encode($data);
//$testResult = array("points"=>"test", "afstand"=>"test");
//print json_encode($testResult);
}
// Always die in functions echoing AJAX content
die();
}
add_action( 'wp_ajax_built_ranking', 'built_ranking' );
If I print the $testResult it returns the array and I can use the data back in jquery, so the function is called.
I've based the code on Send array with Ajax to PHP script
I've multiple ajax calls with $_request instead of $_post and they are working fine. But maybe they can't handle arrays? I've no idea... ^^
What I learned from this question and the help I got: don't guess, debug. try to find ways to see what is posted, what is received, ...
You can read how to 'debug' in the comments of the original question. Useful for starters as me ;)
Working code:
JQuery
var jsonIDs = JSON.stringify(userIDs);
$.ajax({
type: 'POST',
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'built_ranking', // This is our PHP function below
'data' : jsonIDs,
},
dataType:"json",
success:function(data){
// This outputs the result of the ajax request (The Callback)
//$("tr[data-userid='"+userID+"'] td.punten").html(data.punten);
//$("tr[data-userid='"+userID+"'] td.afstand").html(data.afstand);
console.log(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
PHP
function built_ranking(){
if ( isset($_POST) ) {
$data = json_decode(stripslashes($_POST['data']));
print json_encode($data);
//$testResult = array("points"=>"test", "afstand"=>"test");
//print json_encode($testResult);
}
// Always die in functions echoing AJAX content
die();
}
add_action( 'wp_ajax_built_ranking', 'built_ranking' );
I would like to use an autocompletion in my application. I'm trying to use the jquery UI completion but nothing happens. I made an ajax to get all columns with a specific variable written by the user. The query is working, I have my array with all my columns back from the server. With this query reponse, I tried to do the jquery autocompletion in the success ajax but as I said nothing is happening.
Do you have an idea?
function autoCompleteRegate(){
$("#code_regate").keyup(function() {
// AJAX de l'auto-complete
var source = '/gestion/gestDepot/ajaxautocompleteregate';
var codeRegate = $("#code_regate").val();
$.ajax({
type : "POST",
url : source,
async : false,
dataType : 'json',
data : {
'codeRegate' : codeRegate
},
success : function(response) {
var availableTags = response;
$("#code_regate").autocomplete({
source: availableTags
});
}
});
});
public function ajaxautocompleteregateAction()
{
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$params = $this->_getAllParams();
$codeRegate = $params['codeRegate'];
$oDepotService = new Services_Depot();
$response = $oDepotService->searchCodeRegate($codeRegate);
echo json_encode($response);
}
Network query - form
Exemple of nothing happening
The answer from the server
You have to directly pass the cd_regate array instead of a multidimensional array. One workaround is you could process the json output on the backend side :
public function ajaxautocompleteregateAction()
{
$this->_helper->layout->disableLayout();
$this->_helper->viewRenderer->setNoRender();
$params = $this->_getAllParams();
$codeRegate = $params['codeRegate'];
$oDepotService = new Services_Depot();
$response = $oDepotService->searchCodeRegate($codeRegate);
$json = [];
foreach ($response as $key => $value) {
array_push($json, $value->cd_regate); // the output will be "[774970, 774690, 774700,... ]"
}
echo json_encode($json);
}
I would suggest the following for your JavaScript:
$("#code_regate").autocomplete({
source: function(request, response){
$.ajax({
type : "POST",
url : '/gestion/gestDepot/ajaxautocompleteregate',
async : false,
dataType : 'json',
data : {
'codeRegate' : request.term
},
success : function(data) {
response(data);
}
});
}
});
This uses a function as a Source. From the API:
Function: The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete, including JSONP. The callback gets two arguments:
A request object, with a single term property, which refers to the value currently in the text input. For example, if the user enters "new yo" in a city field, the Autocomplete term will equal "new yo".
A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.
When filtering data locally, you can make use of the built-in $.ui.autocomplete.escapeRegex function. It'll take a single string argument and escape all regex characters, making the result safe to pass to new RegExp().
When 1 or more letters are entered into the text field, this will be passed to the function under request.term and you can POST that to your script via AJAX. When you get the result data, it must be in an Array or an Object with the right format.
I am trying to validate list of dynamic text fields.
Validation needs an AJAX call to interact with server.
At the backend I have written just one php file that reads the input request data and performs operation. Below is the example.
abc.js
row_count = 6
for (i = 1; i <=row_count; i++) {
id = "#val"+i.toString() ;
$(id).change(function(){
input_val="random";
$.ajax({
url:"url.php",
type:post,
async:true,
dataType: 'json',
data : {temp:input_val},
success:function(result){},
error: function (request, status, error) {}
});
});
}
url.php
<?php
$random_val = $_POST['temp'];
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
if ($flag == 0){
echo json_encode(array("status"=>'Fail'));
}
else{
echo json_encode(array("status"=>'Success'));
}
?>
It works fine when the row_count = 1 (Just one text field) but fails when the input is more than 1.
When the count is more than 1, the php script is not able to read the request data(The key in JSON data "temp"). it is blank in that case.
Any lead or help should be appreciated.
Thanks
Your javascript bit needs some adjusting, because you do not need to define an ajax for every single element. Use events based on a class. Also, since input behave differently than select, you should setup two different event class handlers.
function validateAjax ( element ) {
var input_val = element.val();// get the value of the element firing this off
$.ajax({
url: "url.php",
type: 'post',
async: true,
dataType: 'json',
data : { temp: input_val },
success: function(result) {
// check your result.status here
},
error: function (request, status, error) { }
});
}
$(".validate_change").on("change",function() { // for selects
validateAjax( $(this) );
});
$(".validate_input").on("input",function() { // for text inputs
validateAjax( $(this) );
});
And for your select or input you add that appropriate class.
<select class="validate_change" name="whatever"><options/></select>
<input class="validate_input" name="blah">
PS
I really worry about this code you have:
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
So, you are just executing anything that is coming in from a webpage POST var??? Please say this website will be under trusted high security access, and only people using it are trusted authenticated users :-)
I'm currently trying to make live form validation with PHP and AJAX. So basically - I need to send the value of a field through AJAX to a PHP script(I can do that) and then I need to run a function inside that PHP file with the data I sent. How can I do that?
JQuery:
$.ajax({
type: 'POST',
url: 'validate.php',
data: 'user=' + t.value, //(t.value = this.value),
cache: false,
success: function(data) {
someId.html(data);
}
});
Validate.php:
// Now I need to use the "user" value I sent in this function, how can I do this?
function check_user($user) {
//process the data
}
If I don't use functions and just raw php in validate.php the data gets sent and the code inside it executed and everything works as I like, but if I add every feature I want things get very messy so I prefer using separate functions.
I removed a lot of code that was not relevant to make it short.
1) This doesn't look nice
data: 'user=' + t.value, //(t.value = this.value),
This is nice
data: {user: t.value},
2) Use $_POST
function check_user($user) {
//process the data
}
check_user($_POST['user'])
You just have to call the function inside your file.
if(isset($_REQUEST['user'])){
check_user($_REQUEST['user']);
}
In your validate.php you will receive classic POST request. You can easily call the function depending on which variable you are testing, like this:
<?php
if (isset($_POST['user'])) {
$result = check_user($_POST['user']);
}
elseif (isset($_POST['email'])) {
$result = check_email($_POST['email']);
}
elseif (...) {
// ...
}
// returning validation result as JSON
echo json_encode(array("result" => $result));
exit();
function check_user($user) {
//process the data
return true; // or flase
}
function check_email($email) {
//process the data
return true; // or false
}
// ...
?>
The data is send in the $_POST global variable. You can access it when calling the check_user function:
check_user($_POST['user']);
If you do this however remember to check the field value, whether no mallicious content has been sent inside it.
Here's how I do it
Jquery Request
$.ajax({
type: 'POST',
url: "ajax/transferstation-lookup.php",
data: {
'supplier': $("select#usedsupplier").val(),
'csl': $("#csl").val()
},
success: function(data){
if (data["queryresult"]==true) {
//add returned html to page
$("#destinationtd").html(data["returnedhtml"]);
} else {
jAlert('No waste destinations found for this supplier please select a different supplier', 'NO WASTE DESTINATIONS FOR SUPPLIER', function(result){ return false; });
}
},
dataType: 'json'
});
PHP Page
Just takes the 2 input
$supplier = mysqli_real_escape_string($db->mysqli,$_POST["supplier"]);
$clientservicelevel = mysqli_real_escape_string($db->mysqli,$_POST["csl"]);
Runs them through a query. Now in my case I just return raw html stored inside a json array with a check flag saying query has been successful or failed like this
$messages = array("queryresult"=>true,"returnedhtml"=>$html);
echo json_encode($messages); //encode and send message back to javascript
If you look back at my initial javascript you'll see I have conditionals on queryresult and then just spit out the raw html back into a div you can do whatever you need with it though.
I'm having trouble figuring out how to display some return JSON objects.
My script works like this:
I'm making an ajax call, sending some params to a CodeIgniter Controller where I'm processing it with a model, making some queries towards an database and then returning the json_encoded rows to the ajax callback function. This works great btw.
Here is what I want to do now and here its where I'm stuck. I want the new JSON objects (contains database rows) to "replace" the old rows in a html table. So I want it to update the table depending on the params I'm passing but only in the tbody mind.
I'm new at jquery so I've tried i few things. I've tried iterate trough the json data and use the $.html(string) function but i guess this replace everything and it will eventually just display the last object(Am i right?).
So I wonder how in a general sense I would do this?
$.ajax({
type: 'GET',
url: 'someSite.com/someEndpoint'
data: xyz.
success: function( response ) {
//lets say you have an object like this: object = { data: { ... } }
var html = '';
for(var i = 0; i<response.data.length; i++) {
html += '<tr><td>'+response.data[i].title+'</td></tr>';
}
$('#someTable tbody').html(html);
}
});
You don't have to return JSON objects in an AJAX request. Try setting the data_type config setting for the $.ajax call to "html" (or leave it blank--jQuery is really good about figuring it out from the response data).
I usually factor out the <tbody>...</tbody> portion of a view to its own view partial. Then, the "original" page load can use it, and so can an updating AJAX call.
The only asterisk to this is if you need some sort of object-oriented response along with the HTML. I would usually do something like this:
{
"stat": "ok",
"payload": "<tr><td>row1</td></tr><tr><td>row2</td></tr>"
}
And then in the ajax success function:
$.post('/controller/action', { some: 'data' }, function(response) {
$('#my_table tbody').append(response.payload);
}, 'json');
What are the params your passing in?
for example you might use a select or input field to trigger an ajax call and pass its value as the param.
var tableObj = {
var init : function(){
//check that your selectors id exists, then call it
this.foo();
},
foo : function(){
var requestAjax = function(param){
var data = {param : param}
$.ajax({
data : data,
success : function(callback){
console.log(callback);//debug it
$("tbody").empty();//remove existing data
for(var i =0; i < callback.data.length; i++){}//run a loop on the data an build tbody contents
$("tbody").append(someElements);//append new data
}
});
}
//trigger event for bar
$("#bar").keyup(function(){
requestAjax($(this).val());
});
}
}
$(function(){
tableObj.init();
})
Your php method
public function my_method(){
if($this->input->is_ajax_request())
{
//change the output, no view
$json = array(
'status' => 'ok',
'data' => $object
);
$this->output
->set_content_type('application/json')
->set_output(json_encode($json));
}
else
{
show_404();
}
}