I have script using smarty engine.
I just tried to use ajax post to get some data from page.
The javascript function as following:
function getTime(val,id) {
$.ajax({
type: "POST",
url: '{$GLOBALS.site_url}/check_time/',
data:'GetDate='+val + '&Jobid='+id,
success: function(data){
alert(data);
}
});
}
the alert show me (3 small squares) I don't know what dose mean !
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.
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.
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.
The http request sent to some 'request_url' returns json response in format {'succes': 1, 'html': 'thestuff'}
so when
jQuery.ajax({
url: 'request_url',
success: function(response){
alert(response.html); //'thestuff' is here as expected
}
});
'thestuff' can be found in response.html as expected. But if this ajax is called inside the 'success' callback of another one ajax request then the response.html is coming empty and 'thestuff' is going to 'response'.
jQuery.ajax({
url: 'some_other_url',
success: function(some_other_response){
jQuery.ajax({
url: 'request_url',
success: function(respose){
alert(response.html); //there is nothing
alert(response); //I see 'thestuff' which is expected in 'html'
}
})
}
});
Why does it happen?
Update: 'thestuff' contains some js code with {} I can suppose something can get confused but why it works well with single (not nested) ajax request.
Not enough reputation to comment so adding as an answer
Here is expanding on charlietfl comment of using dataType.
I made it work using dataType="json". Json has to be strictly formatted though as per jQuery documentation.
jQuery.ajax({
url: 'some_other_url',
success: function(some_other_response){
jQuery.ajax({
url: 'request_url',
dataType:"json",
success: function(response){
alert(response.status); //there is nothing
alert(response); //I see 'thestuff' which is expected in 'html'
}
})
}
});
request_url should return something like this (note, quotes should be used instead of apostrophes)
{"status":"s","html":"some stuff"}
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)
}
});
}