Passing variable from jquery to php - php

i want to pass a variable from jquery to php but my code doesnt work .I tried very hard but no luck . When i click the button nothing happens.plz help thank you
one more thing i tried this without passing variable and i use only echo command then it works but when i pass variable nothing happens
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$("button").click(function(){
var var_data = 5;
$.ajax({
url: "myscript.php",
data: { var_php_data: var_data },
success: function(data) {
// do something;
alert(data);
}
});
});
</script>
</head>
<body>
<button>Change Content</button>
</body>
</html>
myscript.php contains the following code
<?php
echo $_GET['var_php_data'];
?>

Try wrapping your script in a document ready handler. Also you have a trailing comma (,) after the success callback that you should remove. Also you should use a , instead of ; after the data parameter. Specifying the HTTP verb for your AJAX request might also be useful:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('button').click(function() {
var var_data = 5;
$.ajax({
url: 'myscript.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
alert(data);
}
});
});
});
</script>
</head>
<body>
<button>Change Content</button>
</body>
</html>
The reason you need to wrap your click registration in a document ready handler is because you put your script inside the <head> section of your markup and the button hasn't yet been loaded by the browser when you attempt to subscribe to its click handler.

You can install Firebug (Firexox plugin), or user something similar for your browser to see real HTTP request and response. If you will post them here it will be more simple to find the problem.

Track request in FireBug. You can find by FB did request success (200) as well as date send by request.
Also, try http://{your_host}>/myscript.php?var_PHP_data=echoText
Addition:
Darin Dimitrov described the problem right way

Related

JQuery.Ajax Success but just returns server PHP code as text

