Adding PHP Variables to JQuery's Ajax data - php

So as you can probably tell, I'm a bit amateur when it comes to jQuery. So if there's any better methods to do what I'm trying to do, please share kindly :) Here's what's happening. Everything works smoothly in the script when you substitute <?php echo $header_id; ?> for a given id that is compatible, say 17. Although $header_id is defined before this script, it must not be really outputting '17'.
I did research before this, not finding anything to help.
So I guess the main question is, does adding a PHP echo really work in this instance, or do I need another method, or is that not even the problem...
$(".vote-button-disabled").click(function (evt) {
$(this).hide().prev("input[disabled]").prop("disabled", false).focus();
var quizid = "";
console.log(quizid);
$.ajax({
url: "scripts/vote-post.php",
type: "POST",
data: {
'quizid' : '<?php echo $header_id; ?>',
'upvote' : '1',
},
success: function() {
console.log('yes!');
},
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
},
complete: function( xhr, status ) {
alert( "The request is complete!" );
}
});
});
Thanks in advanced!

Something to understand is that PHP is executed on the server side, and JavaScript is executed on client side.
PHP does not actually have any awareness of what is HTML, what is JavaScript, or what is plain text. It just knows that it's serving back some kind of content (maybe). So when you echo HTML or JavaScript code, you're really just creating a text file as far as PHP is concerned. You're creating a file that contains some text (that happens to be HTML + JS code) and sending that as the response to the HTTP request. Your browser interprets the resulting text in the response (which happens to be HTML + JS code). So one way you can think of PHP is as a HTML + JS generator. You can use PHP to output HTML + JS (and of course much more).
Once you understand that PHP is completely done executing by the time the page is sent back for the browser to interpret the HTML and JavaScript, the answer to what you can and can't do with JavaScript becomes much simpler. PHP is not interacting with JS, it's creating the JS code as text for your browser to read after PHP execution has completed.
So, as #charlietfl mentioned in the comments on the question, you should add the quizid to a data-quizid attribute on the button (assuming you're using HTML5), and then get the attribute for the specific element that was clicked, using var quizid = $(this).data('quizid');

If it's an external from PHP .js file, it won't work.
You could, however, insert JS directly in the PHP/HTML view document.
<?php
// Some PHP processing here, whatever you want
?>
<html>
<head>
<script type="text/javascript">
// Your Javascript here, for example:
var some_data = '<?php echo $some_variable; ?>';
// ...
</script>
</head>
<!-- Whatever you want to add -->
</html>

Related

Include PHP file inside a DIV using Jquery & AJAX [duplicate]

This question already has answers here:
using php include in jquery
(2 answers)
Closed 9 years ago.
My problem is that I need to include a PHP file inside a DIV when a button is pressed without the page reloading.
There is even more explanation in the 'Jsfiddle' file.
Below is an included Jsfiddle document.
http://jsfiddle.net/jjygp/5/
Thanks for your time. I am more than happy to provide any information upon request.
See here for your updated jsfiddle
You had marked the change button with a name of Change but were trying to select it with an id of change. Also, you had not told jsfiddle to include jQuery.
Try the following:
<button name="Change" id="Change">Change Div</button>
You are specifying a click function on an id, but no id is set on the button.
You can try with load() function in jquery
http://api.jquery.com/load/
PHP is a server-side script language, which will be executed before a JavaScript script did.
Therefore, you cannot use .load() to execute a PHP code, however, you may try .ajax() to create an AJAX request to the server which can implement the PHP code.
Please see http://api.jquery.com/jQuery.ajax/ if you have trouble on using .ajax().
Note: in .ajax() method, there is a setting called beforeSend, which "can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent". Hope this method helps you in any way.
Then, your JavaScript code will be like this:
$(document).ready(function(){
$("#Change").click(function(){
//doing AJAX request
$.ajax({
url:"include/start10.php",
beforeSend:function(){
$('#myDiv').fadeOut('slow');
},
success:function(data){
// do something with the return data if you have
// the return data could be a plain-text, or HTML, or JSON, or JSONP, depends on your needs, if you do ha
$('#myDiv').fadeIn('slow');
}
});
});
});
You cannot include PHP file with AJAX, but instead the response of the AJAX server-side script, which is the PHP (which has the same effect).
Loading...
The JS file (code):
function ajaxalizeDiv()
{
$.ajax({
type: "get",
url: "/path/to/the/php/you/want/to/include",
data: {
// Anything in json format you may want to include
id: myvarwithid, // descriptive example
action: "read" // descriptive example
},
dataType: "json",
success: onAjax
});
}
function onAjax(res)
{
if(!res || !res.text)
return;
$("#mydiv").html(res.text);
}
And here goes the PHP file:
<?php
$id = (int) #$_GET['id']; // same as in data part of ajax query request
$action = #$_GET['action']; // same as in data part of ajax query request
$text = 'click me';
// Note this is short example you may want to echo instead of die
// You may use not JSON, but raw text. However, JSON is more human-friendy (readable)
// and easy to maintain.
// Note also the array keys are used in the onAjax function form res (response).
die(json_encode(array('text' => $text /* and anything else you want */)));
?>

