Eror 500 with ajax and codeigniter - javascript

I have a problem with calling ajax on my view on codeigniter website. Ajax is calling method in controller on same project.
I have ajax search, which is work correctly. When I chose one of results, he open a new tab and show me a detail information from database. In some cases when I click on some results(I didn't find rule when it will be happening), ajax return me a 500 error, without go into controller method, but when I refresh the page (F5) he shows me a correct result. Did someone have a same problem, or can help me to fix it?
Here is my ajax call:
<script>
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '<?=site_url('index/ajax_read_details')?>',
dataType: 'json',
cache: false,
async:true,
data: {'param':'<?=$selected?>'},
beforeSend: function (xhr) {
$('#loading').show();
},
success: function (data) {
$('#loading').hide();
var details = '<tr>' +
'<td>'+data['title']+'</td> '+
'<td>'+data['code']+'</td>' +
'</tr>';
$('#data >tbody').append(details);
})
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: '+ errorThrown);
}
});
});
</script>
I know now that he didn't go into controller method "ajax_read_details" in index controller in case when it give me an 500 error.But when I refresh, he go into that method and do it correctly job. In both cases, he send a same values but in first he didn't return values, after refresh page he give me a values :(
Short controller method is:
public function ajax_read_details()
{
$param = $this->input->post('param');
echo json_encode(array('title' => $param, 'code'=>param));
}

Related

Having a hard time understanding redirecting / routing in laravel

I am completely stuck since two hours and definitely need your help. Disclaimer: I am not a coder - just a guy who is trying to mock up an idea.
So my page is actually working fine but I thought about moving content from a modal-popup to an actual sub-page. Meaning: If a user clicks on a button, some data points from the current page are being collected and passed to another view which shall be rendered using the data points as input.
EDIT: For clarification: The button is on /results.php where data is generated dynamically. The method should take some data points from here and generate a new view and render it at /buy.php or maybe at /buy/custom.php
My thoughts:
Normal redirect without parameters: Internal Link
Updating page-content without redirect but with parameters: Ajax
So combining my thoughts -> use ajax and return a new fresh view.
What I tried:
$("body").on("click", ".fa-shopping-cart", function() {
var $para1 = $(this).attr("data1");
var $para2 = $(this).attr("data2");
var $para3 = $(this).attr("data3");
var $para4 = $(this).attr("data4");
$.ajax({
url: "buy",
data: {
a: $para1,
b: $para2,
c: $para3,
d: $para4
},
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
type: "post",
success: function(response){
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});});
Routing:
Route::post('/buy', 'PageRouting#buy');
Controller:
public function buy()
{
$para1= $_POST['a'];
$para2 = $_POST['b'];
$para3 = $_POST['c'];
$para4 = $_POST['d'];
// some magic to output $data
return view('pages.buy', compact("data"));
}
buy.blade.php exists and displays $data with help of an foreach-loop.
So, when I first clicked the button the obvious happend:
The view ('pages.buy') is logged / displayed in my console in plain html and not rendered in the browser.
Now I am sitting here since two hours and I have no clue whatsoever. I read some blog post saying that you cannot redirect within an ajax-call. Unfortunately the post did not gave any hint on how to do it instead.
Can someone help me?
All best
If you want to replace entire document with the response you have to use document.write but it's not the best thing to do. Why don't you use normal form submit if you need to return a view?
success: function(response){
document.write(response);
},
P.S. if you want also to change the url, use the history manipulation functions.
https://developer.mozilla.org/en-US/docs/Web/API/History_API
in your buy method -
public function buy ()
{
....//some stuff to get $data
$html = view('pages.buy', compact("data"))->render();
return response()->json([
'success' => true,
'html' => $html
])
}
in your ajax success function
success: function(response){
if(response.success)
{
$('#elementId').html(reponse.html) // or whatever you need
}
},

Bing Maps REST - Javascript

I am a beginner with JavaScript and I am facing some issues with parsing JSON and display the data I want to.
When I run the URL manualy in browser I get a correct result back.
The JavaScript code looks like this:
request = "URL"
function CallRestService(request, callback) {
$.ajax({
url: request,
dataType: "jsonp",
jsonp: "jsonp",
success: function (r) {
callback(r);
var results = data.resourceSets;
console.log(r.message);
alert(r.statusText);
},
error: function (e) {
alert("Error" + JSON.stringify(e));
console.log("Error" + e.message);
}
});
}
When I run this code I get no error in the console but I still get an alert via the error function: "status":200,"statusText":"OK"
Why do I get this?
And thats why I cannot get my data displayed, what I am doing wrong?
EDIT
so I was able to make a working code out of it, but I still get messages from SUCCESS and ERROR at the same time and I also get my data back?!
<script>
var request = "URL";
function CallRestService(request, callback) {
$.ajax({
url: request,
dataType: "jsonp",
jsonp: "jsonp",
success: function (r) {
callback(r);
console.log("working" + r.message);
alert(r.statusText);
},
error: function (e) {
alert("Error" + e.message + JSON.stringify(e));
console.log("message: " + e.message);
console.log("readyState: " + e.readyState);
console.log("responseText: "+ e.responseText);
console.log("status: " + e.status);
}
});
}
CallRestService(request, GeocodeCallback);
function GeocodeCallback(results) {
console.log(results.resourceSets[0].resources[0].travelDurationTraffic);
document.getElementById("sec").innerHTML=Math.round((parseFloat(results.resourceSets[0].resources[0].travelDurationTraffic) / 60));
}
</script>
Assuming that you put an actually URL into the request parameter this looks fine. A 200 status means it was successful and this likely called the console from your success function. I know you said you removed it to be sure, but the page could of been cached. If you take a look at the network request you will likely see that it was successful as well. Ifs possible that an error in your success function is occurring and triggering the error function. Have you tried adding break points inside of the two functions?
Here is a blog post that shows how to access the Bing Maps REST services using jQuery and other frameworks: https://blogs.bing.com/maps/2015/03/05/accessing-the-bing-maps-rest-services-from-various-javascript-frameworks/ It looks like your code is very similar.

Ajax jquery making web api call

I made an api in java , which allows the user to get data.
there is an call : ..../api/users where i give a list back of all users avalible.
Now i got a site with a search user button, wen you press that button i want to make a call to /api/users with the help of Ajax.
i got the part that you can click on the search button, but i don't understand how to make that call with ajax
This is my code:
$.ajax({
url: ”api / resource / users ",
dataType: "json”,
}
).fail(
funcNon(jqXHR, textStatus) {
alert("APIRequestfailed: " + textStatus);
}
).done(
funcNon(data) {
alert("succes!")
}
);
Is this the way of making a good call with ajax ?
or do i have to use :
http://localhost/projectUser/api/resource/users ?
Assuming you are using JQuery to make the Ajax call then this sample code should be helpful to you. What it does is;
On search button was clicked
Do AJAX call to fetch stuff from your Java REST API
When the expected JSON object was returned, parse it and do something
O
$(document).ready(function() {
$('#demoSearchBtn').click(function () {
// Search button was clicked!
$.ajax({
type: "GET",
url: "http://localhost/projectUser/api/resource/users", // edit this URL to point into the URL of your API
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
var jsonObj = $.parseJSON(data);
// Do something with your JSON return object
},
error: function (xhr) {
alert('oops something went wrong! Error:' + JSON.stringify(xhr));
}
});
});
}
if this http://localhost/projectUser/api/resource/users is the url, it's either
$.ajax({
url: ”api/resource/users", ...
or
$.ajax({
url: ”http://localhost/projectUser/api/resource/users", ...
depending on what the browsers current URL is (relative or absoute depends on context of the browser).
but it is never ever ”api / resource / users " with spaces between words and slashes.

check if ajaxcall has been made in ie7

I have an ajax call in my document ready function. But in about 1 out of 10 times in ie7, the ajax function doesnt get called at all.
Is there a way to check if the ajax call has been made, otherwise run it again until it either runs in to the error or success functions? The problem only occurs when i run the page in ietester -> ie7 mode. Thanks
code: http://jsfiddle.net/jxEj5/
You could setup a variable as a monitor, and a timer to issue an ajax call every 5 seconds until the ajaxCall is finished.
The monitor is set through var gotAjax = false and when the Ajax is succeeded, it is set to true gotAjax = true.
Instead of call the $ajax directly, you set a time clock through setTimeout(ajaxCall, 5000). With in the timer, if the ajaxCall is set, you clear the timer through clearTimeout(ajaxCall)
$(function() {
var gotAjax = false;
var ajaxCall = function () {
if (!gotAjax) {
$.ajax({
url: '../SentinelOperationsUI/GenericHandler.ashx',
dataType: 'json',
data: {
'FunctionName': 'GetActivity',
'SearchType': 'Single',
'postedData': JSON.stringify($('#content').data('postedData'))
},
success: function(data) {
gotAjax = true;
$('#content').data('activityKey', data.SENTINEL_OPERATION_ACTIVITY_KEY);
$.ajax({
url: '../SentinelOperationsUI/ajax/activityviews/' + data.ACTIVITY_VIEW,
dataType: 'html',
success: function(data) {
$('#content').hide().html(data).fadeIn(200);
$('#parenttabs, #tabs, #tabs2, #parenttab-1, #parenttab-2').tabs();
}
});
}
});
}
else {
clearTimeout(ajaxCall);
}
};
setTimeout(ajaxCall, 5000);
});
This is an example in jQuery that should help you debug it
If you're not using jQuery, i will need to see your code :)
The error function will occur in case a 404 or similar error occurred, and in case the ajax DID occur but some unexpected response was returned and your javascript bugged, the try .. catch will help you detect the error more easily :)
$.ajax({
url: "file.php",
type : "POST",
contentType : "application/x-www-form-urlencoded",
success: function(response){
try{
// Success code
}catch(e){
// Possibly you have an error in your JS, this should alert it to you
alert(e.message);
}
},
error : function(jqXHR, textStatus, errorThrown){
// Error occured, lets see what's wrong
alert("error " + textStatus + ": " + errorThrown);
}
});

How do I reload the page after all ajax calls complete?

The first time a user is visiting my website, I am pulling a lot of information from various sources using a couple of ajax calls. How do I reload the page once the ajax calls are done?
if(userVisit != 1) {
// First time visitor
populateData();
}
function populateData() {
$.ajax({
url: "server.php",
data: "action=prepare&myid=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
_id = response[json].id;
getInformation(_id);
}
});
}
function getInformation(id) {
$.ajax({
url: "REMOTESERVICE",
data: "action=get&id=" + id,
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
$.ajax({
url: "server.php",
data: "action=update&myid=" + id + '&data=' + json.data.toString(),
dataType: "json",
success: function(json) {
if(json.error) {
return;
}
}
});
}
});
}
So what the code does is, it gets a list of predefined identifiers for a new user (populateData function) and uses them to get more information from a thirdparty service (getInformation function). This getInformation function queries a third party server and once the server returns some data, it sends that data to my server through another ajax call. Now what I need is a way to figure out when all the ajax calls have been completed so that I can reload the page. Any suggestions?
In your getInformation() call you can call location.reload() in your success callback, like this:
success: function(json) {
if(!json.error) location.reload(true);
}
To wait until any further ajax calls complete, you can use the ajaxStop event, like this:
success: function(json) {
if(json.error) return;
//fire off other ajax calls
$(document).ajaxStop(function() { location.reload(true); });
}
.ajaxStop() works fine to me, page is reloaded after all ajax calls.
You can use as the following example :
$( document ).ajaxStop(function() {
window.location = window.location;
});
How it's works?
A: Whenever an Ajax request completes, jQuery checks whether there are any other outstanding Ajax requests. If none remain, jQuery triggers the ajaxStop event.
Hope help y'all, furthermore information, I'm sharing the link of the documentation following.
source: https://api.jquery.com/ajaxstop/
You could just redirect to the same page in the server.php file where the function is defined using a header('Location: html-page');
//document.location.reload(true);
window.location = window.location;
See more at: http://www.dotnetfunda.com/forums/show/17887/issue-in-ie-11-when-i-try-to-refresh-my-parent-page-from-the-popupwind#sthash.gZEB8QV0.dpuf

Categories

Resources