Ajax Posting of data to PHP - php

I have the following code:
<?php
$query=mysqli_query($mysqli, "SELECT assignment,a_id FROM assignments WHERE groupid='".$groupid."'");
$assignments = array(); // create empty assignments array
while ($row=mysqli_fetch_array($query)){
echo'<td class="columnname" id="'.$row['a_id'].'" contenteditable="true">'.$row['assignment'].'</td>';
$assignments[$row['a_id']] = $row['assignment']; // add assignment to array
}
?>
<script>
$('.columnname').keyup(function() {
delay(function(){
var text= $(this).text();
var id= $(this).attr('id')
$.ajax({
type:"POST",
url:"updateassignment.php",
data:{text:text, id:id},
success:function(data){
console.log('success bro!');
}
});
}, 500 );
});
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
</script>
Basically what happens, is that i have a contenteditable and whenever that is keyup (which means whenever user types in info), it will post the data to the php file updateassignment.php which updates the values. However, it doesnt seem to work for me, it gives me the success result, but shows no error. Its sort of not getting the values from the fields, but as you can see, im using $(this) which refers to the columnname class (which is generated dynamically by php)
The php updateassignment file code is below:
<?php
include_once("config.php");
if (isset($_POST['id']) && isset($_POST['text'])) {
$id=$_POST['id'];
$text=$_POST['text'];
$query=mysqli_query($mysqli, "UPDATE assignments SET assignment='$text' WHERE a_id='$id'")or die(mysqli_error($mysqli));
}
?>
I have a feeling that the this is not refering the correct element, therefore contenteditable's ajax is unable to grab the correct value.

I found the answer.
It was because i defined the ajax this inside the delay function, so it would not reference the columnname. The way to solve this is to define $(this) outside of the delay function.

Related

Using if statement in ajax using values from the database