JQuery / PHP call with AJAX not working

I've been trying to get this really simple example of using AJAX with JQuery and PHP to work with no luck (here's the page for the sample). I've had a look at quite a few posts with similar discriptions and none have helped...
I've copied the code exactly but my function that should be run on success is never called. As an experiment, in the call to $.post I commented out the data part ({sendValue:str}) and the JSON part and added an alert into the body of the success function to see if it was called and it was. So I'm guessing there's something wrong with how I've created my data? I also tried to display the data returned from the AJAX call in the alert and it came out as 'undeclared' (data.returnValue).
This is a copy of my code, you can see the full example via the link above and also a working example from the author of the tutorial here: http://www.devirtuoso.com/Examples/jQuery-Ajax/
JQuery:
$(document).ready(function(){
$('#txtValue').keyup(function(){
sendValue($(this).val());
});
});
function sendValue(str){
$.post("ajax.php",
{ sendValue: str },
function(data){
$('#display').html(data.returnValue);
},
"json"
);
}
PHP:
<?php
//Get Post Variables. The name is the same as
//what was in the object that was sent in the jQuery
if (isset($_POST['sendValue'])){
$value = $_POST['sendValue'];
}else{
$value = "";
}
//Because we want to use json, we have to place things in an array and encode it for json.
//This will give us a nice javascript object on the front side.
echo json_encode(array("returnValue"=>"This is returned from PHP : ".$value));
?>
HTML:
<body>
<p>On keyup this text box sends a request to PHP and a value is returned.</p>
<label for="txtValue">Enter a value : </label><input type="text" name="txtValue" value="" id="txtValue">
<div id="display"></div>
</body>
Thanks!
EDIT:
I rewrote my $.post into a $.ajax with an error function in it. I'm definitely hitting the error function and the error is a parse error - I'm guessing it's coming from my PHP script when I call json_encode... here's a screenshot from firebug - anyone got any more ideas?:
Screenshot 1 - firebug console
Screenshot 2 - firebug watch window
Thanks for all the help so far by the way, really appreciate it.
I noticed that var str = $('#txt').val(); would give you an error because $('#txt') does not exist, it should be $('#txtValue').
After looking at your code, everything looks as it should, my next step would be trying to debug your code by using some console.debug() in JavaScript and some echo in PHP. I recommend you get Firebug for Chrome/Firefox and if using IE upgrade to IE9 and use their developer tools. Using the mentioned tools will give you a better idea of how your code is executing.
My first step would be to make sure that the keyup is firing:
$(document).ready(function(){
$('#txtValue').keyup(function(){
alert('keyUp');
sendValue($(this).val());
});
});
Second step would be to make sure sendValue is firing:
function sendValue() {
alert('sendValue');
var str = $('#txt').val();
tmr = null;
$.post(
'test.php',
{ sendValue: str },
function(data) {
alert('inside post');
$('#output').html(data.returnValue);
},
'json'
);
}
Without seeing more of what your various elements are outputting, I don't think I can tell you what to fix, but this example is similar to yours (although it's an all-in-one PHP file rather than two, as in your example). I also added a 350ms timeout to allow the user to type without having the page do an AJAX request every keystroke. As soon as they pause, it'll fetch the data.
Source to test.php
<?php
if(isset($_POST['sendValue']))
{
echo json_encode(
array('returnValue' =>
'Returned: ' . $_POST['sendValue']));
exit();
}
?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>AJAX Sample</title>
</head>
<body>
<input type="text" id="txt" />
<div id="output"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"
type="text/javascript"></script>
<script type="text/javascript">
var tmr = null;
$(function () {
$('#txt').keyup(function() {
if(tmr != null)
clearTimeout(tmr);
tmr = setTimeout("sendValue()", 350);
});
});
function sendValue() {
var str = $('#txt').val();
tmr = null;
$.post(
'test.php',
{ sendValue: str },
function(data) {
$('#output').html(data.returnValue);
},
'json'
);
}
</script>
</body>
</html>
To anyone who gets here looking for an answer to a similar question:
I tried a few things to figure out what was going on, debugging the messages etc and everything looked fine. I then deployed my code to a virtual box running apache and to my web server to see if it was an environmental thing. My code worked on my web server and on the virtual box. I then realised that I had two conflicting installs of PHP on my dev system. I'm not sure why but this was causing the problem but rolling them both back and reinstalling WAMP on the dev system did the trick.
try this
$(document).ready(function(){
$('#txtValue').keyup(function(){
$.post("ajax.php",{ sendValue: str }, function(data){
$('#display').html(data.returnValue);
},
"json"
);
});
});

