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.
Related
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);
}
}
});
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!
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.
Hey everyone. This one is puzzling me. I'm using PHP and Jquery. I am making an ajax request to a PHP file containing a get url. Eg. Path/to/file/?ID=369
The request goes out fine, I've watched it in fire bug.
However in the PHP file, the ID variable doesn't exist. When I do
var_dump($_GET)
I can see that there are two arrays inside the GET array. These are JSON and action.
Can anyone explain to me what's going on here and how I can receive my ID variable?
here are my codes:
<?php
$program_price_id = $_GET['id'];
$programDepatures = getProgramDepaturesGreaterThanToday($program_price_id);
echo "[{optionValue: 0, optionDisplay: 'Select a date'}";
while ($programDepartureData = mysql_fetch_array($programDepatures)) {
echo ", {optionValue: ".
$programDepartureData['id'].", optionDisplay: '".
tidyDateEnglish($programDepartureData['departure_date'])."'}";
}
echo "]";
?>
Best wishes,
Mike
i think you need to specify the ajax method you are using.It might be a $.ajax, $.get or $.getJson.
but i use $.ajax and here is a snippet
$.ajax({
url:"event/service_ajax_handler.php",
type: "GET",
data: {action:"getTime"},
dataType : "json",
success: function(data) {
$("#cmbTimeRange").html("<option value='-1'>Please select time range</option>");
$.each(data, function(){
$("#cmbTimeRange").append("<option value='"+ this.id +"'>" + this.hours +"</option>")
});
},
error: function(){
alert("error");
}
});
pay attention to the data parameter. see also
getJSON
This may be obvious, but I noticed in the sample URL you have ID capitalized, but in your PHP code you have it lowercase. PHP is case sensitive, so it could be as simple as that.
I can't get the following PHP + jQuery to work - all I want the script to do is pass the value through ajax, and get the php to grab it, check it matches and add 1 to score.
This is the code I've written:
<?php
$score = "1";
$userAnswer = $_POST['name'];
if ($_POST['name'] == "145"){
$score++;
}else{
//Do nothing
}
echo $score;
?>
<script type="text/javascript">
$(document).ready(function() {
$("#raaagh").click(function(){
var value = "145";
alert(value);
$.ajax({
url: 'processing.php', //This is the current doc
type: "POST",
data: ({name: value}),
success: function(){
location.reload();
}
});
});
});
</script>
<p id="raaagh">Ajax Away</p>
Thanks for the help, I've changed GET to POST in both instances, and no joy - there's something else wrong.
First of all: Do not go back to the dark ages... don't use the same script to generate HTML and to respond to an ajax request.
I can't make any sense of what you are trying to do... Let me change your code so it at least makes some sense and document what's going on. It seems like the problem is the fact that you are calling location.reload from your success handler.
// ajax.php - Outputs 2 if the name parameter is 145, 1 otherwise (????)
<?php
$score = "1";
$userAnswer = $_POST['name'];
if ($_POST['name'] == "145"){
$score++;
}
echo $score;
?>
// test.html
<script type="text/javascript">
$(document).ready(function() {
$("#raaagh").click(function(){
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data){
// Why were you reloading the page? This is probably your bug
// location.reload();
// Replace the content of the clicked paragraph
// with the result from the ajax call
$("#raaagh").html(data);
}
});
});
});
</script>
<p id="raaagh">Ajax Away</p>
You use POST in your jQuery, but you try and get a GET in you php.
BTW it is good practice to check if a GET/POST variable is set before reading it.
using the isset() function.
Replace $_GET with $_POST and there you are.
Basically POST and GET are two different way to pass variables to a script. The get method in php can also be attached at the end of a url : script.php?variable=value and it is really easy to hack. While the post method can be submitted with forms or ajax calls and it is pretty safe, at least more than the get.
Also i'd suggest you to check whatever a GET or POST variable is set before calling it, so that you can prevent stupid notice errors.
Just use the following code:
if (isset($_POST['var']) and !empty($_POST['var'])) { // do something }
You can also delete the
}else{
// do nothing
}
part of the script, since the else clause it is not necessary always.
You're submitting the data with an Ajax POST, but trying to read it out of a GET. Either use type: "GET" in your Ajax call or $_POST['name'] in your PHP.
The problem is you are using jQuery to POST your value, yet you are reading it with GET.
You should be able to fix your problem by changing your $_GET['name'] to $_POST['name']