Ajax not sending PHP POST data - php

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/

Related

Retrieve data from PHP file by ajax

I found a script on the net, which makes two PHP files interact.
Specifically, the first file (details.php) shows some statistical data of a football match. If the match is in progress, I show the live score by running another PHP file (live_score.php). The two files interact thanks to the following script, present in the details.php file
$(document).ready(function(){
setInterval(function() {
var id=<?php echo"$id"?>;
var x = "<?php echo"$cod"?>";
$("#risultato").load("live_score.php", {var:id, x});
refresh();
}, 5000);
});
from details.php, I call live_score.php passing it some parameters.
These parameters are used by the live_score.php file to retrieve the score and other information in real time.
To print the result on the screen in details.php, I use a simple ECHO inside the live_score.php file, but I would like to retrieve this data and the others in a different way, via ajax if possible, but I don't know if it can be done and how....can you help me please? Thank you
I think you have already solved half of your problem. From your code , you should first remove the "refresh()" to stop reloading the page every 5 seconds.
then make sure that the the payload is correct, because the word "var" is a reserved keyword in JavaScript.
HTML
<div id="risultato"></div>
Javascript
$.ajax({
url: "live_score.php",
type: "POST",
data: { id, x},
success: function(response) {
//this response will be the data from "live_score.php"
//now assuming that
// 1. you use vanilla javascript with plain html + css
// 2. the returning reponse looks like this
// [{"teamName": "theTeam1", "score": 10}, {"teamName": "theTeam2", "score": 10}]
//Clear the current score
$("#risultato").empty();
// Now iterate through the response,
$.each(response, function(index, item) {
var teamName = item.teamName;
var score = item.score;
var html = "<p><strong>" + teamName + "</strong>: " + score + "</p>";
// this code will append (add to the end) the data iterated
$("#risultato").append(html);
});
},
error: function(xhr, status, error) {
//if your code or ajax call had any problems ,
//you can debug here and write error handling logic here, like
if(error){
alert("failed to fetch data");
console.log(error);
}
}
});

jQuery.ajax seems to be bypassed completely - no console log

