jQuery post/ajax post problem - php

HI im trying to send a jquery post/ajax to send some variables to a php file.
<script src="/jquery.js"></script>
<script type="text/javascript">
var music ='';
var genre ='';
var language ='';
var nasheedid = "<? echo $postid; ?>";
var session = "<? echo $_SESSION['SESS_TMP']; ?>";
$(function(){
$('.submit').click(function(){
var postdata = {pmusic: music, pgenre: genre, plang: language, psession: session};
$.ajax({
type: 'post',
cache: false,
url: 'addmusic.php',
data: postdata,
success: function (msg) {
alert(msg);
},
dataType: "text",
});
});
});
now regardless of where i post the stuff to, (even if i change the url to url: blahblah.php123 I still get the same results (which is):
The alert displays the entire source code of the file (that the above code is on)

May be you are having an exception on those pages and its redirecting to the same page so you are seeing the same page everytime. Try to debug your server side code and see.

thanks guys i fixed the problem myself. My server was using rewrite so i had to use url: "/addmusic.php" instead of url: "addmusic.php".

So you see the PHP code in the alert? There are a few causes for this.
You don't have a WAMP stack installed. If not, you need to install WampServer or XAMPP.
It's not configured properly. It could be that PHP isn't setup correctly.
Your configuration doesn't support short tags (<?). Try changing them to <?php.
You're not accessing the file through the server properly. Look at the beginning of the URL, make sure it starts with http://localhost/ .
You might also try using jQuery.post() instead.
It's also best to use json_encode() when outputting from PHP to Javascript.
var nasheedid = <?php echo json_encode($postid); ?>;
var session = <?php echo json_encode($_SESSION['SESS_TMP']); ?>;
It will take care of quoting, escaping, etc.

Related

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.

which is the best method to move php code out of js in ajax

I am developing an application in Yii.. One issue i am facing is, when i am writing ajax functions, the url's will be in php. so i am unable to move the codes to another javascript file.
$.ajax({
url: "<?php echo Yii::app()->createUrl('provider/ajaxdetail');?>",
data: {'type':tagtype},
beforeSend: function() { },
success: function(data) {
}
});
so what is the best method to move php out of the javascript so that i can move the javascript code to another js file. I Thought of putting the url's in a hidden box and then call it in the javascript function. but i hope there will be better methods to do this .
please help
you could create a global variable to store the url, in your html head , so that any js file that needs the url can access it, like:
<html>
...
<head>
..
var MY_APP_URL = '<?php echo Yii::app()->baseUrl; ?>'; //can be like www.somesite.com/
....
//load js files
...
and in the js file you could do:
$.ajax({
url: MY_APP_URL + "controller_name/function_name",
data: {'type':tagtype},
OR you could do:
Yii::app()->clientScript->registerScript('helpers', '
someUrl = '.CJSON::encode(Yii::app()->createUrl('blabla')).';
baseUrl = '.CJSON::encode(Yii::app()->baseUrl).';
');?>
and you can use variables someUrl and baseUrl in your Javascript files

How to properly pass a jquery value to php using ajax?

I want to pass a value from my jquery code to a php variable after a user inputs through a textbox, but I don't receive any value at all in the PHP side through POST.I'm using .change and .post, does anyone here knows how to do it properly?
here's my code:
$(document).ready(function(){
$("#packagename").change(function(){
var packagename = $('#packagename').val();
var url = '{{url}}'; //localhost/test/test.php
$.ajax({
type: 'post',
url: url,
dataType:html,
data:{'val':packagename},
});
});
});
try it
$(document).ready(function(){
$("#packagename").change(function(){
var packagename = $('#packagename').val();
var url = '{{url}}'; //localhost/test/test.php
$.ajax({
type: 'post',
url: url,
dataType:text,
data:{'val':packagename},
success:function(result){
alert(result);
}
});
});
});
The only problem that I can see offhand is that the html in dataType:html, needs to have quotes around it like this: dataType: 'html',. Otherwise your code will look for the variable html, not find it, and throw an error.
http://api.jquery.com/jQuery.post/
dataType
Type: String
The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).
change dataType: html, to dataType: 'html',
Have you tried just putting the url into the url field instead of whatever that object is you are trying to use?
I will assume you are not trying to ajax to the page you are currently on and expecting the php variable to display on the current page.

Wordpress bloginfo('template_directory') not working in jquery

I have a custom jquery file in a wordpress site and I am trying to use the bloginfo('template_directory') assigned to a variable to use in the ajax url paths rather than having to type out the full url each time (especially as this is in development on a test site at the moment so need to ensure everything works when moving to the live site on the actual domain), however all that happens is that the php is added to the url, not the directory path.
What I have at the moment:
$(document).ready(function(){
var templateDir = "<?php bloginfo('template_directory') ?>";
// Login
$('.login-form').on('submit', function(e){
e.preventDefault();
dataString = $(this).serialize() + '&ajax=1';
$.ajax ({
type: "POST",
url: templateDir + "/inc/do-login.php",
data: dataString,
cache: false,
success: function(data)
{.
.
.
}
});
});
And what I get in the console error is (site url replaced with ...):
POST http://www......./...../%3C?php%20get_bloginfo('template_directory')%20?%3E/inc/do-login.php 404 (Not Found)
Can anyone shed any light on this please.
You need to create a Javascript snippet that saves the template dir in a variable, and you can use later using that variable
<script type="text/javascript">
var templateDir = "<?php bloginfo('template_directory') ?>";
</script>
You need to move your templateDir variable out of your javascript file. The reason is because your php will not be interpreted. This means your templateDir variable will literally be equal to "<?php bloginfo('template_directory') ?>";
Luckily you can can still use javascript variables from other scripts or in your html directly.
Here is one solution.
This is your similar to your script but with a few modifications. Read carefully.
$(document).ready(function(){
// Login
$('.login-form').on('submit', function(e){
e.preventDefault();
dataString = $(this).serialize() + '&ajax=1';
$.ajax ({
type: "POST",
url: custom.templateDir + "/inc/do-login.php",
data: dataString,
cache: false,
success: function(data)
{
}
});
});
Now in your functions.php you can use use this trick to add javascript variables that can be accessed by your script:
function custom_init_js()
{
wp_enqueue_script('jquery');
wp_localize_script('jquery', 'custom', array(
'templateDir' => get_bloginfo('template_url')));
}
add_action('get_header', 'custom_init_js');
This will result in the following snippet of javascript being added your html pages.
<script type='text/javascript'>
/* <![CDATA[ */
var custom = {"templateDir":"https://www.website.org/wp-content/themes/yourTheme/"};
/* ]]> */
Now you can assess your template directory by using custom.templateDir in your script. The custom object comes from the wp_localize_script function. You can name this whatever you want.
Additionally you want to use get_bloginfo('template_url'), since template_dir will get you the file path and not the url, which is what you want.
When using this approach, the wp_localize_script is called only when you load the specified script with wp_enqueue_script. In this case, I used jquery.
wp_localize_script is mainly used for internationalization, but can be used to other data.
Here is the codex page: http://codex.wordpress.org/Function_Reference/wp_localize_script

Parse XML with JavaScript?

So, I would like to know how to parse an xml document with JavaScript.
I've got it working in php (view below)
<?php
$xmlGmailFeed = file_get_contents("https://gmail_username:gmail_password#mail.google.com/mail/feed/atom/");
$unreadMessages = $xmlGmailFeed->fullcount;
echo $unreadMessages;
?>
But the only thing with this, is that it's running using the server's IP address and doesnt let users login to their gmail. It pops up saying that there was a suspicious login attempt on their account. So what Id like to know is how I would be able to do the same thing, but run it from the hosts computer. I was thinking javascript to do it? But please let me know if theres a better way!
Edit:
Heres the code that im using..
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script>
$.ajax({
type: "GET",
url: "https://mail.google.com/mail/feed/atom.",
dataType: "xml",
crossDomain: true,
success: parseXml
});
function parseXml(xml)
{
var results = $(xml).find("fullcount").text();
alert(results);
}
</script>
Here's a screen shot of my problem:
http://cbog.co.nr/SC.php?img=Admin/AE0BCBAA4F532BC69A932E5DDD8F14F2
and you can see for yourself, live at:
http://cbogausch.com/test.php
I believe you can just use a DOMParser. jQuery also offers .parseXML() if you're willing to use it.

Categories