I have column name status in Database it contains values(0,1) ,in front end i have image if i click the image it will redirect to the next page i am using ajax here, what i want before redirect it should perform if condition i want to check the database column status if the column contain any row '1' it should redirect if all rows in column '0' its not checking the if condition it will redirecting can anyone guide me how to perform this .below is my code(i.e now in row status all values are 0 it will not redirect it want to show alert but its redirecting)
html
<img id='redirect' src="/image/exporttt.png" style="margin:-30 0 0 0px;cursor:pointer;" >
$sql_selectsupplier = "********";
$result1 = mysql_query($sql_selectsupplier);
while($rows=mysql_fetch_array($result1))
{
$reditect=$rows['status'];
}
Ajax
<script>
$(document).ready(function() {
$("#redirect").click(function() {
if($reditect=1){
var clientid=document.getElementById("client").value;
$.blockUI(
{
message: '<h2>Please wait...</h2><img src="/image/loader.gif" />',
timeout: 2000
});
$.ajax({
type:"post",
data:"clientid="+clientid,
success:function(data){
window.location = '?action=clientroutingchange&clientid='+clientid+'';
$("#result").html(data);
$('.blockUI').hide();
}
});
}
else{
alert("no changes made")
}
});
});
</script>
From your code it's not clear which one is PHP code, and which one is out of the PHP block.
Inside your block you have
if($reditect=1){ which does not seem like a javascript code.
Is that php?
If yes, then you are using it wrong way. = is an assignation operator, so you do assign the value 1 explicitly this way.
I would suggest, if you are using PHP conditions, also to move thme outside the script block:
<?php if ($reditect == 1): ?> # `==` for comparison
<script>
var clientid=document.getElementById("client").value;
// .. all the code
</script>
<?php else: ?>
<script>
alert('.....');
</script>
<?php endif; ?>
If it was an Javascript condition, then you need to assign the value of the php variable to the js var
<script>
var reditect = "<?= $reditect; ?>";
if (reditect == '1') {
// something
</script>
Use == for comparision
if($reditect==1)
and your $redirect is a php variable which doesn't make sense in script
So, use
var reditect = <?php echo $reditect ?>
and check by,
if(reditect==1)

use php inside script [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I am writing a program which I need to add php code inside script
The html has a table, with 2 chosen selectbox, I want to update 2nd selectbox when first when has been changed by user
$('.chzn-select').chosen().change(function() {
var a = $(this).attr('data-id');
var ord = $(this).val();
if (a == 'ord') //Check if first select box is changed
{
var itemcode = $(this).parent().parent().find('[data-id="item"]'); //find second select from same row
//add items from order
<?php
$ord = '<script>document.write(ord);</script>'; //javascript variable to php variable
//This code is not working, if I update the php variable from javascript variable
mysql_query('select * from ords where ord_id = '.$ord.');
?>
$(itemcode).append('<option>a</option>');
$(".chzn-select").trigger("liszt:updated");
}
});
Any ideas?
You could try sending the variables by using the jQuery load function.
page1.html:
<script type="text/javascript">
$('.chzn-select').chosen().change(function() {
var a = $(this).attr('data-id');
var ord = $(this).val();
if (a == 'ord') {
var itemcode = $(this).parent().parent().find('[data-id="item"]');
$('#ord').load('page2.php?ord='+ord);
$(itemcode).append('<option>'+$('#ord').html()+'</option>');
$(".chzn-select").trigger("liszt:updated");
}
});
</script>
<div id="ord"></div>
page2.php:
<?php
$ord = $_GET['ord'];
mysql_query('select * from ords where ord_id = '.$ord);
?>
Here's an example of how it could be done with AJAX. You probably need to adapt it to your needs. The idea was just to show you the basics of an AJAX request:
<script>
$('.chzn-select').chosen().change(function() {
var a = $(this).attr('data-id');
var ord = $(this).val();
if (a == 'ord') //Check if first select box is changed {
var itemcode = $(this).parent().parent().find('[data-id="item"]'); //find second select from same row
//add items from order
$.ajax({
url: "order.php",
type: 'POST',
data: {
ord: ord
},
cache: false,
success: function(data){
$(itemcode).append(data);
$(".chzn-select").trigger("liszt:updated");
}
});
}
});
</script>
Create a PHP file to handle the request and echo the HTML to be appended. This is just a rough example:
<?php
$ord = $_POST['ord'];
if (is_numeric($ord)){
$result = mysql_query('select * from ords where ord_id = '.$ord);
if ($result){
//process query result here
//create HTML string that will be appended
$str = '<option>'.$option.'</option>';
echo $str;
}
}
?>
PHP runs on server-side and prepares the page before the client-side javascript code is invoked. so, assuming this is a PHP file that contains javascript, be advised that best thing the PHP might do is prepare which javscript code will be in the page. if you want to pass javascript variable to PHP, you must SEND them from the client-side to the server-side (probably with $.POST command)
It does not work because $ord in literally the value of:
<script>document.write(ord);</script>
Which is no where near a id.
Try using the jquery post:
$.post("phpdoc.php", { name: ""+ord+""})//this sends the ord value to the php page
.done(function(data) {
alert("Data Loaded: " + data);//this will alert returned data
});

Best way to refresh multiple PHP values every x seconds?

I have an index.php file that I would like to run getdata.php every 5 seconds.
getdata.php returns multiple variables that need to be displayed in various places in index.php.
I've been trying to use the jQuery .load() function with no luck.
It's refreshing the 12 <div> elements in various places on the index.php, but it's not re-running the getdata.php file that should get the newest data.
But If I hit the browser refresh button, the data is refreshed.
getdata.php returns about 15 variables.
Here is some sample code:
<script>
var refreshId = setInterval(function()
{
$('#Hidden_Data').load('GetData.php'); // Shouldn´t this return $variables
$('#Show_Data_001').fadeOut("slow").fadeIn("slow");
$('#Show_Data_002').fadeOut("slow").fadeIn("slow");
$('#Show_Data_003').fadeOut("slow").fadeIn("slow");
$('#...').fadeOut("slow").fadeIn("slow");
}, 5000); // Data refreshed every 5 seconds
*/
</script>
Here's an example of GetData.php:
$query = "SELECT column1, COUNT(column2) AS variable FROM table GROUP BY column";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$column1 = $row['column1 '];
$variable = $row['variable '];
if($column1 == "Text1") { $variable1 = $variable; }
elseif($column1 == "Text2") { $variable2 = $variable; }
... continues to variable 15 ...
}
Then further down the page the HTML elements display the data:
<div id="Hidden_Data"></div>
<div id="Show_Data_001"><?php echo $variable1; ?></div>
<div id="Show_Data_002"><?php echo $variable2; ?></div>
<div id="Show_Data_003"><?php echo $variable3; ?></div>
...
I tried using the data parameter as suggested here:
https://stackoverflow.com/a/8480059/498596
But I couldn't fully understand how to load all the variables every 5 seconds and call them on the index page.
Today the GetData.php page just returns $variable1 = X; $variable2 = Y and so on.
UPDATE
For some reason the jQuery is not loading the GatData.php file and refreshing the variables.
I tried adding to "Hidden_Data" to the include('GetData.php') and then the variables are readable on the page.
If I remove this part, the page displays "variable not set" warning that suggesting that the jQuery is not loading the GetData.php script into the Hidden_Data <div>.
Try
<script>
var refreshId = setInterval(function()
{
$('#Hidden_Data').load('GetData.php', function() { // Shouldn´t this return $variables
$('#Show_Data_001').fadeOut("slow").fadeIn("slow");
$('#Show_Data_002').fadeOut("slow").fadeIn("slow");
$('#Show_Data_003').fadeOut("slow").fadeIn("slow");
$('#...').fadeOut("slow").fadeIn("slow"); });
}, 5000); // Data refreshed every 5 seconds
*/
</script>
Above is assuming, that your code returns snippet of HTML elements (Show_Data_XXX), but now that you've clarified your question above wont help you alone...
What you need to do is either in your php send back new value elements or send back your results as data and update existing elements.
Put your elements into a php Array and then send it back
data.php after sql call
$results = Array();
while($row = mysql_fetch_array($result)){
$column1 = $row['column1 ']; // change Text1 in db to Show_Data_001 in html or vice versa
$variable = $row['variable '];
$results[$column1] = $variable;
}
echo json_encode($results);
in your javascript something like this...
$.getJSON('GetData.php',function(data) {
$.each(data, function(key, val) {
$('#'+key).text(val);
});
});
I didn't put the fadeOut and fadeIn into the example, because it complicates it a bit. You could do fadeOut to all those elements before calling getJSON and the fadeIn as the results pouring in. Hope this helps
First of all, make sure you have correct respond from server, just like this:
//We won't use load() to load content for now
window.setInterval(function(){
$.ajax({
url : "path_to_your_php_script.php",
type : "GET",
beforeSend: function(){
//here you can display, smth like "Please wait" in some div
},
error : function(msg){
//You would know if an error occurs
alert(msg);
},
success : function(respondFromPHP){
//Are you getting distinct results every 5 sec?
alert(respondFromPHP);
return;
//if respondFromPHP contains data you want
//ONLY THEN, add some effects
}
});
}, 5000);
The only difference between this approach and yours, is that, you can handle errors and make sure you are getting data you want.
Can you show me the code of GetData.php?
Rather than using Jquery.load you can actually get the page with $.post or $.get and format your results from GetData.php to Json or xml you can easily map it to your javascript.
Using $.post it will allow you to have a callback after getting the value from GetData.php and you can check it if it's working right or not. If it gets a data from your GetData.php then you can populate it to your DIV elements.
You can check more information regarding POST and GET here:
http://api.jquery.com/jQuery.post/

jQuery Sortable Grid into MySQL Database PHP

I'm trying to sort images using: http://jqueryui.com/demos/sortable/display-grid.html
And then somehow submit the newly sorted array/results into a MySQL Database using PHP?
I'm having difficulty figuring this out (newby alert), so if anyone can shed some light on this, I'll be dishing out hi-5s like there's no tomorrow.
Cheers
In particular you need to look at attaching an event to the sortable
http://jqueryui.com/demos/sortable/#event-update
and serialize for getting the relevant content http://jqueryui.com/demos/sortable/#method-serialize
EDIT
This is a primitive version of what you need to do.
<script>
$(function() {
var arrayOfIds = [];
$( "#sortable" ).sortable({
update: function(event, ui) {
$.each($(this).sortable('toArray'), function(key, value) {
arrayOfIds.push(value.replace('el-',''))
});
var jqxhr = $.ajax({
url: "order.php?order="+encodeURIComponent(arrayOfIds),
})
.success(function(response) { console.log("success" + response ); })
.error(function() { console.log("error"); })
.complete(function() { console.log("complete "); });
}
});
$( "#sortable" ).disableSelection();
});
</script>
Each li element than needs an id that your DB can understand
<li class="ui-state-default" id="el-1">1</li>
the "1" in id="el-1" should relate to an id in your DB table. When you reorder, the update event fires, goes through the new order, grabs all the ids and passes that to an ajax request which a php file then can pick up. the order.php script then go split the numbers by the "," and update your table one by one.
e.g.
$itemOrders = explode(',',$_POST['order']);
$sizeOfList = sizeof($itemOrders);for($i=0; $i<$sizeOfList; $i++)
{
$itemId = intval($itemOrders[$i]);
$query = "UPDATE your_table_name SET order_no = '".$i."' WHERE id = '".$itemId."' ";
if ($result = $msHandle->query($query))
{
$message = 'success';
}
else
{
$message = 'fail ';
}
}
There will be a callback function on the sorting event which you can use to send an AJAX request to a PHP script which updates a database. Think of it as after you've made a sorting action (i.e. moving one item around), you send the values (i.e. the ordered list) to a PHP script that takes those values and updates the database. I'll assume you have experience in MySQL as you seem to know the fundamentals of the problem.

Print the value in loop in Jquery ready function

somehow still not able to do what I’m inted to do. It gives me the last value in loop on click not sure why. Here I want the value which is been clicked.
Here is my code:
$(document).ready(function() {
var link = $('a[id]').size();
//alert(link);
var i=1;
while (i<=link)
{
$('#payment_'+i).click(function(){
//alert($("#pro_path_"+i).val());
$.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_"+i).val()}, function(data){
//alert(data);
$("#container").html(data);
});
});
i++;
}
});
Here the placement_1, placement_2 .... are the hrefs and the pro_path is the value I want to post, the value is defined in the hidden input type with id as pro_path_1, pro_path_2, etc. and here the hrefs varies for different users so in the code I have $('a[id]').size(). Somehow when execute and alert I get last value in the loop and I don’t want that, it should be that value which is clicked.
I think onready event it should have parsed the document and the values inside the loop
I’m not sure where I went wrong. Please help me to get my intended result.
Thanks, all
I would suggest using the startsWith attribute filter and getting rid of the while loop:
$(document).ready(function() {
$('a[id^=payment_]').each(function() {
//extract the number from the current id
var num = $(this).attr('id').split('_')[1];
$(this).click(function(){
$.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_" + num).val()},function(data){
$("#container").html(data);
});
});
});
});
You have to use a local copy of i:
$('#payment_'+i).click(function(){
var i = i; // copies global i to local i
$.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_"+i).val()}, function(data){
$("#container").html(data);
});
});
Otherwise the callback function will use the global i.
Here is a note on multiple/concurrent Asynchronous Requests:
Since you are sending multiple requests via AJAX you should keep in mind that only 2 concurrent requests are supported by browsers.
So it is only natural that you get only the response from the last request.
What if you added a class to each of the links and do something like this
$(function() {
$('.paymentbutton').click(function(e) {
$.post("<?php echo $base; ?>form/setpropath/",
{pro_path: $(this).val()},
function(data) {
$("#container").html(data);
});
});
});
});
Note the use of $(this) to get the link that was clicked.

Categories