Trying to call PHP file using jQuery Ajax - php

I am developing using jQuery 2.0.2 on Debian 7.0.0.
I am trying to call a PHP script from a JavaScript file using jQuery.ajax. My code is as follows.
jQuery.ajax({
type: "POST",
url: "DisplayParameters.php",
data: { LUT:lut,
Brightness: brightness,
Gamma: gamma,
Background: background}
}).done(function( result ) {
$("#msg").html( " Ajax called" );
});
At the beginning of DisplayParameters.php, I have the following.
?>
<script language="JavaScript">
alert('DisplayParameters');
</script>
<?php
but the alert box is not called. Firebug proceeds without any errors and shows the DisplayParameters.php text (with a +/- control to collapse and expand it). But the alert box is not called. I cannot get any feedback from DisplayParameters.php to trace what is happening.
What would be the best way for me to get feedback (like alert boxes or console.log) from DisplayParameters.php?

Your ajax call returns the contents of DisplayParameters.php as text, console.log(result) would show:
<script language="JavaScript">
alert('DisplayParameters');
</script>
If you want to add this extra code to the page (which I don't recommend unless you are sure you won't break the current page), you can try:
jQuery.ajax({
type: "POST",
url: "DisplayParameters.php",
data: { LUT:lut,
Brightness: brightness,
Gamma: gamma,
Background: background}
}).done(function( result ){
$("#msg").html( " Ajax called" );
$("body").append(result);
});
Another approach would be to serialize (JSON) the information you need, set the dataType: "json" option, and act based on this information.
If you will send HTML, ensure your PHP code doesn't shows any error or warning messages.

The alert() should happen inside .done() on the ajax call. Like the following:
.done(function(result) {
alert(result);
$("#msg").html( " Ajax called" );
});
And instead of alerting on DisplayParameters.php, use echo so that that will be the returned value for result. Like the following:
<script language="JavaScript">
//...some JS codes here
<?php echo 'DisplayParameters'; ?>
</script>

Related

POST PHP error via Ajax on unsuccessful login

I'm trying to get a Bootstrap Alert to be shown when a user could not be logged in.
To do this, I am using Ajax (jQuery) and POSTing the error upon redirect, to the script on my index.php
Here is the PHP on login.php:
$message = "Your Email or Password combination were incorrect. Please try again.";
echo json_encode($message);
header('Location: /');
and my jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: "message",
success: function (response) {
var message = jQuery.parseJSON(message);
$('#alert').text(message);
}
})
});
</script>
What I'm trying to achieve is:
User tries to log in (and fails)
Redirected to home page (as my login form is in the header)
Error alert is shown, with the $message content as the error text.
When I make an incorrect login (to trigger the error) I get
JSON.parse: unexpected character at line 1 column 1 of the JSON data
I'm still a beginner with jQuery, and have tried to follow other examples which is why my code probably doesn't make sense (and why it isn't working).
I'm using firebug on Firefox to debug the jQuery.
Thanks for your time
I believe your error lies in a misunderstanding of what the line: $(this).attr('action') is doing in your $.ajax call.
When I run your code the function works perfectly... except that it loads the current page! Which is exactly what you told it to do. Sending $(this).attr('action') in the url: parameter just told your ajax function to load the current page. As the current page has javascript and presumably HTML defined in it the response is not valid JSON.
What you want to do is change:
url: $(this).attr('action'),
To:
url: 'path/to/login.php',
i change type and remove comma
make a json request and chage success to done
try this
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
method: "POST",
url: $(this).attr('action'),
data: "message",
dataType: "json"}).done(function () {
var message = jQuery.parseJSON(message);
$('#alert').text(message);
})
}

change php variable with ajax

