How to separate data received from $.get() callback function - php

I have this:
<div ><span id="compareResult"></span> <span id="result"></span></div>
$.get(
'data.php',
{ valA: $(this,'option:selected').val() , valB:$(this,'option:selected').val()},
function(childData){
$('#result').html(childData).css('display', 'none')});>
PHP:
function getData($names,$id,$flag){
if($flag==0){
$strResult = '<select multiple class="sel" id="selectname" size='.count($names).'>';
}
if($flag==1){
$strResult = '<select multiple class="sel" id="selname" size='.count($names).'>';
}
for($i=0; $i<count($names); $i++)
{
$strResult.= '<option value='.$id[$i].'>'.$names[$i].'</option>';
}
echo $strResult.= '</select>';}
How do I break apart/parse the response inside .html(childData) so I can put it in different span(i.e. id="compareResult")?
Thanks in advance.

This doesn't directly answer your question, but it answers what I think the real question might be.
If the data is coming from your own server, I strongly recommend you look at the jQuery Taconite plugin. It makes child's play of doing multiple-element updates via AJAX. All you have to do is make a slight change to the format of how the data is delivered to the browser.
Seriously, check it out.

After you make the html call to update #result's HTML, you will be able to access anything that was inserted inside #result in subsequent calls.
For example:
$.get(
'data.php',
{ valA: $(this,'option:selected').val() , valB:$(this,'option:selected').val()},
function(childData){
$('#result').html(childData).css('display', 'none');
$('#result #someContainer').appendTo('#compareResult');
}
);

I responded to a similar question recently, but you can actually grab any information you might need from the HTML response by creating a jQuery object of the response. For example:
var response = $("<div>This is my element <span class='a-thing'>Thing</span></div>");
alert(response.find('.a-thing').text());
In your callback, you could do the same thing:
$.get(
'data.php',
{ valA: $(this,'option:selected').val() , valB:$(this,'option:selected').val()},
function(childData){
var result = $(childData);
alert(result.find('.some-selector').text());
}
});

Related

Ajax output to second div using PHP

