Resetting a div to load new json/ajax information? - php

Alrighty. So it's been a while since i've worked with Ajax/json/jquery/javaeverything and I cannot for the life of me remember how to "reset" a div/wipe the buffer after running a json/ajax function.
Case in point: I've got a button that is effected by ajax function, the code is below.
function CMA(id)
{
$('#capture').on('click',function(){
$.ajax({
url:'cma.php',
type:"POST",
data:{sid:id,uid:uid},
dataType:"json",
success: function(data) {
if(data.status == 'attack')
{
$('#capture').fadeOut('slow',function(){
$(this).html('CAPTURING').prop('disabled',true).fadeIn('slow')});
}
}
})
});
}
It is directly effecting this bit of code
$html .="<table>
<tr>
<th colspan='2'>Star Information</th>
</tr>
<tr><th>Star ID</th><td id='starID'></td></tr>
<tr><th>Current Owner</th><td id='owner'></td></tr>
<tr><th colspan='2'><button id='capture'>CAPTURE</button></th></tr>
</table>";
($html is echoed else where but that's a lenghty bit of code)
The information in the starID information will change, so does the owner information (as far as I can tell). However, the CAPTURE button will not change back. as I've said, It's been a while since i've worked with anything java, so if this is something super obvious, i apologize -- but my google foo is failing me spectacularly and my brain is running solely off mountain dew and pringles.

Related

Ajax not sending PHP POST data

I'm using the following ajax script to POST data back after re-sorting the rows (which works fine). I'm not getting anything in the alert(data) that is being shown once I drag-and-drop the row. It should show me what it's trying to pass to the 'refresh_order.php' file.
I am NOT a jQuery or ajax expert -- I found this bit of code online and the first part works for me (the dragging and dropping) but I don't know what's wrong with the ajax that posts the data back to MySQL.
What do I need to do to fix this?
$('tbody').sortable({
cancel: ":input,button,[contenteditable]",
axis: "y",
update: function (event, ui) {
var data = $(this).sortable('serialize');
alert(data); // Sent to server
$.ajax({
data: data,
type: 'POST',
url: 'refresh_order.php',
success: function(response) {
// alert(response); // Server response
}
});
}
});
[I have looked through most of the posts here on Stack Overflow and seen nothing that helps my situation. I even tried to reach out to the person who I got the code from but haven't received a response.]
From the documentation:
Note: If serialize returns an empty string, make sure the id attributes include an underscore. They must be in the form: "set_number" For example, a 3 element list with id attributes "foo_1", "foo_5", "foo_2" will serialize to "foo[]=1&foo[]=5&foo[]=2". You can use an underscore, equal sign or hyphen to separate the set and number. For example "foo=1", "foo-1", and "foo_1" all serialize to "foo[]=1".
I assume your tr elements are missing the id attributes in the appropriate format. Here's a working example:
<table>
<tbody>
<tr id="tr_1">
<td>r1c1</td>
<td>r1c2</td>
</tr>
<tr id="tr_2">
<td>r2c1</td>
<td>r2c2</td>
</tr>
</tbody>
</table>
$('tbody').sortable({
cancel: ":input,button,[contenteditable]",
axis: "y",
update: function(event, ui) {
var data = $(this).sortable('serialize');
console.log(data);
}
});
https://jsfiddle.net/bwxmfzs5/

Ajax serialize() form error

There have been similar questions, but I have browsed them a lot and found no accurate answer or fix so please offer a solution!
I am ajaxing a form to a page, and expecting a value back - no big deal. I've done it a million times before, but now it just refuses to work for this one form.
form html:
<form class="selectClaimType" action="place.php" method="post">
<select id="claimtype" name="claimtype">
<option value="privatebuilding">Private Building</option>
<option value="communalbuilding">Communal Building</option>
<option value="outside">Stored Outside</option>
</select>
<input type="submit" id="submit2" name="submit2" class="button" value="save"/>
</form>
jQuery:
$('form.selectClaimType').on('submit',function(e) {
console.log('found');
$form = $(this);
console.log($form.serialize());
e.preventDefault();
$.ajax({
url: "place.php", //$form.attr('action'),
type: "post", //$form.attr('method'),
data: $form.serialize(),
success: function(data) {
console.log(data);
if (data == 1) {
console.log('hello');
}
else {
console.log('failure to change claim type'+data);
}
},
data: function(data) {
console.log('error ajaxing'+data);
}
});
});
The form is not dynamically created, and as you can see I have console.log(ged) nigh on everything. So I know that the form.serialize() is working (values appear as expected). I left out the preventDefault() to test, and the get values were correct.
I have tried dataTypes of script, html, text, xml and json - no success.
I have a var_dump of $_REQUEST and $_POST on the posted to page - these are both empty arrays. I have changed the page that the post is sent to - still doesn't work.
Any ideas at all?
Maybe it is failing. Have you added a fail() callback to see if you get any output from that. Maybe the error is where you are submitting.
data: $form.serialize(),
....
data: function(data) {
console.log('error ajaxing'+data);
}
Probably a conflict here...maybe meant error: ?
This does not answer you question but maybe it solves your problem.
new FormData(form)
is a new native way to send a form.(including files)
Check the pure javascript way to send forms with xhr2.
support all modern browser including mobile devices & ie10
function ajax(a,b,e,d,c){
c=new XMLHttpRequest;
c.onload=b;
c.open(e||'get',a);
c.send(d||null)
}
// Url,callback,method,formdata or {key:val},placeholder
Send the whole Form
var form=document.getElementsById('myForm');
form.onsubmit=function(e){
e.preventDefault();
ajax('submit.php',SUCCESSFunction,'post',new FormData(this));
}
More info
https://stackoverflow.com/a/20476893/2450730 with working copy & past php page.
if you have any questions just ask.

complex jqueryui dialog

Okay, that's a presumptuous title - it's complex to me.
Overview: (See screenshots and UPDATE at bottom.)
a. On $(document).ready, jQuery/AJAX builds table with one contact per row
b. Each table row, 3rd cell, is: <a id="edit_83">edit</a> tag -- "83" is example and represents the contact_id from db, so each a tag will have a unique id number that is used in step (d)
c. As table being built, construct jqueryui dialog (autoOpen=false) for each contact in AJAX callback
d. when any edit anchor is clicked, jquery splits off the contact_id and uses that to display the appropriate jQueryUI dialog.
Objective: Clicking on edit link in any table row opens a jqueryui dialog with edit form for that contact.
Problem: The form opens, but there are no form fields inside. In fact, in the DOM the injected form/div is missing for each table row. ???
HTML:
<div id="contact_table"></div>
Javascript/jQuery - AJAX call:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "ax_all_ajax_fns.php",
data: 'request=index_list_contacts_for_client&user_id=' + user_id,
success: function(data) {
$('#contact_table').html(data);
var tbl = $('#injected_table_of_contacts');
tbl.find("div").each(function() {
$(this).dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
buttons:
{
Okay: function() {
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
})
});
}
});
});
AJAX/PHP 1 - ax_all_ajax_fns.php:
}else if ($_POST['request'] == 'index_list_contacts_for_client') {
$user_id = $_POST['user_id'];
$r = build_contact_table_for_client($user_id);
echo $r;
}
AJAX/PHP 2: - functions.php
function build_contact_table_for_client($user_id) {
$aContact_info = get_contact_data_ARRAY_user_id($user_id, 'first_name','last_name','email1','cell_phone', 'contact_id');
$r = '<table id="injected_table_of_contacts">
<tr>
<th width="120">Name</th>
<th width="200">Email Address</th>
<th width="100">Cell Phone</th>
<th>Action</th>
</tr>
';
while ($rrow = mysql_fetch_array($aContact_info)) {
$r .= '
<tr>
<td>'.$rrow['first_name'].' '.$rrow['last_name'].'</td>
<td>'.$rrow['email1'].'</td>
<td>'.$rrow['cell_phone'].'</td>
<td>
<a class="editcontact" id="edit_'.$rrow['contact_id'].'" href="#">edit</a>
/
<a class="delcontact" id="del_'.$rrow['contact_id'].'" href="#">del</a>
<div id="editThisContact_'.$rrow['contact_id'].'" style="display:none">
<form name="editForm" onsubmit="return false;">
<p class="instructions">Edit contact information:</p>
First Name:<span style="padding:0 20px;">Last Name:</span><br />
<input type="hidden" id="fn_'.$rrow['contact_id'].'" value="'.$rrow['first_name'].'">
<input type="hidden" id="ln_'.$rrow['contact_id'].'" value="'.$rrow['last_name'].'">
Email:<span style="padding:0 20px;">Cell Phone:</span><br />
<input type="hidden" id="em_'.$rrow['contact_id'].'" value="'.$rrow['email1'].'">
<input type="hidden" id="cp_'.$rrow['contact_id'].'" value="'.$rrow['cell_phone'].'">
</form>
</div>
</td>
</tr>
';
}
$r .= '</table>';
return $r;
}
jQuery - document.click event - if injected code missing, how is it able to find the selector??
$(document).on('click', '.editcontact', function(event) {
var contact_id = this.id.split( 'edit_' )[1];
var etc = $( '#editThisContact_' + contact_id );
etc.dialog("open");
});
UPDATE - PARTIAL SOLUTION:
The dialog is now appearing - the cancel button was out of place, per this post. However, the injected code has vanished. Nothing else changed - just got the dialog code working by fixing syntax error in placement of cancel button.
In response to the question on my comment on the original post:
You really already know JSON, it stands for JavaScript Object Notation. This is a JSON object:
{"a":1,"b":2,"c":3}
look familiar? JSON is just a fancy name for something we've been using a long time (that may not be 100% true, but it's how I see it.)
The idea is to have the server pass back JSON objects and have your JavaScript create/update HTML based on them. In your scenario, you were having your PHP build multiple HTML dialogs. Instead, you would have your PHP pass back an array of objects each one representing a single row from your table, like so:
{
"records":
[
{
"field a":"value a",
"field b":"value b"
},
// record 2
{
"field a":"value a",
"field b":"value b"
}
]
}
If you were to request that from the server using .getJSON(), jQuery would automatically read that and give you a an object with a .records property that is an array of objects! Now you can use JavaScript to update a single dialog/form on the screen when they click one of the corresponding records.
Note: You could have PHP just pass back an array of objects, but it is best practice to wrap it in an object above. Many times you'll want other info too, for example, when you are doing paginated search results you're going to need to know the total number of records and what page you're on and maybe other data points.
An added benefit of this is that the server is done much faster. You push all of the display logic onto the client's computer, and hence, can server more pages from the same server.
That's a real brief explanation. There are tutorials and examples ALL OVER the web. Any good Ajax app you use online (GMail for example) uses JSON objects instead of passing huge blocks of HTML around. Here are a few links, Google has quite a few more:
http://php.net/manual/en/function.json-encode.php (turn any variable into a JSON string.)
http://www.json.org/example.html
http://www.w3schools.com/json/default.asp
http://www.jsonexample.com/
PHP Example: http://www.electrictoolbox.com/json-data-jquery-php-mysql/
Another PHP Example: http://www.jquery4u.com/json/ajaxjquery-getjson-simple/ (the alternative method for json-data.php in this link is the way to go, the other way is just silly!)
There are also some really good frameworks out there to help out with this process. I'm a huge fan of both backbone.js and spine.js. Both use jQuery, both help you use best practices when building apps (like MVC.)
It's nice when you solve your own question. Not so nice when the answer is a ID-ten-T error.
In the injected HTML, note the type of the input fields (screenshot 1). Change type to type="text", and all works as desired.
When concepts are new, Occam's Razor moves almost beyond reach.
I still don't understand why I can't see the injected markup, though..!

