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
Related
I've been trying to call a VB.NET function from JavaScript for the website I've been working on, and found out about AJAX and started trying to use it.
(For reference, my target framework is 4.6.1.)
The following is a snippet of my VB.NET code, where PopulateDetailSection() is something which returns a string which is supposed to be the text from the div, but my breakpoint never hits this function.
System.Web.Services.WebMethod(EnableSession:=True, BufferResponse:=False)
Protected Shared Function PopulateDetail() As HtmlGenericControl
Return PopulateDetailSection()
End Function
and as for the AJAX call:
jQuery.ajax({
url: "frmActiveTrackingG.aspx/PopulateDetail",
type: "GET",
//contentType: "application/json: charset=utf-8",
dataType:"html",
success: function (data) {
alert(data);
}
});
I've tried alerting several things, but it keeps returning undefined unless I alert data which appears to return the aspx file starting with the header.
I usually don't ask questions here, but I'm truly stumped on this.
There some issues with your JavaScript. As described here: https://stackoverflow.com/a/5332290/428010 you need to post on the web page/method.
jQuery.ajax({
url: "frmActiveTrackingG.aspx/PopulateDetail",
type: "POST",
contentType: "application/json: charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
}
});
On the VB side the method need to be public not protected.
So I am using ajax to post a serialised form to a php script and then on success alert the returned data.
My code works fine on my local environment, but uploaded, the eval() function mucks everything up.
here is my code:
function post_that_shit(formIdToSerialize, postUrl) {
var serializedData = $("#"+formIdToSerialize).serialize();
var post_url = postUrl+".php";
//alert(serializedData + "\n" + post_url);
$.ajax({
url: post_url,
type: "POST",
data: serializedData,
success: function(data){
data = eval('('+data+')' );
console.log(data.msg);
if(data.reload == 'yes'){
window.location.reload();
}
if(data.relocate != 'no'){
window.location.href = data.relocate;
//alert(data.relocate);
}
if(data.msg != 'no'){
$(".message").html(data.msg);
//alert(data.msg);
}
//alert('relocate: '+data.relocate);
}
});
}
So it is pretty simple.
The php echo out a json encoded array like so:
echo json_encode(array('msg' => $errors, 'relocate' => 'no'));
And depending on what is echoed, the msg is displayed or the user relocated.
Why do I get the error of SyntaxError: Unexpected token ')' when I use the code online?
Locally it works just fine :(
Thanx for your help
Chris
You don't need to use eval(). Just set the dataType option to 'json' and the data will be internally parsed to an object by jQuery
$.ajax({
url: post_url,
type: "POST",
dataType:'json',
data: serializedData,
success: function(data){
console.log(typeof data); // returns "object"
In addition setting the proper content type header for application/json at server also helps
I don't know why you need the eval() function in that place. It's a wrong coding. Your solution is put the data type to JSON and the ajax function treats automatically as a json:
$.ajax({
url: post_url,
type: "POST",
dataType: 'json',
data: serializedData,
success: function(data){
console.log(data.msg);
if(data.reload == 'yes'){
window.location.reload();
}
if(data.relocate != 'no'){
window.location.href = data.relocate;
//alert(data.relocate);
}
if(data.msg != 'no'){
$(".message").html(data.msg);
//alert(data.msg);
}
//alert('relocate: '+data.relocate);
}
});
First of all, eval is evil. Don't use it... never ever! It's like a bomb ready to detonate.
Secondly, parsing json can be done natively in Javascript. No need for eval.
You can use JSON.parse and it will return you an object parsed by the string containing the json text.
eval is used to evaluate code, in other words, it is executing javascript not json. When eval returns an object, it is simply a side effect of JSON being a subset of JavaScript. In other words, any string formatted as json can be evaluated to JavaScript. But JavaScript cannot be formatted to JSON. There is no representation of Date, Function and many more complex objects. That said, when using eval, you're actually executing JavaScript and that is the big problem here. It could execute potentially dangerous code while parsing JSON simply requires parsing data into a data structure and nothing more.
Here more about JSON: https://fr.wikipedia.org/wiki/JavaScript_Object_Notation
So it would allow anyone to add somewhat some javascript that would then get executed by your use of eval. It could allow someone to execute code on the browser of other users. It could be used to steal passwords for example or steal any kind of private information that wouldn't be accessible otherwise.
jQuery on the other hand allow you to parse json natively by using the dataType attribute as 'json'. Like this:
$.ajax({
url: post_url,
type: "POST",
dataType: 'json',
data: serializedData,
success: function(data){
console.log(data.msg);
Or using JSON.parse
$.ajax({
url: post_url,
type: "POST",
data: serializedData,
success: function(data){
data = JSON.parse(data)
console.log(data.msg);
Also as charlie pointed out, parsing by ourselves JSON means that we have to wrap it in a try catch, because parsing might fail if the json isn't valid.
But using jQuery gives us a way to handle that easily.
You could rewrite your code such as this:
var req = $.ajax({
url: post_url,
type: "POST",
dataType: 'json',
data: serializedDate
});
req.done(function (data) {
// Success
});
req.fail(function () {
// Error something went wrong
});
The advantage of using the promise form is that you can chain calls to have clean async code instead of the callback hell and infinite function nesting.
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)
}
});
}
I'm trying to get ajax to work in JSBIN like demonstrated in this video. What have I don't wrong. Seems like it ought to work!
$(document).ready(function(){
$.ajax({
type: "get",
url: "http://jsbin.com/ipefom/1/js",
dataType: "json",
success: function(returnedData){
console.log(returnedData)
}
});
});
http://jsbin.com/ocerag/3/edit
I don't understand where my parseerror comes from.
Your json is invalid:-
There is as edit:8 in json which is misplaced and also you have duplicate keys while the number is repeated again. Seems like the same set was copy pasted again.
"968":"a","969":"a","970":"a","971":"a","972":"a","973":"a","974":"a","975":"a","976":"a","977":"a","978":"a","979":"a","980":"a","981":"a","982":"a","983":"a","984":"a","985":"a","986":"a","987":"a","988":"a","989":"a","990":"a","991":"a","992":"a","993":"a","994":"a","995":"a","996":"a","997":"a","998":"a","999":"a"} edit:8
{"0":"a","1":"a","2":"a","3":"a","4":"a","5":"a","6":"a","7":"a","8":"a","9":"a","10":"a","11":"a","12":"a","13":"a","14":"a","15":"a","16":"a","17":"a","18":"a","19":"a","20":"a","21":"a","2
Because it is not returning valid json, when you try
dataType: "html", in place of dataType: "json", then it will show that the returning is not a valid json.
So I am trying to do a post using jQuery.ajax instead of an html form. Here is my code:
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/$org_ID',
data: data,
success: function(data){
$('#data_box').html(data);
}
});
Here is my problem:
When this was in an html form, the $org_ID that was part of the URL would actually pull the variable and send it as part of the URL. Now that this is in jquery, its just sending $org_ID as text. How can I get this to figure out what the variable, $org_ID is? I tried declaring it in the javascript but I am brand new to jquery/javascript and don't really know what i'm doing.
Thanks!
Are you rendering this in PHP? In that case you need to do:
url: '/groups/dissolve/<?php print $org_ID; ?>'
Otherwise, you need to do something like
var org_id = 'foo';
// or
var org_id = '<?php print $org_id ?>';
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/'+org_ID,
data: data,
success: function(data){
$('#data_box').html(data);
}
});
Unlike PHP, you can't interpolate variables in javascript, you have to concatenate them with the string.
If you're trying to POST a variable (org_id) then you should put it in data:
data['org_id'] = org_id;
$.ajax({
type: 'POST', // GET is available if we prefer
url: '/groups/dissolve/',
data: data,
success: function(data){
$('#data_box').html(data);
}
});
While you can concatenate params onto your url to send them in an HTTP request, putting them in a data object not only lets jQuery do more work for you & escape HTML entities etc (and keep your code cleaner), but also allows you to easily debug and play around with ajax() settings.
It's not clear in the question where your data comes from, but you can use something like:
url: '/groups/dissolve/'+orgId,
or:
url: '/groups/dissolve/?orgId='+orgId,
Short answer, concatinate
url: '/groups/dissolve/' + $org_ID