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)
}
});
}
Related
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
I need to send ajax post on ajax posted page.
index.php has
$.ajax({ type: "POST",datatype:"json", url: "/notification.php",
data: "kime=karaakce&tur=konuyayorum&postid=2020",
success: function(html){
}
});
notification.php has same function but posts to track.php
$.ajax({ type: "POST",datatype:"json", url: "/track.php",
data: "kime=karaakce&tur=konuyayorum&postid=2020",
success: function(html){
}
});
However, notification.php doesnt send the ajax post. How can I make it run ?
First thing you cannot run the jquery code even if you include it in your notification.php file. That is because jquery runs only in browser, not at backend. So unless you "physically" open the notification.php page in browser the jquery won't run.
So to address your issue you'll have to chain the success response from one php file to next.
eg:
Data from index.php ---> notification.php ---> index.php ---> track.php
(Although a very crude approach)
Here is the code that can achieve this.
index.php file
$.ajax({
type: "POST",
datatype:"json",
url: "/notification.php",
data: {
kime=karaakce,
tur=konuyayorum,
postid=2020
}
success: function(responseData){
$.ajax({
type: "POST",
datatype:"json",
url: "/track.php",
data: {
kime=karaakce,
tur=konuyayorum,
postid=2020
}
success: function(html){
// This is your final success
}
});
}
});
Your notification.php file should return a JSON data which you can use to send it to the next request. It will come in 'responseData' object.
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
I need to load a dynamic created javascript with PHP. Is there any good solution to load javascript creating by PHP after some ajax requests finished?
Thx in regards, i am searching for 2h in stackoverflow.
if i call .ajax function where html/js respone, jquery kills the js ;/
jQuery.ajax({
type: 'POST',
dataType: 'html',
url: $url,
success: function(result)
{
result // html
jQuery.ajax({
type: 'GET',
dataType: 'script',
url: $url,
success: function(result)
{
//the result is js and is availble in browser if you return
//a function you can execute this now
}
});
}
});
Hope someone find his answer here :) gl & hf & nice day
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.