I am trying to to an on the fly database update of a select field but there can be more than one instance on the page of this field. I had this working for a single on change select field change, but with more than one I am simply passing the values for the first one.
I have in the past dealt with creating unique DOM ids for these on the page, but in this instance with a select field and using the change function I am a bit befuddled. Also most of the situations I found in searching this were not for select fields or dealing with passing variables in this way. I am fully aware this is crude and probably there is a much better way to accomplish this task.
$('.preferenceData').change(function(){
$.ajax({
type: 'POST',
url: "save_preferences.php",
data: {data1: $('.preferenceData').val(), data2: $('#userID').val()}, // this second data element not really needed but is passing var
dataType: 'text',
success: function(html){
if(html) {
$("div#updateDisplay").replaceWith('<div id="updateDisplay">' + html + '</div>');
}
})
});
The form bit:
echo '<div id="userPref"><select class="preferenceData" name="preferenceData'.$row['uid'].'">';
$prefs = enum_select($db,'db_table_name','email_preferences');
foreach($prefs as $pref)
{
echo '<option value="'.$pref['value'].'-'.$data['topicid'].'-'.$row['uid'].'"'.($row['email_updates'] == $pref['value'] ? ' selected' : '').'>'.$pref['display'].'</option>';
}
echo '</select></div>';
The function it's passed to:
function save_preferences()
{
if ( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' )
{
$db = new db(0);
$vars = $_POST['data1'];
$data = explode("-", $vars);
// Update Database
$data = $db->Exec('UPDATE km_vendors_users SET email_updates = "'.$data[0].'" WHERE vid = "'.$data[1].'" AND uid = "'.$data[2].'"');
if($data==false)
{
echo $db->log;
//return false;
}
else
echo '<img src="/images/icons/success_check_animated.gif">';
}
}
For your code, you are trying to pass $('.preferenceData').val() for data1, which will be fairly unexpected results (and usually not a value).
Instead you can use $(this).val() which refers the specific element that changed, and its value.
$('.preferenceData').change(function(){
$.ajax({
type: 'POST',
url: "save_preferences.php",
data: {data1: $(this).val()},
...etc...
});
});
Related
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've been googling for a way to do this but everything I have found doesn't help me.
I'm not sure how to post all the below variables, If I select only one of them it'll post just fine as well as putting it into the correct database column.
any help would be much appreciated.
function submit() {
var mm10 = $('#10MM'),
mm16 = $('#16MM'),
mm7 = $('#7MM'),
mm2 = $('#2MM'),
fines = $('#Fines'),
bark = $('#Bark'),
cqi = $('#CQI');
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: ,
success: function(){
$("#successMessage").show();
}
});
};
You can do it in two ways. One using arrays, or two using objects:
function submit() {
var mm10 = $('#10MM').val(),
mm16 = $('#16MM').val(),
mm7 = $('#7MM').val(),
mm2 = $('#2MM').val(),
fines = $('#Fines').val(),
bark = $('#Bark').val(),
cqi = $('#CQI').val();
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: [mm10, mm16, mm7, mm2, fines, bark, cqi],
success: function() {
$("#successMessage").show();
}
});
} // Also you don't need a semicolon here.
Also you don't need a semicolon at the end of the function.
Using arrays is easier, if you want more precision, use objects:
function submit() {
var mm10 = $('#10MM').val(),
mm16 = $('#16MM').val(),
mm7 = $('#7MM').val(),
mm2 = $('#2MM').val(),
fines = $('#Fines').val(),
bark = $('#Bark').val(),
cqi = $('#CQI').val();
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: {
"mm10": mm10,
"mm16": mm16,
"mm7": mm7,
"mm2": mm2,
"fines": fines,
"bark": bark,
"cqi": cqi
},
success: function() {
$("#successMessage").show();
}
});
} // Also you don't need a semicolon here.
And in the server side, you can get them through the $_POST super-global. Use var_dump($_POST) to find out what has it got.
Kind of like Praveen Kumar suggested, you can create an object. One thing I was curious about, it looks like you're passing jQuery objects as your data? If that's the case, $_POST is going to say something like [object][Object] or, for me it throws TypeError and breaks everything.
var form_data = {};
form_data.mm10 = $('#10MM').val(); // Input from a form
form_data.mm16 = $('#16MM').val(); // Input from a form
form_data.mm7 = $('#7MM').val(); // Input from a form
form_data.mm2 = $('#2MM').text(); // Text from a div
form_data.fines = $('#Fines').text();
form_data.bark = $('#Bark').text();
form_data.cqi = $('#CQI').text();
$.ajax({
type: "POST",
url: "classes/Post/ChipSubmit.php",
data: form_data,
success: function() {
alert('success');
}
});
}
Then to get those values in your PHP you'd use:
$_POST[mm10] // This contains '10MM' or the value from that input field
$_POST[mm16] // This contains '16MM' or the value from that input field
$_POST[mm7] // This contains '7MM' or the value from that input field
$_POST[mm2] // This contains '2MM' or the value from that input field
And so on...
I tried to put together a jsFiddle for you, though it doesn't show the PHP portion. After you click submit view the console to see the data posted.
Im currently trying to do the follow:
Request a PHP file from my image.js code
In the request call - query out data from my mysql database and save
it in a PHP array
Return the array to image.js as a JSON object.
I got nr 1 + nr 3 covered - what im strugling with is how to save my database attributes correctly into the PHP array and afterwards iterate through each record from the json callback.
Database attribute example:
player_id (unique key) || player_name || player_country || player_image || player_league ||
Question/Challenge 1: Saving the Array (this is what im not sure of)
while ($row = mysql_fetch_assoc($res))
{
$myCallbackArray[] = array($row['player_id'], $row['player_name'], $row['player_country'], $row['player_image']);
}
- The following array, will just be one "flat-array" with no dimension based on saving all corresponding attributes under seperate player_id's?
To give some some context - and assuming the array is fine, we then in a 'next-step' send it back to JS
$callback = $myCallbackArray;
echo json_encode(array('returned_val' => $callback));
Question/Challenge 2: Accessing the array values in JS (this is what im not sure of)
//Save the data
var url = "request.php"; //
var request = $.ajax({
type: "POST",
url: url,
dataType: 'json',
data: { user_id: id},
success: function(data)
{
//HERE WE HANDLE THE RETURNED ARRAY
if(data.returned_val) {
for( var i = 0; i < data.returned_val.length; i++ ){
//HERE I WOULD LIKE TO MAKE THE DIFFERENT ATTRIBUTES ACCESSABLE
}
},
error:function() {
//FAILURE
}
});
return false;
-So in this part im not sure how to actually handle the multi-dimensional array from PHP. I assume we need to save it out in a Javascript array and then we can probably iterate / access each value through an foreach loop - but yet again,- how im not entirely sure?
I'll suggest to use json_encode:
$myCallbackArray []= (object) array(
"player_id" => '...',
"player_name" => '...',
"player_country" => '...',
"player_image" => '...',
"player_league" => '...'
);
$json = json_encode($myCallbackArray);
$json is actually the following:
[{"player_id":"...","player_name":"...","player_country":"...","player_image":"...","player_league":"..."}]
which is valid JSON and you could easily use it in javascript.
I think your accessing the data wrong in your success function, the data comes back as an array. Here is an example:
var request = $.ajax({
type: "POST",
url: url,
dataType: 'json',
data: {user_id: id},
success: function(data){
var myval = data["returned_val"];
alert(myval);
},
error:function() {
//FAILURE
}
});
I'm implementing a photo tagging system.
in my php file I have:
if($_POST['type'] == "insert") {
$pid = $post->ID;
$tag_name = $_POST['tag_name'];
$tag_link = $_POST['tag_link'];
$pic_x = $_POST['pic_x'];
$pic_y = $_POST['pic_y'];
$arr = array("tag_name" => $tag_name, "tag_link" => $tag_link, "pic_x" => $pic_x, "pic_y" => $pic_y);
add_photo_tag($pid, $arr);
wp_redirect("http://www.test.com");
}
to catch the data. in my js file i have:
$('#tagit #btnsave').live('click',function(){
name = $('#tagname').val();
link = $('#taglink').val();
counter++;
$('#taglist ol').append('<li rel="'+counter+'">'+counter+'. '+name+' (<a class="remove">Entfernen</a>)</li>');
$('#imgtag').append('<div class="tagview" id="view_'+counter+'">'+counter+'</div>');
$('#view_' + counter).css({top:mouseY,left:mouseX});
$('#tagit').fadeOut();
$.ajax({
type: "POST",
url: "content.php",
data: "tag_name=" + name + "&tag_link=" + link + "&pic_x=" + mouseX + "&pic_y=" + mouseY + "&type=insert",
cache: true,
success: function(data) {
alert("success!");
}
});
});
Somehow the variables don't get passed to the php resulting in me not able to save the data properly to database.
The problem must be somewhere in either the $.ajax part or php. Can someone help me?
Well, you're checking post variable $_POST['type'] == "insert_tag" while it's actual value is: &type=insert. Others look fine. Btw never user .live(), it's obsolete, do it with .on()
Also, if all your elements are on a form you may use $('your_form_selector').serialize() - that'l be your post data
Your php code is looking for 'type' to be equal to 'insert_tag'.
Your JavaScript is POSTing with type=insert - so your php code ignores it.
Why are you redirecting in your PHP code? Remove this line:
wp_redirect("http://www.test.com");
You can replace it with some sort of a simple feedback system. After all you want the server-side to pass back the status and maybe some validation messages.
$return = array('status' => 0, 'msg' => 'all is well');
if(!add_photo_tag($pid, $arr)) {
$return['msg'] = __('Could not add photo tag.');
$return['status'] = -1;
}
echo json_encode($return);
Try with the following code:
$.ajax({
type: "POST",
url: "content.php",
data: {"tag_name": name,"tag_link":link,"pic_x": mouseX,"pic_y":mouseY, "type":"insert"},
//change here like I have done
cache: true,
success: function(data) {
alert("success!");
}
});
And Replace the if($_POST['type'] == "insert_tag") line with following:
if($_POST['type'] == "insert")
As the value you are passing of $_POST['type'] is insert not insert_tag.
EDITED:
one more thing as I have found that is you have not used the var before initializing the variable. use the var name = ...
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/