Pass javascript variable to php in same file - javascript

Is it possible to pass a javascript variable to php code in the same file?
For example I did this, in my example.php:
JS
$.ajax({
url: 'example.php',
type: 'POST',
data: {var: 12345},
success: function(data) {
console.log("success");
}
});
PHP
$var = $_POST['var'];
echo $var;
But it doesn't work. Any solutions?

$.ajax({
url: 'example.php',
type: 'POST',
data: {var: 12345},
success: function(data) {
console.log("success");
}
});
Your AJAX request expect a response (you assigned it to data variable).
You should elaborate more the value returned by your PHP script, like console.log(data) to see what it is returning.
Your PHP file can't write it directly to your html file, because it is a server-side operation and your page is already loaded. I think you should add some request-type logic in you PHP too if you want to have HTML file rendering and Javascript AJAX requests both in the same file.
A solution could be to catch the AJAX[POST] request in PHP code and return some HTML or String values to attach in HTML like $(body).append(data);
Here you can learn more: https://www.w3schools.com/php/php_ajax_php.asp

Related

Accessing PHP variable as URL in JQuery Ajax request

I am experiencing some problems with having the Ajax request function/method in JQuery recognizing a PHP-variable from outside the script code. What I am trying to do is using the variable $live_update_url as the url-argument in the Ajax code. The code below is not working, but if I hard code the value of the url there are no problems. So it should be the variable itself that is not accessed. What am I doing wrong here?
function ajaxd() {
$.ajax({
url: <?php print($live_update_url);?>,
type: "get",
data: {live_time: 'value'},
dataType: "json",
success: function(data){
$('#local_time').html(data.live_time);
}
});
It looks like you are missing the quotes around the URL value in your JSON.
Make sure that the value returned by the $live_update_url includes quotes or try this:
function ajaxd() {
$.ajax({
url: "<?php print($live_update_url);?>",
type: "get",
data: {live_time: 'value'},
dataType: "json",
success: function(data){
$('#local_time').html(data.live_time);
}
});
Found a solution:
Used the following definition of $live_update_url in the PHP code:
$live_update_url = "'http://localhost/projectName/api/time.php?g_id=".$g_id."'";
This string already includes single quotes within the double quotes. Then I used the echo <<<_END-construct and just added the following line in the Ajax request:
url: $live_update_url

Extract Json response

I am trying to to extract a Json response in jquery sent from a php file.
This is the .js code:
$.ajax({
url: 'index.php?page=register', //This is the current doc
type: 'POST',
datatype: 'json',
data: {'userCheck': username},
success: function(data){
// Check if username is available or not
},
error: function(){
alert('Much wrong, such sad');
}
});
This is the response from the php file:
if($sth->fetchColumn()!=0){
//$response = array("taken");
$response = array("username"=>"taken");
echo json_encode($response);
//echo '{"username':'taken"}';
}else{
//$response = array("available");
$response = array("username"=>"available");
echo json_encode($response);
//echo '{"username":"available"}';
}
I have tried all combinations I can think of in both files, but nothing seems to work. It is a simple check for a username in the database. If I console log the data I get from the response, I get this:
{"username":"available"}<!DOCTYPE html>
// The rest of the page html
So the info is there, but how do I access it? I have tried several syntaxes found around the internet, but no luck so far. I seem to recall that a json response only can contain valid json, so is the problem the html? I don't think I can avoid this due to the structure of my application, so hopefully it is possible to access the json with my present structure.
in you Ajax
EDIT:
change
datatype:"json",
the case of parameter name was not respected, the t must be T
dataType:"json",
now retry please
$.ajax
({
url: 'index.php?page=register', //This is the current doc
type: 'POST',
dataType: 'json',
data: {'userCheck': username},
success: function(data)
{
// Check if username is available or not
switch(data.username)
{
case "available":
// do you want
break;
case "taken":
// do you want
break;
}
},
error: function()
{
alert('Much wrong, such sad');
}
});
in PHP
simply that, and don't forget to exit; to avoid include html page in your json response !
This is the code coming after the }".... who break your json output
and make it unreadable by javascript (worste, it simply break your javascript !)
echo json_encode(["username"=> ($sth->fetchColumn()!=0) ? "taken":"available"]);
exit;
When you're responding to an AJAX call, you should just return the JSON response, not the HTML of the page. Add:
exit();
after this code so you don't display the HTML after the JSON.
In the JS code, use if (data.username == 'available') to tell whether the username is available.
The other problem in your code is that you have a typo here:
datatype: 'json',
It should be dataType, with an uppercase T.
You can also put:
header("Content-type: application/json");
before echoing the JSON in the script, and jQuery will automatically parse the response.
Also you can set request headers in your jQuery ajax call beforeSend function like follows
beforeSend: function (xhr) {
xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
xhr.setRequestHeader('Accept', 'application/json');
}
So you're strictly declaring the data type to be json

Best practice for using php file with AJAX

I'm beginning web development with php and am testing jQuery ajax calls to a php file to run functions. But I've noticed that the php file loads into the resources each time I call it with an AJAX POST method. What is the best solution to prevent this occurrence? Also, are there better coding practices to use when performing multiple function calls (what I'm used to calling web services or web methods in the c# world) from a single file in php?
test.php
<?php
if($_POST['action']=='test'){
$arr = array(
'stack'=>'overflow',
'key'=>'value'
);
echo json_encode($arr);
}
?>
scripts.js
function postTest(){
var data = {
action: 'test'
};
$.ajax({
type: "POST",
url: "test.php",
dataType: 'json',
data: data,
success: function(result){
console.log(result)
}
});
}
Update:
I changed my code to use the data variable as an object in the ajax call.
The original question still stands however. How do I use a function inside a php file without it being loaded into the site resources in the browser for each ajax call?
Thank you.
If you're noticing that the php block is never getting executed, then you're passing in the data wrong. Try this:
function postTest(){
var data = {
'action': 'test'
};
$.ajax({
type: "POST",
url: "test.php",
dataType: 'json',
data: data,
success: function(result){
console.log(result)
}
});
}
JSON.stringify is not working in your favor, here.
To demonstrate this, you could put print_r($_POST) in your php script and see what console.log(result) gives you.
To remedy this, you can simply put your data in the $.ajax() block:
function postTest(){
$.ajax({
type: "POST",
url: "test.php",
dataType: 'json',
data: {
action: 'test'
},
success: function(result){
console.log(result)
}
});
}

Posting JSON string to PHP page

Okay, I'm having some suicidal issues posting a JSON string to a PHP page. I have literally been through the top ten results on Google and plenty of SO questions related to my problem, but still can't work out what I'm doing wrong.
I have multiple forms on a page and want to collect all form fields, turn them into a JSON string and post them to a PHP page, where a script iterates each item and updates the relevant database tables.
This is my jQuery/JS script to collect the data from all the forms:
var photo_annotations = {};
$('form').each(function(i) {
var id = $(this).attr('id');
photo_annotations[id] = {
caption: $('#'+id+'_caption').val(),
keywords: $('#'+id+'_keywords').val(),
credit: $('#'+id+'_credit').val(),
credit_url: $('#'+id+'_credit_url').val()
};
});
If I console.log my photo_annotations object, this is what is produced, based on a two form example:
({11:{caption:"Caption for first photo.", keywords:"Keyword1,
Keyword2, Keyword3", credit:"Joe Bloggs",
credit_url:"www.a-domain.com"}, 12:{caption:"Caption for Lady Gaga.",
keywords:"Keyword3, Keyword4", credit:"John Doe",
credit_url:"www.another-domain.com"}})
I then need to POST this as a string/JSON to a PHP page, so I've done this:
$.ajax({
type: 'POST',
dataType: 'html',
url: 'ajax/save-annotations.php',
data: { data: JSON.stringify(photo_annotations) },
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data) {
$('#form_results').html(data);
} else {
alert("No data");
}
}
});
And on my PHP page, I've got this:
<?php
//print_r($_POST['data']);
$decoded = json_decode($_POST['data'],true);
print_r($decoded);
?>
Now, this isn't the only thing I've tried. I've tried to remove all the JSON settings from the AJAX script, in a bid to just send a pure string. I've tried removing contentType and JSON.stringify but still won't go. My PHP page just can't get the data that I'm sending.
Please help push me in the right direction. I've got to the point where I can't remember all the variations I've tried and this little script is now on day 2!
MANAGED TO FIX IT
I rewrote my AJAX function and it worked. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
Try:
$.ajax({
// ...
data: { data: JSON.stringify(photo_annotations) },
// ...
});
If you just set the "data" property to a string, then jQuery thinks you want to use it as the actual query string, and that clearly won't work when it's a blob of JSON. When you pass jQuery an object, as above, then it'll do the appropriate URL-encoding of the property names and values (your JSON blob) and create the query string for you. You should get a single "data" parameter at the server, and it's value will be the JSON string.
Try urldecode or rawurldecode as follows:
<?php
$decoded = json_decode(urldecode($_POST['data']), true);
print_r($decoded);
?>
I rewrote my AJAX function and it now works. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
The only thing I can think of is that the order of AJAX settings needed to be in a particular order. This is my old AJAX script which does not send POST data successfully - well it does send, but cannot be read!!
var the_obj = JSON.stringify(photo_annotations);
var data_str = "annotations="+the_obj;
$.ajax({
type: 'POST',
dataType: 'html',
data: data_str,
url: 'ajax/save-annotations.php',
success: function(data) {
$('#form_results').html(data);
}
});
in your ajax call try resetting the dataType to json
dataType: "json",
You wouldn't have to use the JSON.stringify() either. On your php script you won't have to decode [json_decode()] the data from the $_POST variable. The data will be easy readable by your php script.