I am extracting data from an external URL and unable to get the javascript functions working

I want to load the external page's data into a div along with the javascript functions(though the js file is same for both of them, the functions do not work). The file loads fine into the page, but the javascript function don't work properly.
My Code-
var emaild = $("#hidden").val();
var div = $("#mydiv");
var refreshId = setInterval(function() {
$.getScript("js.js", function() {
div.html($("#load").load('posts.php?id='+emaild));
});
}, 6000);
$.ajaxSetup({ cache: false });
Thanks in advance. Hope I get a solution soon! :D
You may have a problem here:
div.html($("#load").load('posts.php?id='+emaild));
$.html() expects an html string and you're giving it a deferred instead. It may not be the cause of your script not running, but good to eliminate anyhow.
Is there a reason why you're using $("#load").load when you want the output of the call to go inside div. In other words, isn't this what you really want?
div.load('posts.php?id=' + emaild);

POSTing data to the server, behind the scenes

I'm building a website which has a page that users can add content to, and they can rearrange the divs to whichever position and size they want. I'd like to have a save button which saves the current position of each div; however, I don't want the page to refresh each time (I'm also going to have an auto-save, which will have to save the information in the background).
I can't figure out how to post the data to the server though, without causing the page to reload. I figure I need some kind of AJAX request, but can't find anything that tells me how to do that (all the AJAX examples I can find seem to be about reading data from the server). I think I'm just starting to go round in circles now, but I can't get my head around this at all - I know it's probably not a hard thing to do, but I keep getting confused by the different examples.
So, first of all, is this the best way to do it? And, if so, can someone point me to a straightforward example of posting data via AJAX? I'm already using jQuery, so can use that for the Ajax as well.
Thanks.
Super simple AJAX with jQuery:
$.ajax({
url: '/save-the-stuff-url',
type: 'POST',
data: {
// information about your divs, etc.
'foo' : 'bar'
},
success: function(response) {
// if the AJAX call completes successfully, this function will get called.
alert('POST successful!');
}
});
Give it a shot!
Here, try this for AJAX:
$.post("example.php", {
from : "ajax", // put some info in these - they are the params
time : "2pm",
data : "save"
},
function(data) { // callback function - data always passed to it
$("#success").html(data); // do something with that data
}
);
And put this somewhere:
<span id='success'></span>
And then, try this example for example.php:
<?php
if(isset($_POST['from']) and $_POST['from'] == 'ajax'){
echo "<span style='color: green;'>Saved!</span>";
}
else {
echo "<span style='color: red;'>Failure!</span>";
}
?>
And then just modify these to fit your needs, probably changing the file of target. Whatever the script outputs is what is given to the ajax request. This means that if this was my PHP script:
<?php echo "Aloha!"; ?>
And this was my javascript:
$("#output").load("myScript.php");
Then #output would have "Aloha!" in it.
Hope this helps!
Please go through the Jquery site for various examples of post.
HTH
and the jQuery docs pages are a great way to learn jQuery.. the page for post is http://docs.jquery.com/Post
you may also want to look at jQuery draggables if you're not using that yet..
http://docs.jquery.com/UI/API/1.8/Draggable
you can fire a save tied to your draggable object being let go rather easily with
$( ".selector" ).draggable({
stop: function(event, ui) { ... }
});