I have an php variable like this:
PHP Code:
$php_value = 'Am from PHP';
And I want to be able to change this variable with jQuery and the jQuery is on the same page?
You can't.
By the time the page has been delivered to the browser and the JavaScript has run, the PHP program that generated the page will have finished running and the variable will no longer exist.
JavaScript will allow you to send new data to the server (Ajax), where the server could store the data somewhere (a database is usual), and read the response.
JavaScript will also allow you to modify the page in in the browser (DOM) (including with the data included in the response for an Ajax request).
PHP code is run server-side, and jQuery runs on the client. The way to update a PHP variable from jQuery is to have a jQuery call which submits to the PHP page, and have the PHP look for it:
$php_value = 'Am from PHP';
if exists($_POST['php_value_from_jquery']) {
$php_value = $_POST['php_value_from_jquery'];
}
If I understand your question correctly, AJAX cannot post data to PHP code on the same page. I've been told that it can, but it is not trivial - still, I cannot imagine how that is possible. At any rate, AJAX is easy if a secondary PHP file is used.
Here is an example of what I mean. If you try this:
<?php
echo 'Hello';
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '',
success: function(data) {
alert(data);
}
});
}); //END $(document).ready()
</script>
</head>
<body>
</body>
</html>
The popup will contain the HTML for the page.
However, if you use two files:
file1.php
<?php
echo 'Hello';
?>
file2.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'file1.php',
success: function(data) {
alert(data);
}
});
}); //END $(document).ready()
</script>
</head>
<body></body>
</html>
The popup will contain only the word "Hello".
To use ajax, you must call an external PHP file.
After considering the above, note that Quentin's answer is important -- even if you use AJAX to set a PHP variable on the server, that variable disappears after the AJAX completes -- just like the PHP variables all disappear after your index.php has finished rendering the DOM and presenting it to the visitor's browser.
So, what's to be done? Two options.
(1) As Quentin points out, you can store values permanently in a database, or
(2) You can use a PHP superglobal, such as a $_SESSION variable. For example:
Client side: file2.php
var storeme = "Hello there";
$.ajax({
type: 'POST',
url: 'file1.php',
data: 'stored_on_server=' +storeme,
success: function(data) {
alert(data);
}
});
file1.php
<?php
session_start();
$SESSION['a_variable_name'] = $_POST['stored_on_server'];
You can later retrieve that variable value thus:
$.ajax({
type: 'POST',
url: 'file3.php',
success: function(data) {
alert(data); //a popup will display Hello There
}
});
file3.php
<?php
session_start();
echo $SESSION['a_variable_name'];
You can't able to change the php value using javascript. i.e Server scripts runs first after that client side script will take effect in that case you cant able to modify the same, since they already rendered in browsers
If jQuery is going to be processing the data, then you can assign the PHP variable to a jQuery variable like this:
<script>
var jquery_value = <?php echo $php_value; ?>
</script>
As far as I know, because jQuery is client-side and php is server side, it's not possible to assign a jQuery variable back to PHP.

Simple jquery ajax php request

I am doing a basic jquery ajax call on a php file and can't seemsto figure out why it isn't working. Any help is appreciated. Fiebug does not seem to show any ajax or XHR action going on. I want to not to refresh the page and just execute the ajax call. Thanks.
JS
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"</script>
<script>
function getData(url_param){
$.ajax({
type: 'get',
url: 'data.php',
data: {url_param:url_param},
success: function(data) {
$('#data').html(data);
}
});
};
$('#clickMe').click(function(e){
e.preventDefault();
getData(2);
});
</script>
HTML:
<div><a id='clickMe' href='data.php?url_param=url_param'>CLICK ME TO RUN PHP</a></div>
<div id="data"></div> <!-- divto show result -->
PHP:
<?php
if($_GET['url_param']){
echo "simple ajax call";
}
?>
You have to bind the event inside an onload function. The most common practice is:
$(document).ready(function(){
$('#clickMe').click(function(e){
...
});
});
You should also add return false; in the last line of your event.
First, you have misspelled your function name (getGata != getData).
Secondly:
data: {url_param:url_param}
Are you setting the javascript variable url_param anywhere? The $.ajax data parameter is formatted as follows:
get/post variable name : get/post variable value
As you have it now, it doesn't seem that you are assigning a value to url_param.
you can simply use jQuery post function.
$.post('data.php',{param1:'your param 1', param2 : 'your param 2'}, function(response){
//do your operation here. response is what you get from data.php. 'json' spicifies that the response is json type
$("#data").html(response);
},'json');
The (amended?) JavaScript prevents your code from working, because you haven't closed the angle brackets on jQuery source, it should be:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
One of the comments states you shouldn't have the href in the anchor, but because you've ignored defaults this isn't triggered (assuming JS is enabled in the user's browser).
Finally, I think that
return false;
should really be inside the function after
getData(2);
but since we're ignoring defaults, the anchor shouldn't make an attempt to go anywhere or reload anyway.

