I'm trying to send an AJAX request to a page to interpret some data, and if it complies with what i'm looking for, send another AJAX request back. Right now I can see the first request is being made, but I'm not getting one back
//message.php
<head>
<script>
function org_name(str){
alert(str); //this alert appears, so I know the data is being received by this function
$.get("common_functions.php", { group_name: str} );
}
</script>
</head>
Then, on common_functions.php I have a similar request back, however, I'm not sure exactly what the issue is. The alert box doesn't even appear so I'm confused as to why the console would say the request was sent
//common_functions.php
if(isset($_GET['group_name'])){
?>
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
alert('common_functions'); //this does not appear
$.get("message.php", { name: "test"} );
</script>
<?
}
When I open up the javascript console in chrome I see the request sent form message to common_functions, but apparently the request on common_functions isn't sending one back
//text from javascript console
Request URL:http://localhost/message/common_functions.php?group_name=test
Request Method:GET
Status Code:200 OK
Does anyone see something obvious that I'm doing wrong or missing? If it makes a difference, common_functions is included in message.php because I do use some other functions from that page for my php.
You have to do something with your data. Right now, you're making an AJAX call, and doing nothing with your data.
So something like the following would work:
$.ajax({
url: "common_functions.php",
data: { group_name: str },
type: "GET",
success: function (data) {
$(data).appendTo("head");
}
});
Use $.ajax if you want control over execution states:
$.ajax({
type: "POST",
url: "common_functions.php",
data: { name: "test"},
success: function(r)
{
// user r as output
},
error: function(xhr, ajaxOptions, thrownError)
{
// error report
alert(xhr.responseText);
}
});
In this case you can see if execution was successful or if error occurred.
Also you can use firebug add-on for firefox or chrome to detect if response was sent. There is also an excellent tool called Fidler, which can give you much better overview over request/response states.
Here is an excellent tutorial for ajax debugging.
$.get will strip out <script> tags. You can use another jQuery AJAX method load() that won't, or use $.getScript. If you need content and script you can do both by making an ajax request for the content, and in the success callback of that ajax, call for the script with $.getScript
load() replaces all the content in the specified selector
$('#myDiv').load('common_functions.php', { name: "test"})
Will take all the content of the php output and replace all the contents of #myDiv but will also run the scripts
you may use a library that does that for you automatically, using http://phery-php-ajax.net
in your case, it would be
function messages($data){
$r = new PheryResponse;
// return your messages
return $r->json($messages);
}
function common($data){
$r = new PheryResponse;
switch ($data['group_name']){
case 'messages':
$r
->include_script(array(
'jquery' => 'http://code.jquery.com/jquery-1.8.2.js'
))
->phery_remote('messages'); // load your messages
break;
}
return $r;
}
Phery::instance()->set(array(
'common' => 'common',
'messages' => 'messages'
))->process();
on your page load
$(function(){
phery.remote('common', {'group_name': 'messages'});
});
you don't have to do anything else. btw, if you are including jQuery AFTER you are using $.get(), it won't work, obviously
Related
I'm trying to make an async call to the same page but for some reason, the async call is not being made and hence getting "userinfo" undefined error! could someone please tell me what I'm doing wrong in this thank you!
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$( document ).ready(function() {
//getting location of the user and assigning it to the variable
$.get("http://ipinfo.io", function (response) {
var usercity=response.city;
console.log(usercity);
$.ajax({
//no need to provide url since we are making async call on the same page
type: "post",
data: {cityinfo:usercity},
});
}, "jsonp");
});
</script>
<?php
session_start();
$usercity=$_POST['cityinfo'];
echo $usercity;
?>
First, you make a regular request to the PHP page. $_POST['cityinfo'] is undefined at this stage because you don't set it. The page includes an error message telling you that.
Second, you make a JSONP request to ipinfo.io, and call a callback function when you get a response.
Third, you make a second HTTP request to the PHP page. This time you do define $_POST['cityinfo']. You have no success handler to do anything at all with the response so, although $_POST['cityinfo']; is set, you don't see any effect of that (unless you were to use the developer tools Network tab to examine the response itself).
It is important to note that this is a second, distinct request to the same URL. The JavaScript does not travel back through time and set the $_POST['cityinfo']; variable in the previous request (and it is the response to the previous request that is still displayed in the browser window).
I implement chrome extension and i used jquery $.ajax to get data from the server side by json, but the response returned with additional javascript code and this made the error always fired instead of the success although the response returned the json i sent from the server side.
the ajax call:
$.ajax({
url:'http://www.domain.com/ajax/getTags',
data:{'cookie':cookie_value},
type:'get',
dataType:'json',
beforeSend:function(){
},
success:function(data){
},
error:function(xhr, status, error){
alert(xhr.responseText);
}
});
and the response is :
{"status":"error","msg":"<span class='error_msg alert'>Please complete the missing fields.<\/span>"}
<script type="text/javascript">
var uid = '3887';
var wid = '4102';
</script>
<script type="text/javascript" src="http://cdn.popcash.net/pop.js"></script>
the first line is the actual data sent by the server and all the next lines is additional data i don't know from where it came.
I used PHP in the server side and this is the script that return the json data
$json['status'] = 'error';
$json['msg'] = "<span class='error_msg alert'>Please complete the missing fields.</span>";
echo json_encode($json);
What's wrong? and how can i solve it ?
The server side page you are calling is returning Content-Type:text/html. You can start by setting this to return application/json in the PHP script.
<?PHP
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);
The JS scripts in the body looks suspect (especially given that you don't recognise this script), have you observed this script on all page calls. It looks like some kind of ad content delivery. Does the server you are hosting on belong to you? If so have you swept if for adware/malware?
In this script, using php's return will not work, whereas echo will. Thing is, if I use echo, and someone where to access the page directly, they would be able to see the output without the formatting.
<script type="text/javascript">
$(function() {
$('.callAppend').click(function() {
$.ajax({
type: 'GET',
url: 'recent.php',
dataType:'HTML',
cache:false,
success: function(data){
console.log(data);
//}
},
});
return false;
});
});
</script>
This the php script
<?php
$feedback = 'Hello this is the php page';
return $feedback; //Use echo, and all works fine.
?>
return is used for returning a value from a function to another piece of PHP code.
jQuery is not part of the execution of the PHP code on the server, so it has no idea what is really going on server side. jQuery is waiting for the rendered server response, which is what echo provides.
This SO answer provides a solution to only allow an AJAX script to be called by that type of request:
Prevent Direct Access To File Called By ajax Function
Even though it is checking for 'XMLHttpRequest', someone could make this type of request from something else other than you weboage.
When you use AJAX to load a URL, you're loading the raw output of that URL. Echo produces output but return doesn't. You'll need to do some reason on the subject of OOP to understand what the purpose of return is.
Echo is the correct way to send output.
I'd like to have a form on a HTML page not refresh when it's sent, which I've done, but I'd also like to allow the echo command in the PHP file to be able to call JavaScript from within the HTML file.
So far, all the echo commands aren't being carried out, which isn't what I expected.
Here's some code from the HTML and PHP files:
HTML:
<script type="text/javascript">
function functionInFile() {
alert("recieved");
}
$(function() {
$(".postform").submit(function() {
var content = $(this).serialize();
$.post('signup.php?', content);
return false;
});
});
</script>
and the PHP:
echo '<script type=\'text/javascript\'>functionInFile()</script>';
So basically, I'd like the PHP file to be able to invoke a function in the HTML file, while not being redirected when I click submit.
Any help appreciated.
You can use the success callback of the $.post() to execute a function which your PHP passes back. Try this:
PHP
// do some stuff with the posted data
echo 'functionInFile'; // name of js function to execute in calling page
jQuery
function functionInFile() {
alert("recieved");
}
$(function() {
$(".postform").submit(function() {
$.post(
'signup.php?',
$(this).serialize(),
function(func) {
window[func]();
},
'text'
);
return false;
});
});
It could be better to use the callback function of post
jQuery.post( url [, data] [, success(data, textStatus, jqXHR)] [,
dataType] )
So you would execute what ever code is within the reply or pre determined login onsusccess
$.post( 'signup.php?', content,
function( data ) {
//data contains the reply of the post so you can
//exec the code like this using JavaScript
//altogether eval is frowned upon because it is high overhead and opens
//opens up to code injection or whatever
//eval(data);
//so you just execute whatever method you need
functionInFile();
//or you reply from server in json and converto tobject
//reply: {'executeFunction': true}
var obj = jQuery.parseJSON(data);
if (data.executeFunction == true) { functionInFile(); }
}
);
ParseJSON
In order for PHP echo to work. the page MUST reload baecause it is server side.
A webpage cycle is SERVER SIDE, then Client side.
[SERVER] -> [CLIENT -> AJAX to SERVER -> SERVER REPLY ATTACH]
It looks like you're sending the right <script> tag. XHR return values are treated as data though, not executable code. Luckily for you, jQuery has code to check if you insert a <script> tag into the dom and execute it. You should be able to just do:
$.post('signup.php?', content, function(html) {$(document).append(html);});
and your script will execute.
(I would recommend making this happen in a different way though. I've worked on Apps that send large portions of javascript back in AJAX calls, and it's a pain to debug. It would be much better to send back a JSON object with a string for the next action, then keep an object of "approved" actions as a string -> function lookup table.)
I am using a simple ajax loader to get content on wordpress.
$("#page_preview").load("ajaxloader/", function(response, status, xhr) {
if (status == "error") {
alert("Sorry but there was an error");
}
else
{
$('#page_preview').fadeIn(300);
}
});
return;
When I load a specific post that has a google map embedded, obviously something goes wrong BUT instead of going inside the if statement, the firebug shows that it goes beyond this code. Neither if or else hit.
Using the eclipse debugger I found that the page load successfully, but when it returns the data to the .load() method, the last breaks.
Any ideas on what might going on?
How
<script>
// as of jQuery 1.5.x ++
var pagePreview = $("#page_preview");
$.get("ajaxloader/").success(
function(response, status, jqXhr) {
alert("Success!");
pagePreview.empty();
pagePreview.append(response);
// i feel you need to parse the response for the google map div, and perform another $.get() of the google url?
}).error(function(response, status, jqXhr) {
alert("These are not the droids you are looking for. move along.");
}).complete(function(response, status, jqXhr) {
alert("Complete!");
});
</script>
#Why
jQuery.load() will get you on the documentation. .load is equivalent to this
It is roughly equivalent to $.get(url, data, success) except that it
is a method rather than global function and it has an implicit
callback function. When a successful response is detected (i.e. when
textStatus is "success" or "notmodified"), .load() sets the HTML
contents of the matched element to the returned data.
You need to register in $.ajax( complete:function(responseText, textStatus, XMLHttpRequest)){}); and check the textStatus value. if ok, then load the data into the destination $('selector') yourself. Or fix the .load() by watching your network xmlHttpRequests in chrome (ctrl + shift +j) or some network tab in firebug and debug the issue with your 'url' value in $('selector').load( 'url', function(response, status, xhr){})
A simple way to debug this is to look at the XHR requests with the firebug console tab. There might be a problem with the request URL and you might not get any data back, or maybe you get an error or something. With firebug you could easily see what the server returns.
Since .load only load on success, you could add a
console.debug("In .load function");
at the begging of the function. Again, checking with firebug you could find out if the .load callback is actually fired.
use $.ajax function
eg
$.ajax({
url: "test.html",
context: document.body,
success: function(){
//when Successfully executed
},
error: function(){
//When Error Fires
}
});