I am running a very simple Jquery.Ajax call as a test. The code should work as it is an example from a programming class. However, on my Windows XAMPP, all I get back in the alert is the ajax.php code in html format... I do get a success 200 code though from the Ajax query. I'm at a loss for what is wrong. Does anyone have any suggestions?
Ajax.html
<!DOCTYPE html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
// Handler for .ready() called.
useJQuery();
});
function useJQuery() {
$.ajax({
type: 'POST',
url: "ajax.php",
data: { i_want_text:'yes' },
success: function (response) { alert(response); },
});
}
</script>
</head>
<body>
</body>
</html>
Ajax.php
<?
if ($_POST["i_want_text"]) {
print "text received with value of " . $_POST["i_want_text"];
}
?>
from php documentation http://php.net/manual/en/language.basic-syntax.phptags.php
PHP allows for short open tag <? (which is discouraged since it is only available if enabled using the short_open_tag php.ini configuration file directive, or if PHP was configured with the --enable-short-tags option).`
so In ajax.php change <? to <?php

New to ajax and can't set the session variable with a post request

I've been struggling with this for two hours now and I've narrowed down the issue to a simple test case. I've done plenty of research and finally settled on trying to reproduce the first answer from this question: Set session var with ajax.
When I push this button (lazy html, but that's not where the issue lies):
<html>
<head>
...
<script src="jquery.js"></script>
...
<head>
<body>
....
<?php
var_dump($_SESSION);
?>
<input type="button" class="update">
....
</body>
</html>
This ajax request in jquery.js gets called:
$.(".update").click(function() {
$.ajax({
type: "POST",
url:"setSession.php",
data: {bar: "foobar"},
success: function() {
console.log("Successful request sent");
}
});
And finally the setSession.php file:
<?php
session_start();
$_SESSION["foo"] = $_POST["bar"];
?>
The success message is printed to the console so I know I'm hitting the right file. Why isn't the session variable getting set? I have php 5.5.2 if that matters at all. Thanks for you help!
Like I suggested on the comments, do this to fix your code:
Reload the page on your success:
success: function() {
console.log("Successful request sent");
location.reload();
}
Make sure you have session_start() in all the pages that uses sessions:
session_start(); //this must be at the top, before you print anything
Might this can help you.
In setSession.php write echo $_SESSION["foo"] = $_POST["bar"];
In your ajax script do
$.(".update").click(function() {
$.ajax({
type: "POST",
url:"setSession.php",
data: {bar: "foobar"},
success: function(e) {
console.log(e);
}
});
now open browser console (F12). click on your button.update. Check if is there written bar in console.

jQuery calling php script onload

I am trying to use jQuery's ajax to call a php script onload. This script will return xml from a url web service, parse through it, and then display bits and pieces of it into a div tag when the page loads (onload). I'm okay with php when it comes to using forms, but getting php scripts to run onload is not working for me. Could someone please look through my code and give me your advice? Thanks in advance.
HTML:
<!doctype html>
<html>
<head>
<title>Word of the Day</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="code.js"></script>
</head>
<body>
<h3>Word of the Day: </h3>
<div id="word_day"></div>
</body>
</html>
JavaScript:
$(document).ready(function() {
$(window).load(function() {
$.ajax({
post: "GET",
url: "word_day.php"
}).done(function() {
alert(this.responseText);
}).fail(function() {
alert(this.responseText);
});
});
});
I did not add my PHP code since I was pretty sure that it wasn't the cause of my frustration.
You don't need those two handlers, just one:
$(document).ready(function()
{
$.ajax(
{
post: "GET",
url: "word_day.php"
}).done(function()
{
alert(this.responseText);
}).fail(function()
{
alert(this.responseText);
});
});
As you had it you were trying to create one handler when the handler fired which was never going to work.
Edit:
Your done/fail part should look like:
}).done(function(data)
{
alert(data);
}).fail(function(jqXHR, textStatus, errorThrown)
{
alert(textStatus);
});

communication between PHP and Javascript

I want to send some data to Javascript from PHP.(these two file is different file in same folder)
For example, If I calculate some value in PHP side, I want to send the data to javascript and I use the data.
How can I do this??
There's complete technology for that called AJAX with a lot of tutorials on the internet.
And there's already a great and easy-to-deploy implementation - within jQuery.
In practice, you can use this:
FILE: index.php
<HTML>
<body>
<input type="text" id="test" value="123"><br>
<input type="button" id="btn" onclick="send_to_php()" value="send to php">
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
function send_to_php() {
$.ajax({
url: 'js_php.php',
type: 'POST',
// Form data
data: function(){
var data = new FormData();
data.append('test', $("#test").val() );
return data;
}(),
success: function (data) {
var obj = JSON.parse(data);
$("#test").val( obj.result );
},
error: function (data) {
console.log(data);
},
complete: function () {
},
cache: false,
contentType: false,
processData: false
});
}
</script>
</body>
</HTML>
FILE: js_php.php
<?php
//FILE: js_php.php
$test = $_POST["test"];
$test .= "456";
$arrResult = array(
'result' => $test
);
print json_encode($arrResult);
die();
?>
The file "index.php" is the communication between JavaScript and PHP using jQuery Ajax method.
When click the "send to php" button will run the "send_to_php ()" that will take the value of the input id "test" and send through ajax, for "js_php.php" file.
In turn, the file "js_php.php" will receive this variable as POST, modify and print the value in JSON format.
The method implemented by ajax function "send_to_php ()" will be "listening" all that "js_php.php" print.
After the success of the return, javascript convert the text "js_php.php" printed on a JSON object and then the JS able to process within the javascript code:
success: function (data) {
var obj = JSON.parse (data);
$("# test").val(obj.result);
},
<script type='text/javascript'>
var myVar = <?php echo $myVar; ?>;
</script>
in a nutshell. There are more sophisticated way to communicates though.
Have a Look at this AJAX Tutorial: http://news.php.net/php.general/219164
Assign a JavaScript global variable in a script tag in the PHP page, and include the other javascript files after.
Sample:
<html>
<head>
<script type='text/javascript'>var testGlobal = <?php echo $globalJSValue ?></script>
<script type='text/javascript' src="url"></script>
<script type='text/javascript' src ="url"></script>
</head>
</html>
testGlobal variable will now be available to both javascript files.

Submit a form and reload data on same page

I got a left_column with a #form, when I sumbmit it should load the results on #content_div without refreshing the page.
Im using this:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">
$(function() {
$('#dateform').submit(function(evt) {
evt.preventDefault();
$.ajax({
url: "charts/client.php",
type: 'POST',
data: $(this).serialize(),
success: function(result) {
$('#content_div').html(result);
}
});
});
});
</script>
<div id="content_div">
Nothing seems to appear.
And firebug reports this:
ReferenceError: google is not defined
This charts/client.php is using google api, and yes i've declared it like this:
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
What am I doing wrong?
Thanks
use ajax form
<script>
// wait for the DOM to be loaded
$(document).ready(function()
{
// bind 'myForm' and provide a simple callback function
$("#tempForm").ajaxForm({
url:'../calling action or servlet',
type:'post',
beforeSend:function()
{
alert("perform action before making the ajax call like showing soinner image");
},
success:function(e){
alert("data is"+e);
alert("now do whatever you want with the data");
}
});
});
</script>
you can find the plugin here
It seems that the error you get is from the client.php, not from the actual jquery ajax script.
Probably you tried to call a google method before creating a new instance of the google object you used. I could help you out more if you post the client.php's code here.
For example, when i have worked with gmaps api:
trying to do:
geocoder.geocode( { 'address': target}, function(results, status) {...
before setting :
var geocoder = new google.maps.Geocoder();
will return "google is not defined";

Categories