I have some jQuery/HTML where I accept a single item of user input (text) and want to pass it to PHP, to be stored for later use in a session variable. I've looked at many pages on this type of action, and found the closest accepted answer to what I think I need is the one here Set Session variable using javascript . The following code is broadly based on that, but it seems that the ajax is doing nothing. I've got console.logs all the way through, and at each possible path through the ajax statement (done, fail and always) but none show up. The console log shows:
(document).ready
Take new list name from input
ListA1
passName: ListA1
:
Object {listNamePOST: "ListA1"}
passName function end
returned from passName()
about to echo $_SESSION['listName'] :
end
Which misses out 6. success or 6. fail and 7. always. And the line console.log(< ?php echo $_SESSION['listName'] ?>); doesn't even show a blank line.
Where am I going wrong, please?
Here is test.php
<?php session_start(); ?>
<form method="post" name="newlistform">
<label for="list_name">Input:</label>
<input style="position: relative; " name="list_name" type="text" required />
<span class="button" id="makeIt">Go</span>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
/* ƒ: Pass listName out to SESSION variable */
function passName ( listName ) {
console.log('4. passName: ', listName);
var params = {listNamePOST: listName};
console.log("5. :");
console.log(params);
jQuery.ajax({
url: "storesession.php",
type: "POST",
data: params,
dataType : "json",
success: function(data, textStatus, xhr) {
console.log("6. success");
console.log(data);
},
error: function(xhr, textStatus, errorThrown) {
console.log("6. fail");
}
});
console.log('8. passName function end');
}
$(document).ready(function () {
console.log('1. (document).ready');
$( '#makeIt.button' ).click(function () {
console.log('2. Take new list name from input');
var listName = $( 'input[name=list_name]' ).val();
console.log('3.', listName);
passName ( listName );
console.log('9. returned from passName()');
console.log("10. about to echo $_SESSION['listName'] :");
console.log(<?php echo $_SESSION['listName'] ?>);
console.log('12. end');
});
})
</script>
and here is storesession.php
<?php
$_SESSION['listName'] = $_POST['listNamePOST'];
?>
(I'll sanitize the user input later.)
Edit: Just removed 'test.php' at the end of each of the console log lines. I copied them in inadvertently.
2nd edit: For information - This code is an extract of a larger php file which includes another $.ajax call, to get some data from a MySQL db, and that is working.
3rd edit: Changed 'done:' back to 'success:', 'fail:' back to 'error:' and removed 'always:'. This now adds 6. success as the last line, so #FrancescoMM and #Kevin put me right, though I don't understand why it didn't work when I had that originally.
As '6. success' appears at the end of the log, I'm going to try async: false and report back:-
OK, that fixed the sequence problem, but the console log statement between log statements 10. and 12. still does not appear. No 'undefined' or even a blank line.
So the problem is now reduced to getting listName into a session variable.
4th edit: Now solved. When I moved the session_start statement from test.php to storesession.php and found it didn't work, I moved it back, but not as the very first statement. I since found http://www.yourhowto.net/how-to-check-and-create-php-session-variables/ so moved the statement to the very beginning, and now the user data is being passed across to the session variable and shows up correctly at the end of the log between 10. and 12.
If it's really your complete storesession.php, you are missing session_start() in it.
Are you returning data in json format from the AJAX call? I had a similar problem and it was because of the data type, lose the dataType : "json" unless you are actually returning json, and see if that helps.

Jquery:create a dictionary to autocomplete all inputs

i want to add an smart autocomplete to my project in which when ever user is typing a word in any input its autocompleted from his own dictionary.
his owner dictionary is built by saving every word he ever submit to server something like (array_values($_POST))
my current JS
$('input.complete').live('keyup.autocomplete', function(){
var hi=$(this).val().toUpperCase();
var was=this;
$(this).autocomplete({
//PROBLEM Should i consider to change source from ajax/mysql to different source ?
//since there gona be too many requests ??
source: function(request, response) {
$.ajax({ url: '<?=base_url()?>ajax/ac',
//PROBLEM how can i set term=word currently being edited..(start=' ',end=pointerpos)
data: { 'term': this.term },
dataType: "json",
type: "POST",
success: function(data){
if(data.length){
//response(data);
//Commented out cause i dont wana display dropdown.. just typeahead.
if(data[0]['value'].substr(0,hi.length).toUpperCase()==hi){
$(was).val(data[0]['value']);
//currently working with single word inputs..once i get how to select only current word will edit these..
was.selectionStart=hi.length;
was.selectionEnd=data[0]['value'].length;
}
}
}
});
},
select: function(event, ui){},
minLength: 2,
delay: 500
});
As u can see i have 2 problems
Question
how can i select current word that user is typing ?
is this a good approach to reach my goal, or i should consider different plugin
You are using PHP language as well. So in my opinion you can use PHP to solve your problem more easily. Let's say you have php function get_word($excerpt) in get.php file. So,
<?php
get_word($_POST['excerpt']);
function get_word($excerpt) {
// Find exact word from database or array using given $excerpt
// and return complete word.
return $complete_word;
}
?>
And in your jquery (assuming input field as .input),
$(document).ready(function() {
$('.input').live('keyup',function() {
var excerpt = $(this).val();
$.post("get.php", {excerpt:excerpt}, function(data) {
// do anything with data.
$('.input').val(data);
});
});
})
For more precise, you can get bunch of matching words from get.php file, and display list of words to be selected.

jQuery Droppable - Make an Update Statement after an element gets dropped

I want to do an update statement in my database, after an element gets dropped on a jQuery UI droppable element.
$("#pictures th div").droppable({drop: function(ev, ui) {
alert('You filled this box with a picture');
var this_id = $(ui.draggable).attr("alt");
var draggableId = ui.draggable.attr("id");
}
I know how to get the information (see the code above) I need, but how can I put them now into the database ?
Thank you !
At this point, you can use jQuery's $.post() method to post to a PHP file you've written. In the $.post(), you can pass the ids you would like to have written to your database.
So something like this:
$.post("/save.php", { imageId: this_id, draggedId: draggableId }, function (data) {
alert("success!");
});
Post the variable values to other page lyk this:
$.ajax({
type: "POST",
url: "data.php",
data: "Cat=" + id + "&Wid=" + WID
});
and then on data.php page get the values lyk this:
$Cat=$_POST['Cat'];
$WID=$_POST['Wid'];
simply store them in database by using insert query,hope it will help you.

Sending a value from a dropdown box to PHP via jQuery

I'm trying to take values from a dropdown two boxes and send them to a PHP file which will draw an appropriate field from a mySQL database depending on the combination chosen and display it in a div without refreshing the page using AJAX. I have the second part sorted, but I'm stuck on the first part.
Here is the HTML: http://jsfiddle.net/SYrpC/
Here is my Javascript code in the head of the main document:
var mode = $('#mode');
function get() {$.post ('data.php', {name: form.him.value, the_key: #mode.val()},
function(output) {$('#dare').html(output).show();
});
}
My PHP (for testing purposes) is:
$the_key = $_POST['the_key'];
echo $the_key;
After I have it in PHP as a variable I can manipulate it, but I'm having trouble getting it there. Where am I going wrong? Thanks for your replies!
You need a callback function as well to have the server response to the POST.
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
This snippet will post to ajax/test.html and the anonymous function will be called upon its reply with the parameter data having the response. It then in this anonymous function sets the class with result to have the value of the server response.
Help ? Let me know and we can work through this if you need more information.
Additionally, $.post in jQuery is a short form of
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
dataType: dataType
});
your jquery selectors are wrong:
html:
<select id="mode">
jquery selector:
$("#mode").val();
html:
<select name="player">
jquery selector:
$("select[name=player]").val();
You want to add a callback to your ajax request, its not too hard to do, here ill even give you an example:
$.ajax({
url: "http://stackoverflow.com/users/flair/353790.json", //Location of file
dataType: "josn",//Type of data file holds, text,html,xml,json,jsonp
success : function(json_data) //What to do when the request is complete
{
//use json_data how you wish to.;
},
error : function(_XMLHttpRequest,textStatus, errorThrown)
{
//You fail
},
beforeSend : function(_XMLHttpRequest)
{
//Real custom options here.
}
});​
Most of the above callbacks are optional, and in your case i would do the following:
$.ajax({
url: "data.php",
dataType: "text",
data : {name: ('#myform .myinput').val(),the_key: $('#mode').val()},
success : function(value)
{
alert('data.php sent back: ' + value);
}
});​
the ones you should always set are url,success and data if needed, please read The Documentation for more information.

Categories