I'm a web developper in a small company that decided to make its selling website in PHP5/Laravel 4.2 instead of Prestashop or anything else. The site is hosted by another company, and we don't have the liberty to make anything we'd want on the server.
I made 6 monthes ago a script in AJAX that let the user know without refreshing how high would his shipping fee and taxes cost. We're in Europe in the border of France and Switzerland, so it's really a necessity to have this script. It worked really great, until this week when I wanted to implement another script, and found out that this script didn't work anymore (for how long, I don't know).
The JS :
function shippingFee()
{
var idCountry, weight;
weight= document.getElementById('weight').value;
idCountry = document.getElementById("country").value;
$.post('ajax/shippingFee',
{idCountry: idCountry, weight: weight},
function(data){
obj = JSON.parse(data);
$('#fee).html(obj.fee);
$('#total').html(obj.total);
$('#sub').html(obj.sub);
$('#promo').html(obj.promo);
});
};
Here is my route :
Route::post('ajax/shippingFee', 'AjaxController#shippingFee');
Here's my function (not everything, just the final result) on the AjaxController:
public function shippingFee(){
//Test values, only for this example
$fee = 12;
$total = 24;
$sub = 3;
$promo = 0;
$res = ['fee'=>$fee, 'total'=>$total, 'sub'=>$sub, 'promo'=>$promo];
echo json_encode($res);
}
When I click on the button that activate the function, I have this error :
SyntaxError : unexpected token in json at position 0
And if I click on the source, I have my JSON :
{"fee": 12, "total":24, "sub":3, "promo":0}
Again, the code worked perfectly six monthes ago, and still works on localhost. Do you have any idea on what's happening ?
Thanks a lot.
specify the dataType in Post request, also check the response result in Developer tools that will give you clear idea. don't forget to call exit(0) method once you echo result that will fix the issue if you using any framework
PHP Exit method
Okay, I succeeded. I don't know why, but my json_encode wasn't sending a satisfying json. I tried to change the structure of my function with this :
function shippingFee()
{
var idCountry, weight;
weight= document.getElementById('weight').value;
idCountry = document.getElementById("country").value;
$.ajax({
url: "ajax/shippingFee",
type: "Post",
data: {'idCountry':idCountry, 'weight':weight},
traditional: true,
success: function (data) {
data = JSON.stringify(eval('('+data+')'));
var obj= JSON.parse(data);
$('#fee).html(obj.fee);
$('#total').html(obj.total);
$('#sub').html(obj.sub);
$('#promo').html(obj.promo);
}
});
};
Thus, with the data = JSON.stringify(eval('('+data+')')); I say that this is a JSON. And my code is working like a charm. I found this solution by watching this post : Convert object string to JSON
I tried to put the dataType:"JSON" before the success, but when I did it returned an error. With contentType:"application/json" I had an error 500.
Thanks to the people who answered me :)
Related
Please be patient. This is my first post as far as I remember.
This is a part of my calendar.js script. I'm trying to POST data that I fetch from modal window in index.php to sql.php.
function saveModal() { /*JQuery*/
var current_date_range = $(".modal-select#daterange").val();
var current_room_number = $("#mod-current-room-number").val();
var current_room_state = $("#mod-current-room-state").val();
var myData = {"post_date_range": current_date_range, "post_room_number": current_room_number, "post_room_state": current_room_state};
var myJSON = JSON.stringify(myData);
$.ajax({
type: "POST",
url: "sql.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
data: myJSON,
beforeSend: function() {
$("#ajax").html("<div class='loading'><img src='/images/loader.gif' alt='Loading...' /></div>");
},
success: function(result){
$("#ajax").empty();
$("#ajax").html(result);
$("#ajax").fadeIn("slow");
window.location.reload(true);
},
error: function(){
alert(myJSON);
$("#ajax").html("<p class='error'> <strong>Oops!</strong> Try that again in a few moments.</p>");
}
})
}
I get the data just fine (as you can see I have checked in the error: function() with alert(myJSON);). It looks like this: {"post_date_range":"12/19/2018 - 12/28/2018","post_room_number":"118","post_room_state":"3"}. Nevermind that the daterangepicker.js returns dates in the hideous MM/DD/YYYY format, which I would very much like to change to YYYY-MM-DD. The real problem is, the code never gets to success: function().
Now my sql.php is in the same folder as calendar.js and index.php.
In sql.php I try to retrieve those values with:
$currentDateRange = $_REQUEST['post_date_range'];
$currentRoomNumber = intval($_REQUEST['post_room_number']);
$currentRoomState = intval($_REQUEST['post_room_state']);
I have checked many other SO Q&As and none have helped me solve my problem. I don't see any spelling errors. It's not disobeying same origin policy rule. I don't want to use jQuery $.post function. Anyone sees the obvious solution?
You want to send array in post rather than the string so directly send myData to get array value in your PHP file rather converting to JSON string It would work with your current PHP file as you require.
You should specify a POST key for the JSON data string you are sending:
var myJSON = JSON.stringify(myData);
(...)
$.ajax({
(...)
data: 'data=' + myJSON,
You need to parse (decode) this string in your PHP file to be able to use it as an array/object again:
$data = json_decode($_REQUEST['data']);
$currentDateRange = $data['post_date_range'];
$currentRoomNumber = intval($data['post_room_number']);
$currentRoomState = intval($data['post_room_state']);
Also, dataType in jQuery.ajax function is specified as "The type of data that you're expecting back from the server." according to jQuery documentation. As far as I can tell from your code, you might rather expect something else as your response, so try excluding this line.
I am sorry to have burdened you all. It's my third week programming so my lack of knowledge is at fault.
I did not know how dataflow works between AJAX and PHP in the URL...
While I was searching for other errors, I printed or echoed out many different things. The PHP file should echo only 1 thing, although it can be an array with multiple values.
Like this for example:
$return_arr = array("sql"=>$sql1, "result"=>$result, "out"=>$out);
echo json_encode($return_arr);
I appologize again.
The question is about speeding up the loading of a ASP.NET web app, and I found that the loading time of the filtering feature of the web app is unacceptable. The filter list is generated from a database. Please see the following code:
This function is in .js and is invoking the webservice method.
function filterSetup() {
filterChanged = true;
var reset = true;
DDL_WebService.fillFilter(SucceededCallbackWithContext, FailedCallback,new ddlContext("My_Filter", reset));
filterSystemSetup();
}
This function is in .js too and is executed after the webservice method.
function SucceededCallbackWithContext(result, userContext) {
var ddl = $get(userContext.cntrl);
var curVal = userContext.getVal();
// Fetching result...
}
This function is one method in a web service file called "DDL_WebService.vb". It is in .vb and is getting the data from a database.
<WebMethod()> _
Public Function fillFilter() As List(Of String)
Dim strSQL As String
strSQL = "select '(All)' from My_Table "
Return getData(strSQL)
End Function
Problem: I thought after the last line of fillFilter(), it should go to SucceededCallbackWithContext()in almost no time (The step-into command tells me nothing happens in between too). However, getting to SucceededCallbackWithContext() from the last line of fillFilter() takes around 7 seconds.
I am not sure what is taking the time and how can I confirm and resolve that.
Any help is greatly appreciated :)
Updates:
Looking at the problem from another angle using Developer tool, I get the result shown in the sceenshot. Now my question becomes what are the possible reasons that some methods take too long to run (Note: For the webservice method with the longest request time, I speed up the query from 10 seconds to less than 3 seconds, but the request time is still arount 15 seconds). Could it be that the executing of one webservice method would affect the speed of another webservice method? Thanks again!
If you are going to filter data why you try to load all records with all columns?
If your my_table records is around 1000 or less than 1000(I mean you have a small data set) you can not understand performance issue but after a while as your data grow(for example it reaches up to 100000) you notice that your service is getting slower and slower.
If you query is not your main query in code so first use browsers developer tools or any other tools to measure response time of your service to be sure that problem is in your server side codes or in your javascript codes
Try to compress your datataTable before sending it !I share with you two functions thaallow the compression and decompression :
Public Shared Function CompressData(ByVal ds As DataSet) As Byte()
Try
Dim data As Byte()
Dim memStream As New MemoryStream()
Dim zipStream As GZipStream = New GZipStream(memStream, CompressionMode.Compress)
ds.WriteXml(zipStream, XmlWriteMode.WriteSchema)
zipStream.Close()
data = memStream.ToArray()
memStream.Close()
Return data
Catch ex As Exception
Return Nothing
End Try
End Function
Public Shared Function DecompressData(ByVal data As Byte()) As DataSet
Try
Dim memStream As New MemoryStream(data)
Dim unzipStream As New GZipStream(memStream, CompressionMode.Decompress)
Dim objDataSet As New DataSet()
objDataSet.ReadXml(unzipStream, XmlReadMode.ReadSchema)
unzipStream.Close()
memStream.Close()
Return objDataSet
Catch ex As Exception
Return Nothing
End Try
End Function
Hope help you.
Although it has been a long time since I posted the question, I still want to update my progress on this problem just to thanks Beldi and mostafa for the suggestions and to give people some hints when having similar issues.
Overall the problem has not been resolve but we came up with a workaround.
We were guessing that some queries might take a long time to finish, so I carved out all the queries that take a long time according to the developer tool. I tested them one by one and found that they are all pretty fast. In the next quite a bit of time, I was stuck on verifying what the developer tool indicates.
One breakthrough happens when I dissect the following code:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "dataservice/getSimData_WebService.asmx/getSimsList",
data: JSON.stringify(params),
dataType: "json",
success: function (data, textStatus) {
if (textStatus == "success") {
var thegrid = $("#jqGrid_sims")[0];
thegrid.addJSONData(data.d);
}
},
error: function (data, textStatus) {
alert("Error from get grid data");
}
});
In this piece of ajax call, the code sends out the request upon executing. The time between the beginning of the execution and the beginning of the if statement is requesting time, and that is the time the developer tool indicates.The time that code inside if statement spends is the fetching time.
After looking into the requesting time and the fetching time for each ajax call, I found the fetching time for a simulation functionality takes a relatively significant amount of time. Since loading the functionality would cause the page to be frozen and trying to reduce the frozen time has more uncertainties and takes longer, we finally decide to not load it initially. Instead, it will load once a user clicks on a button.
Hope this would help anyone who has similar problems.
I know this question has been asked before several times on this forum, but I think I am missing something. Or maybe it is because I don't know JSON/AJAX that well.
Here is the thing.
I got some javascript/JQuery code on a page, say on index.php, (not yet in a seperate JS file) which let you put any number in an array from 1 to 10. If it's already in it, it will be removed if clicked again.
Now I want to pass that JS array to PHP, so I can create tables with it.
Here's what I have done.
$(".Go").click(function() {
var enc = JSON.stringify(tableChoice);
$.ajax({
method: 'POST',
url: 'calc.php',
data: {
elements: enc
},
success: function(data) {
console.log(enc);
}
});
});
And in my calc.php I got this to get the values to PHP.
<?php
$data = json_decode($_POST['elements'],true);
echo $data;
?>
Now here comes the noob question:
If I click my (.Go) button, what really happens?
Because the console.log let's me see the correct values, but how do I access it? The page (index.php) doesn't automatically go to the calc.php.
When I use a <form> tag it will take me there, but it shows this error:
Undefined index: elements
I am sure I am looking at this the wrong way, interpreting it wrong.
Can someone please help me understand what it is I should be doing to continue with the JS array in PHP.
With a XHR request you don't do a page reload. With your $.ajax method you post data to the server and receive information back. Since you can see information in your console, the success method is triggered.
You might want to take a look at your DevTools in for example Chrome. When you open your Network tab and filter on XHR you see what happens. You can inspect your XHR further by looking into the data you've send and received.
So my question to you is: what do you want to happen onSuccess()? What should happen with the data you receive from your backend?
In JavaScript:
$(".Go").click(function() {
var enc = JSON.stringify(tableChoice);
$.ajax({
method: 'POST',
url: 'calc.php',
data: {
"elements="+enc;
},
success: function(data) {
console.log(data);// You can use the value of data to anywhere.
}
});
});
In PHP:
<?php
if(isSet($_POST[elements]))
{
$data = json_decode($_POST['elements'],true);
echo $data;
}
else
{
echo "Elements not set";
}
?>
I have the following Ajax call:
$.ajax({
type: 'POST',
url: myBaseUrl + 'Products/addItemToBasket',
dataType: 'json',
data: {
id: window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1),
amount: amount
},
success: function (data) {
alert(data);
var dat = JSON.parse(data);
}
}
});
Now this calls the following method in php:
public function addItemToBasket()
{
if ($this->request->is('post')) {
//todo delete efter at have insat fancybox med valg af antal styk. (sendes via ajax).
$shopping = null;
$item = $this->Product->find('first',array('conditions' => array('Product.id' =>$this->request->data['id'])));
if(isset($_SESSION['basket'])){
$shopping = $_SESSION['basket'];
}else{
$shopping = array();
}
array_push($shopping,$item);
$_SESSION['basket'] = $shopping;
echo json_encode($_SESSION['basket']);
}
}
When i try to debug it everything is working (it gets into the php function) and updates my $_SESSION variable.
BUT it never runs the success function and it never alerts the data.
What am i doing wrong?
NOTE: I know this question is from a couple of months ago, but any help will be useful for people looking for answers to this kind of problems.
As far as I know, because I'm running with a similar problem, it all depends on the response you get from the webservice (you can check it out with Chrome debugging console). For instance, I'm getting this now:
readyState: 4
statusText: "OK"
responseText: (The result I am looking for)
The problem is, as you say, I always get to run the Error part of the callback, never the Success, even if I'm getting the right responseText. As I've read, that's because the call to the WS was OK, but the parsing from JSON wasn't, so it calls "error".
So far I don't know how to fix it, but maybe this will give a clue.
I have two HTML pages that work in a parent-child relationship in this way:
The first one has a button which does two things: First it requests data from the database via an AJAX call. Second it directs the user to the next page with the requested data, which will be handled by JavaScript to populate the second page.
I can already obtain the data via an ajax call and put it in a JSON array:
$.ajax({
type: "POST",
url: get_data_from_database_url,
async:false,
data: params,
success: function(json)
{
json_send_my_data(json);
}
});
function json_send_my_data(json)
{
//pass the json object to the other page and load it
}
I assume that on the second page, a "document ready" JavaScript function can easily handle the capture of the passed JSON object with all the data. The best way to test that it works is for me to use alert("My data: " + json.my_data.first_name); within the document ready function to see if the JSON object has been properly passed.
I simply don't know a trusted true way to do this. I have read the forums and I know the basics of using window.location.url to load the second page, but passing the data is another story altogether.
session cookie may solve your problem.
On the second page you can print directly within the cookies with Server-Script tag or site document.cookie
And in the following section converting Cookies in Json again
How about?
Warning: This will only work for single-page-templates, where each pseudo-page has it's own HTML document.
You can pass data between pages by using the $.mobile.changePage() function manually instead of letting jQuery Mobile call it for your links:
$(document).delegate('.ui-page', 'pageinit', function () {
$(this).find('a').bind('click', function () {
$.mobile.changePage(this.href, {
reloadPage : true,
type : 'post',
data : { myKey : 'myVal' }
});
return false;
});
});
Here is the documentation for this: http://jquerymobile.com/demos/1.1.1/docs/api/methods.html
You can simply store your data in a variable for the next page as well. This is possible because jQuery Mobile pages exist in the same DOM since they are brought into the DOM via AJAX. Here is an answer I posted about this not too long ago: jQuery Moblie: passing parameters and dynamically load the content of a page
Disclaimer: This is terrible, but here goes:
First, you will need this function (I coded this a while back). Details here: http://refactor.blog.com/2012/07/13/porting-javas-getparametermap-functionality-to-pure-javascript/
It converts request parameters to a json representation.
function getParameterMap () {
if (window.location.href.indexOf('?') === (-1)) {
return {};
}
var qparts = window.location.href.split('?')[1].split('&'),
qmap = {};
qparts.map(function (part) {
var kvPair = part.split('='),
key = decodeURIComponent(kvPair[0]),
value = kvPair[1];
//handle params that lack a value: e.g. &delayed=
qmap[key] = (!value) ? '' : decodeURIComponent(value);
});
return qmap;
}
Next, inside your success handler function:
success: function(json) {
//please really convert the server response to a json
//I don't see you instructing jQuery to do that yet!
//handleAs: 'json'
var qstring = '?';
for(key in json) {
qstring += '&' + key + '=' + json[key];
qstring = qstring.substr(1); //removing the first redundant &
}
var urlTarget = 'abc.html';
var urlTargetWithParams = urlTarget + qstring;
//will go to abc.html?key1=value1&key2=value2&key2=value2...
window.location.href = urlTargetWithParams;
}
On the next page, call getParameterMap.
var jsonRebuilt = getParameterMap();
//use jsonRebuilt
Hope this helps (some extra statements are there to make things very obvious). (And remember, this is most likely a wrong way of doing it, as people have pointed out).
Here is my post about communicating between two html pages, it is pure javascript and it uses cookies:
Javascript communication between browser tabs/windows
you could reuse the code there to send messages from one page to another.
The code uses polling to get the data, you could set the polling time for your needs.
You have two options I think.
1) Use cookies - But they have size limitations.
2) Use HTML5 web storage.
The next most secure, reliable and feasible way is to use server side code.