Calling JavaScript within Php block and vice-versa

echo "<a href=#> Delete </a>";
Whenever a user hits Delete, a javascript function should be called for confirmation. Somewhere in the Javascript function, php code should be used for delete operation. How do I do that? Use something like "some php code goes here" and "some javascript function();" for me to know where to put what. Thanks.
This assumes that you are using jQuery...
<a href='javascript:delete();'>Delete</a>
<script type="text/javascript">
function delete()
{
$.post("/your_script.php", {}, function(result) {
});
}
</script>
JavaScript functions execute on the client (in the browser) and PHP executes on a server. So, the JavaScript must send a message - via HTTP - to the server to be handled by PHP. The PHP would perform the delete. Make sense?
The message sent to the server might be sent via AJAX.
Maybe you should use Ajax: http://en.wikipedia.org/wiki/Ajax_%28programming%29
PHP is a server-side technology, while JS is a client-side. They cannot interact with each other - in other words: they're completely independent.
PHP can only output code that is a JS code:
echo 'document.getElementById("test").appendChild(document.createTextNode("' . $myVar . '");';
It's all PHP can do. JavaScript cannot direct interact with PHP as well. You'll have to use AJAX to send a new HTTP request and process returned data.
PHP is a server-side language, thus you can not output PHP script to the browser and expect that it will parse it with the PHP engine.
What you're looking for is probably AJAX, or simply redirecting the user to another page (with different URL parameters) or submitting a form.
AJAX doesn't require from the browser to reload the page, while the two other methods does.
Anyway, you can execute a JS script with the "onclick" method, that's executed when the user clicks on the element: Delete
But the following approach looks better and considered as an ideal one:
Delete
<script type="text/javascript">
document.getElementById("myId").onclick = myFunc;
</script>
Since this involves Ajax, let's assume you can use jQuery to handle the XHR an so on.
<script>
$('#del').click(function(ev){
ev.preventDefault();
var del_conf=confirm('Are you sure you want to delete this item?');
if(del_conf){ $.post('delete.php',{'del':1,'id':123123},function(data){
alert(data.result);},'json');
}
});
</script>
<a id='del'>Delete</a>
Okay, so that's some JS and HTML. Now, you need a separate PHP script to handle the post. To go with the example, this would be saved in the same directory, named 'delete.php'.
<?php
$del=(int)$_POST['del'];
$id=(int)$_POST['id']
if($del<1 || $id<1){ exit; }
else{
//do your DB stuff
}
if($db_success){
echo json_encode(array('result'=>'success'));
}
else{
echo json_encode(array('result'=>'error'));
}
here is another example using jQuery:
<div id="message"></div>
<a class="action" type="delete" rel="1234567">delete</a>
<script type="text/javascript">
$('a.action').click(function(){
var $this = $(this);
var processResponse = function(data){
//optionaly we can display server response
$('#message').html(data);
return;
};
var postPparams = {
module:'my_module_name',
action:$this.attr('type'),
record_id: $this.attr('rel')
};
$.post('/server.php',postPparams, processResponse);
});
</script>

Categories