ajax to retrieve data from another page after post

I know this is very easy, but i only know the DOM equivalent of this code. the very long one. i've already searched trough some of the questions here in stack but i cant seem to find the solution.
so basically i have this script:
function searchNow(str)
{
$.ajax({
url: "search.php",
type: "POST",
async: false,
data: {"search": str},
success: function(data){
alert("test");
$("#result").html(data);
}
});
}
<table>
<tr>
<td>Search: </td>
<td><input type = "text" name = "search" onBlur="searchNow(this.value)"> </td>
</tr>
this will submit search to search.php to do a query search and retrieve the result and display it at id result.
i can do this easily using the old DOM ajax but then i wanna try using this jquery version instead since it is cleaner and maybe faster.
at my search.php
i have this:
$search = $_POST['search'];
return $search;
sadly i cant seem to return anything at all.
some input would be greatly appreciated, im already starting to be familiar with jquery ajax but only on the same page, not on inter page manipulation.
thank you,
-magician
Your PHP file should output the value. The ajax is going read that page and get it's content.
$search = $_POST['search'];
echo $search;
You want to be doing echo $search rather than return.
You can also add print_r($_POST); to take a look at what is going on in the PHP side of things.
Once you see what that is doing you can develop your php script a little further.
// Sets the correct response type
header('Content-type: application/json');
// get your search string/query
$search = $_POST['search'];
/*
* Do whatever you need in order to get a result
*/
echo json_encode($result);
exit;
If you are passing the search query to a database be sure to read Nettuts great intro to PDO. There are a lot of common pitfalls that can lead to security issues/exploits - avoiding one of the main ones (SQL injection) is covered in that post.
As per your comment, make sure your page with the search field is properly including jquery in the right place (sorry I don't mean to patronise if this is obvious!)
<html>
<head>
<title>Jquery Ajax</title>
<!-- google nicely host jquery for free... -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
function searchNow(str)
{
$.ajax({
url: "search.php",
type: "POST",
data: { "search": str },
success: function(data) {
alert("test");
$("#result").html(data);
}
});
}
</script>
<table>
<tr>
<td>Search: </td>
<td><input type="text" name="search" onBlur="searchNow(this.value)" /></td>
</tr>
</table>
<div id="results"></div>
</body>
</html>
Dont forget to create an HTML element with ID="result" used by the selector to contain the result printed by your search.php.
$("#result").html(data);
Your PHP file should output the value. The ajax is going read that page and get it's content.
$search = $_POST['search'];
echo $search;
Also, the success option is set to be deprecated in the future releases of jQuery. You should instead use .done(callbackFunction) like so:
$.ajax({
url: 'beh.php',
type: 'POST',
data: {search: "beeeeeeeh"}
}).done(function () {
// do stuff
})
Also, is there any reason in particular why you are setting async to false?
I tried using
type: 'GET'
and in php file, got the value as
$search = $_GET['search'];
echo $search;
It worked. Hope it works for you also.

Cascading select

Sorry in advance everyone for this question as I know the cascading select boxes has been done to death but I can't seem to find any good help. I've tried various things but it all seems to fail and I'm not understanding why.
Here's the jquery I have currently:
function tester() {
$("select#type").attr('disabled', 'disabled');
$("select#cat").change(function(){
var vid = $("select#cat option:selected").attr('value');
var request = $.ajax({
url: "show_type.php",
type: "POST",
data: {id : vid}
});
request.done(function(msg) {
$("#result").html( msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
});
}
Don't mind the first section of the code with the select#type and select#cat as these are for what I was trying to get the code to populate at first, however the .change is my trigger for the .ajax request. The rest of the code I'm merely trying to dump a simple return message into an empty div#result upon a successful ajax request.
I ran a test, and the var vid populates correctly.
Here's the simple PHP file I'm trying to call with the ajax:
<?php
$requ;
if (isset($_POST['id'])) {
$requ = 'Worked';
} else {
$requ = "didn't work";
}
echo $requ;
?>
I thought perhaps the problem was the id wasn't being passed properly so I altered the PHP script to give me any valid output regardless of whether the $_POST was set or not.
I won't post the HTML as I'm just trying to dump this all into a div while I test it. When I run the script I get the 'Request Failed' error message with a message of "error".
Here is the other jquery & PHP I have also tried, using the .post instead of the .ajax:
function tester() {
$("select#type").attr('disabled', 'disabled');
$("select#cat").change(function(){
$("select#type").html("<option>wait...</option>");
var vid = $("select#cat option:selected").attr('value');
$.post("show_type.php", {id:vid}, function(data){
$("#result").empty().append(data);
}, "json");
});
}
And the PHP to accompany this particular jquery:
$requ = $_POST['id'];
$ret = 'You selected: ' . $requ;
echo json_encode($ret);
Again, it all failed. I also tried the above code without using the json encoding/parameters. All I want to do is a simple (so I would think) cascading select dropboxes. The second box to be dependent of the first boxes selection. I'm beginning to think that this all just may not be worth it and just sticking strictly to PHP with links to resubmit the page with a GET and populate a new section or div with the results of the first click. Any help or suggestions you might have would be greatly appreciated, I've spent 2 solid days trying to figure this all out. Thanks in advance
Alright, I got it fixed. Thanks to Mian_Khurram_ljaz for making me take a different look at the hierarchical structure of the file. I was assuming that since the js was calling the php file, by placing the php file in the same folder as the js, I could call the php by using the url: show_type.php but that was actually wrong. The structure is considered from the actual page invoking the js and php, and therefore the url should have been js/show_type.php since I had the show_type.php file in my js folder.
It's always the little mistakes that take you days to figure. For those in the future looking to find decent code for cascading select drop boxes, here is my functioning and fully expanded code (which also includes a tri-level cascade)
jQuery:
function project() {
$("select#model2").attr('disabled', 'disabled');
$("select#brand2").attr('disabled', 'disabled');
$("select#project").change(function(){
$("select#model2").attr('disabled', 'disabled'); // if changed after last element has been selected, will reset last boxes choice to default
$("select#model2").html('<option selected="selected">Choose...</option>');
$("select#brand2").html("<option>Please wait...</option>");
var pid = $("select#project option:selected").attr('value');
$.post("handler/project.php", {id:pid}, function(data){
$("select#brand2").removeAttr("disabled");
$("select#brand2").html(data);
});
});
$("select#brand2").change(function(){
$("select#model2").html("<option>Please wait...</option>");
var bid = $("select#brand2 option:selected").attr('value');
var pid = $("select#project option:selected").attr('value');
$.post("handler/projBrand.php", {proj: pid, bran: bid}, function(data){
$("select#model2").removeAttr("disabled");
$("select#model2").html(data);
});
});
}
Just call the function in the $(document).ready of your js.
Notice the comment, having this 'redundant' call to disable and force the last box to select the default is just in case the user makes a selection in all 3 boxes but goes back to the first box and changes the selection.
Here is the php handler file:
<?php
include_once('../includes/file.inc');
$request = $opt -> getModelvBrand();
echo $request;
?>
The other handler file for the jQuery is nearly exactly the same, only invoking a different method in the class file.
And lastly, the HTML:
<form action="" method="post">
<select id="project">
<option value="0">Choose...</option>
<?php echo $opt -> getProject();?> //populates first box on page load
</select>
<select id="brand2">
<option value="0">Choose...</option>
</select>
<select id="model2">
<option value="0">Choose...</option>
</select>
<br /><br />
<input class="like-button" type="submit" title="Submit" value="" />
</form>
Thanks again Mian for making me take a different look at my file(s).
Hope this code helps someone else in the near future.

Categories