Read Data from text file on server using $.ajax to call a php script

This is my first time posting on this site. I have looked over several of the previous postings related to this topic, but did not find anything that works for me. I am trying to use javascript and jquery $.ajax to call a php script on the server and return the contents of the file. Thus far I am not getting any data back. I am able to update the .txt file on the server using the $.ajax, but could use some help in finding out what I am doing wrong to retrieve it. I do not see any errors being generated from the php script and the events.txt file is not blank. vb.net and c# are my native languages so this is a bit foreign to me.
My js is:
function readText() {
var url = "readdata.php";
var result = "";
$.ajax({
url: url,
type: 'get',
dataType: 'text',
success: function (data) {
result = data;
alert(result);
},
async: false
});
}
and my readdata.php script is:
<?
$file=fopen("events.txt","r");
$read=fread($file,filesize("events.txt"));
fclose($file);
echo $read;
?>
Any advise is welcome. Thanks!
The type in $.ajax should be in capitals
type: 'GET'
function readText() {
var url = "readdata.php";
var result = "";
$.ajax({
url: url,
type: 'GET',
dataType: 'text',
success: function (data) {
result = data;
console.info(result);
},
async: false
});
}
After adding the error: function(){} to the ajax call, I was able to work through this issue.
It turned out that part of the issue was permissions on the server (not able to read from file in the file permissions on the server).
Also I was trying to run locally and I did not have php installed on my local machine.

Categories