Ajax jquery returns blank page

I have this JavaScript code:
$(document).ready(function(){
$('#sel').change(function(){
$.ajax({
type: "POST",
url: "modules.php?name=TransProject_Management&file=index",
data: "&op=index_stat&stat="+$(this).val(),
cache: false,
success: function(data) {
//alert(data);
$("#ajax_results").html(data);
}
});
});
});
On status change i need to refresh a div without page reload. But it returns blank page. If i try alert the result on success, i get the response, also i checked with inspect element, its ok. The problem is that it returns blank page.
The file i'm working on, is the same( modules.php?name=TransProject_Management&file=index ) i called in ajax.
the html:
<body>
//...
<div id="ajax_results">
//.....
//somewhere here is the select option <select id="sel">......</select>
//.....
</div>
</body>
Any help, would be very appreciated.
use the following code to return your response html:
echo json_encode(array($your_response));
Then in your javascript, you will need to reference the data as:
success: function(data) {
$("#ajax_results").html(data[0]);
}
since it is now an array.
this in your ajax function refers to the jQuery XHR object, NOT the $('#sel') object. Just assign it to a variable before the ajax function like var sel = $(this) then use it later inside the function. Try this:
$('#sel').change(function(){
var sel = $(this);
$.ajax({
type: "POST",
url: "modules.php?name=TransProject_Management&file=index",
data: "&op=index_stat&stat="+sel.val(),
cache: false,
success: function(data) {
//alert(data);
$("#ajax_results").html(data);
}
});
});
});
Hmm, first glance the code looks good. Have you tried using Chrome debug tools? Hit F12 and check the Network tab, this will show you what is being returned. You can also debug without using an alert so you can step through to see what exactly the properties are.
Just thought, you might need to add 'd' to the data returned. Anyway, if you do what I suggested above, put a pause break on the line and run the code you will see what you need.
Based on your comments below the question, it seems that you are using the same script to display your page and to call in the javascript. This script seems to return a complete html page, starting with the <html> tag.
A page can only have one <html> tag and when you try to dump a complete html page inside an element in another page, that will lead to invalid html and unpredictable results.
The solution is to have your ajax script only return the necessary elements / html that needs to be inserted in #ajax_results, nothing more.

First ajax call doesn't work

I'm trying ajax for the first time but it doesn't work.
This is "some.php" which handles the ajax call:
<?php
echo "success";
?>
And this is the javascript that calls it:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.min.js"></script>
<script type="text/javascript">
var msg;
$.ajax({
type: "POST",
url: "some.php",
data: ({ })
success: function(msg){
alert( msg );
}
});
</script>
Can you see where the problem is?
I should state I'm working under wordpress and both files reside in \wp-content\themes\twentyten (maybe the url in the ajax call is wrong?)
First of all remove the data:({}) which is pointless. you are also missing a , behind your data statement. this is most likely the issue.
if both the files is in the same directory, then the url should be correct.
However, i urge you to use a tool like FireBug in order to debug your problem further
You should run your script when the page has loaded (more precisely, when the DOM is ready). jQuery offers an event for that.
Your code could then look something like this:
$(document).ready(function(){
$.ajax({
type: "POST",
url: "some.php",
data: ({ })
success: function(msg){
alert( msg );
}
}
});
Two things to do:
register a .fail callback. The code as it is will just call the alert() if it succeeds, otherwise, errors are not raised. See http://api.jquery.com/jQuery.ajax.
check the web server log to see if some.php is exec'd and if so, what errors may be occurring on the server.

Categories