I am a new user of ajax; so...
I am using ajax on a simple html page to access a php script to receive data, calculate results using data in an mysql table, and echo results in a div on the same page. My javascript statement to do this is:
$.post('ajax/phpscript.php', {
postuser:theuser,
postname:uans1
}, function(data) {
$('#outputdiv1').html(data);
}
);
The php echo output goes to a div on the main page called outputdiv1.
I got that part; no problem. Not sure exactly how it works, but it does work.
I would also like to echo output to a different div (which I will call outputdiv2) on the same page, using the php script. In my php script, How do I refer to or echo output this other div?
I guess I could have a second $.post statement in the javascript code, accessing a second php script. But that would force me to access the mysql database a second time. Doesn't seem efficient to me.
Is there a better way to do this?
Thanks.
HTML code is here:
theuser is defined earlier
<table width=400 align=center><tr><td>
There is a question here, with 2 possible answers:<p>
<form>
<input type=radio style="width:22px; height:22px" name="ques1" id="opt1" value="answer 1" onclick="post1()"> answer 1<br>
<input type=radio style="width:22px; height:22px" name="ques1" id="opt2" value="answer 2" onclick="post1()"> answer 2<br>
</form>
<div id="outdiv1">first response from php will go here, beneath the question.<br></div>
<script type="text/javascript">
function post1() {
var uans1 = "none"
if (document.getElementById("opt2").checked) {
uans1 = "answer 2"
}
if (document.getElementById("opt1").checked) {
uans1 = "answer 1"
}
$.post('ajax/phpscript.php',{postuser:theuser,postname:uans1}, function(data) {$('#ans1div').html(data);});
}
</script>
</td>
<td width=20%>
<div id="outputdiv2">
second response from php will go here, to the right of the question.<p>
</div>
</td>
</tr></table>
first response will not be the same as the second response.
You could use JSON to communicate and return an array. something like this in js
$.ajax({
url: 'ajax/phpscript.php',
method: 'POST',
data: {
postuser: theuser,
postname: uans1
},
dataType: 'JSON'
}).done(function(data) {
if ($.isArray(data)) {
$('#outputdiv1').html(data[0]);
$('#outputdiv2').html(data[1]);
}
});
And your php script should do something look like this
<?php
include('dbconnection.php');
$result = [];
//SELECT data for div1 (part you already have)
$result[] = $mysql_result_as_html_for_outputdiv_1; // In your case this would be a html string
//SELECT other data for div2
$result[] = $mysql_result_as_html_for_outputdiv_2; // In your case this would be a html string
header('Content-Type: application/json');
echo json_encode($result);
?>
An even more clean solution would be to just return the data as objects from php and make some templates in js suitable for your data.
You need to understand this: who write in the div is javascript, not php, cause you are using ajax. Ajax is a way to comunicate with php, and give a response. Now you need to handle this response with javascript.
If you want to put the same content in outputdiv1 and outputdiv2, you not need to post ajax again, only write it in two divs.
$.post('ajax/phpscript.php',{postuser:theuser,postname:uans1}, function(data) {$('#outputdiv1').html(data);$('#outputdiv2').html(data);});
if you want different data i suggest you think the system to get all result that you need in one post request and return it in a json format (see http://php.net/manual/es/function.json-encode.php), so you can handle better with JSON.parse() in client side.

AJAX\JQUERY: Update MYSQL database with form data without refreshing

Ok, so I've gotten most of this thing done.. Now comes, for me, the hard part. This is untreaded territory for me.
How do I update my mysql database, with form data, without having the page refresh? I presume you use AJAX and\or Jquery to do this- but I don't quite grasp the examples being given.
Can anybody please tell me how to perform this task within this context?
So this is my form:
<form name="checklist" id="checklist" class="checklist">
<?php // Loop through query results
while($row = mysql_fetch_array($result))
{
$entry = $row['Entry'];
$CID = $row['CID'];
$checked =$row['Checked'];
// echo $CID;
echo "<input type=\"text\" value=\"$entry\" name=\"textfield$CID;\" id=\"textfield$CID;\" onchange=\"showUser(this.value)\" />";
echo "<input type=\"checkbox\" value=\"\" name=\"checkbox$CID;\" id=\"checkbox$CID;\" value=\"$checked\"".(($checked == '1')? ' checked="checked"' : '')." />";
echo "<br>";
}
?>
<div id="dynamicInput"></div>
<input type="submit" id="checklistSubmit" name="checklistSubmit" class="checklist-submit"> <input type="button" id="CompleteAll" name="CompleteAll" value="Check All" onclick="javascript:checkAll('checklist', true);"><input type="button" id="UncheckAll" name="UncheckAll" value="Uncheck All" onclick="javascript:checkAll('checklist', false);">
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');"></form>
It is populated from the database based on the users session_id, however if the user wants to create a new list item (or is a new visitor period) he can click the button "Add another text input" and a new form element will generate.
All updates to the database need to be done through AJAX\JQUERY and not through a post which will refresh the page.
I really need help on this one. Getting my head around this kind of... Updating method kind of hurts!
Thanks.
You will need to catch the click of the button. And make sure you stop propagation.
$('checklistSubmit').click(function(e) {
$(e).stopPropagation();
$.post({
url: 'checklist.php'
data: $('#checklist').serialize(),
dataType: 'html'
success: function(data, status, jqXHR) {
$('div.successmessage').html(data);
//your success callback function
}
error: function() {
//your error callback function
}
});
});
That's just something I worked up off the top of my head. Should give you the basic idea. I'd be happy to elaborate more if need be.
Check out jQuery's documentation of $.post for all the nitty gritty details.
http://api.jquery.com/jQuery.post/
Edit:
I changed it to use jquery's serialize method. Forgot about it originally.
More Elaboration:
Basically when the submit button is clicked it will call the function specified. You want to do a stop propagation so that the form will not submit by bubbling up the DOM and doing a normal submit.
The $.post is a shorthand version of $.ajax({ type: 'post'});
So all you do is specify the url you want to post to, pass the form data and in php it will come in just like any other request. So then you process the POST data, save your changes in the database or whatever else and send back JSON data as I have it specified. You could also send back HTML or XML. jQuery's documentation shows the possible datatypes.
In your success function will get back data as the first parameter. So whatever you specified as the data type coming back you simply use it how you need to. So let's say you wanted to return some html as a success message. All you would need to do is take the data in the success function and place it where you wanted to in the DOM with .append() or something like that.
Clear as mud?
You need two scripts here: one that runs the AJAX (better to use a framework, jQuery is one of the easiest for me) and a PHP script that gets the Post data and does the database update.
I'm not going to give you a full source (because this is not the place for that), but a guide. In jQuery you can do something like this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { // DOM is ready
$("form#checklist").submit(function(evt) {
evt.preventDefault(); // Avoid the "submit" to work, we'll do this manually
var data = new Array();
var dynamicInputs = $("input,select", $(this)); // All inputs and selects in the scope of "$(this)" (the form)
dynamicInputs.each(function() {
// Here "$(this)" is every input and select
var object_name = $(this).attr('name');
var object_value = $(this).attr('value');
data[object_name] = object_value; // Add to an associative array
});
// Now data is fully populated, now we can send it to the PHP
// Documentation: http://api.jquery.com/jQuery.post/
$.post("http://localhost/script.php", data, function(response) {
alert('The PHP returned: ' + response);
});
});
});
</script>
Then take the values from $_POST in PHP (or any other webserver scripting engine) and do your thing to update the DB. Change the URL and the data array to your needs.
Remember that data can be like this: { input1 : value1, input2 : value2 } and the PHP will get something like $_POST['input1'] = value1 and $_POST['input2'] = value2.
This is how i post form data using jquery
$.ajax({
url: 'http://example.com',
type: 'GET',
data: $('#checklist').serialize(),
cache: false,
}).done(function (response) {
/* It worked */
}).fail(function () {
/* It didnt worked */
});
Hope this helps, let me know how you get on!

Json parse and add format

I use this in a function:
$.ajax({
type: 'POST',
url: 'demopost.php',
data: { ... },
dataType: 'json',
success: function(data)
{
console.log(data);
}
});
The demopost.php contains only a query.
The output will be:
But how can I show it inside a div? OR How can I add some formation e.g. with foreach like a php array?
EDIT:
I tried with it (the place of console.log(data):
$('.inner').append(data);
Of course there was a div with class inner. But nothing show
EDIT2:
The query in the demopost.php:
... try
{
$c_id = htmlspecialchars($_POST['cid']);
$leftprice = $_POST['left'];
$rightprice = $_POST['right'];
$items=$main->pdo->prepare("SELECT name, price FROM clf_items WHERE category_id IN (
SELECT node.id
FROM clf_category AS node,
clf_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt AND price BETWEEN :left AND :right
AND parent.id = :c_id)");
$items->execute(array(':c_id' => $c_id, ':left' => $leftprice, ':right' => $rightprice));
$items_array = array();
while ($row = $items->fetch(PDO::FETCH_ASSOC))
{
$items_array[] = $row;
}
echo json_encode($items_array);exit;
}...
What you are doing here is to return some JSON data from the server which can be read by javascript, but is not useful to be pushed into HTML without some processing.
One solution would be to get the JSON array you receive and transform it into a HTML string before pushing it onto the page. This might look like:
success: function(data)
{
var result = '<table>';
for (i=0; i<data.length; i++) {
result += '<tr><td>'+ data[i].name+'</td><td>'+data[i].price+'</td></tr>';
}
result+= '</table>';
$(".inner").html(result);
}
Now this has not money formatting, no html escaping, very crude layout etc pp. Before you try to make this raw sketch into something useful I recommend looking into the various template engines available for jQuery; a few are listed in this post: jQuery Templates are deprecated? (and unlike the question suggests, jQuery templates are not dead, but got some competition).
However I would prefer another approach: create the HTML server side (instead of JSON), so you return a HTML snippet the same way you would return a full HTML page normally in PHP, and in the ajax request say you want HTML: dataType: 'html', and then you can push the result straight into $(".inner").html(data) (or $(".inner").append(data), no idea how your HTML should look like), as you originally wanted.
I guess this is the same as schwierig wanted to say, but I feel one need to tell it more explicit.
For what reason are you using Ajax if you are not processing the data you are sending? If you just want to format the data, you don't really need PHP to do that.
Of course it would be possible. If you want to process with PHP you need to echo your formatted result and use the .done() function as described in the jQuery API
http://api.jquery.com/jQuery.ajax/
$.post('demopost.php',{..}, function(data) {
$('.inner').html(data);
});
try this one hope it will help and make sure you have div with inner class

Putting mySQL Database Information into a JavaScript Array

What I'm trying to do is create a slideshow by grabbing database information and putting it into a javascript array. I am currently using the jquery ajax function to call information from a separate php file. Here is my php code:
mysql_connect('x', 'x', 'x') or die('Not Connecting');
mysql_select_db('x') or die ('No Database Selected');
$i = 0;
$sql = mysql_query("SELECT comicname FROM comics ORDER BY upldate ASC");
while($row = mysql_fetch_array($sql, MYSQL_ASSOC)) {
echo "comics[" .$i. "]='comics/" .$row['comicname']. "';";
$i++;
}
What I want is to create the array in php from the mysql query and then be able to reference it with javascript in order to build a simple slideshow script. Please let me know if you have any questions or suggestions.
Ok have your .php echo json_encode('name of your php array');
Then on the javascript side your ajax should look something like this:
$.ajax({
data: "query string to send to your php file if you need it",
url: "youphpfile.php",
datatype: "json",
success: function(data, textStatus, xhr) {
data = JSON.parse(xhr.responseText);
for (i=0; i<data.length; i++) {
alert(data[i]); //this should tell you if your pulling the right information in
}
});
maybe replace data.length by 3 or something if you have alot of data...if your getting the right data use a yourJSArray.push(data[i]); I'm sure there's a more direct way actually...
You may want to fetch all rows into a large array and then encode it as a JSON:
$ret = array();
while($row = mysql_fetch_array($sql, MYSQL_ASSOC))
$ret[] = $row
echo json_encode($ret);
Then, on the client side, call something like this:
function mycallback(data)
{
console.log(data[0].comicname); // outputs the first returned comicname
}
$.ajax
(
{
url: 'myscript.php',
dataType: 'json',
success: mycallback
}
);
Upon successful request completion, mycallback will be called and passed an array of maps, each map representing a record from your resultset.
It's a little hard to tell from your question, but it sounds like:
You are making an AJAX call to your server in JS
Your server (using PHP) responds with the results
When the results come back jQuery invokes the callback you passed to it ...
And you're lost at this point? ie. the point of putting those AJAX results in to an array so that your slideshow can use them?
If so, the solution is very simple: inside your AJAX callback, put the results in to a global variable (eg. window.myResults = resultsFromAjax;) and then reference that variable when you want to start the slideshow.
However, since timing will probably be an issue, what might make more sense is to actually start your slideshow from within your callback instead. As an added bonus, that approach doesn't require a global variable.
If this isn't where you are stuck, please post more info.

Submit Value With Javascript

I'm a stuck with the following function:
<script type="text/javascript">
function removeElement($parentDiv, $childDiv){
if (document.getElementById($childDiv)) {
var child = document.getElementById($childDiv);
var parent = document.getElementById($parentDiv);
parent.removeChild($child);
}
}
</script>
x
This function deletes a child element, and its content, which works great client-side! But I am wanting to pass a value to the server, in the same instance, so the content of the element can be deleted from the mysql database too. I have no idea how to do this, so any suggestions will be very appreciated!
Notes: $child, and $parent are strings generated within the php file, that I use to give each element a unique ID.
To make your life easier, use jQuery or similar framework. Here's how you would do it in jQuery:
$(function() {
$('.delete').click(function() {
var link = $(this);
var id = link.attr('id').replace('element_', '');
$.ajax({
url: 'handler.php',
data: {
element: id
},
type: 'post',
success: function() {
link.remove();
// Or link.closest('tr').remove() if you want to remove a table row where this link is
}
});
return false;
});
});
The HTML:
Remove
And handler.php:
mysql_query("DELETE FROM `table` WHERE id = '".mysql_real_escape_string($_POST['element'])."'");
Always remember to escape database input!
If you're a total noob as you said, you probably won't understand all of this so I suggest you read something about jQuery's AJAX capabilities and about overall development using jQuery or similar JavaScript framework.
Lets say I want to delete an entity using a ID
JQUERY - $.post()
This is an easy way to send a simple POST request to a server without having to use the more complex $.ajax function. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code). Jquery post docs
On the server assuming you have an open database connection.
mysql_query("DELETE FROM TABLE WHERE ID = ".$_POST['ID']);
more on mysql_query found here
EDIT:
So the following will only remove the element when the ajax post is complete. Note the first arg is the url to the script that will take the action , second is the data to be sent, in this case the ID post value will be {child.id} and the third is a anon inline callback function that will take action to remove the element client side.
<script type="text/javascript">
function removeElement($parentDiv, $childDiv){
if (document.getElementById($childDiv)) {
var child = document.getElementById($childDiv);
var parent = document.getElementById($parentDiv);
$.post('{URLTOSCRIPT}', 'ID=$child.id',function () { parent.removeChild($child); });
}}
</script>
When you call the function, you'd want to put your PHP variables in tags like so:
<?php echo $parent; ?>
and
<?php echo $child; ?>
In the function definition, you will want to get rid of the PHP style variables and use something like:
function removeElement(parentDiv, childDiv) {
//CODE
}

Categories