JQuery $.post() doesn't work - ajax

Can any one help me with the following code:
$(document).ready(function() {
$("#add_user").submit(function() {
$.post( "../php/register_sql_ins.php",
{r_fname: $("#fname").val(),
r_lname: $("#lname").val(),
r_uname: $("#uname").val(),
r_pass: $("#pass").val(),
r_authLevel: $("#authLevel").val(),
r_email: $("#email").val(),
r_company: $("#company").val(),
r_phone: $("#phone").val(),
r_address: $("#add").val()}, function(result) {
alert(result);
}
);
return false;
});
});
This should store my user data in a sql table. the php part of code(register_sql_ins.php) works fine. but this query piece of code just doesn't work!! and I have no idea what is the problem!
With Firebug it returns false every time!
By the way sorry for bad english. It's not my mother tong!

There are two places where I would look for the cause of such error:
Network tab in Firebug. Check what is sent to the server and what is the response. If data sent is correct and server replies with status 200, then you have to debug your PHP script, else
Server logs. If the request failed to complete succesfully, log will contain the reason.

Related

how to control multiple ajax requests in laravel 5.2

I am working on an application where different ajax requests fires depending upon different actions.
For example, there is a chat window having send button. When i click on that button an empty message is sent with ajax, successfully. It work nice. But when I hit the send button too many times, at start some requests respond 200 (ok) but then it respond 500 (internal server error). Due to this the other requests that are going continuously like updateLastActivity also disturb.
The preview of the error in developer's tool is:
Whoops like something went wrong.
Note: When I make this chat system in core PHP, it work fine. There is no internal server error when I send too may requests.
Here is the code I am using
//the following code is used to send the message
$(document).on('click','.send_message_bt',function(event){
event.preventDefault();
var id=$(this).data('id');
var name=$(this).data('name');
var message=$("#message_field-"+id).val();
$.ajax({
//headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
headers: { 'X-CSRF-TOKEN': {!! json_encode(csrf_token()) !!} },
url:'{{route('user.sendmessage')}}',
type:'POST',
data:{
id:id,
message:message
},
success:function(data,status){
//clear the message field value
$("#message_field-"+id).val('');
//update the chat history
fetchChatHistory(id,name);
},
error:function(response){
if(response.status==401){
alert('You are not logged in!');
window.location=window.location.href;
}
}
});
});
here is the back end code
public function sendMessage(Request $request){
$message=new Userchatmessage();
$message->message=$request->message;
$message->sender_id=Auth::user()->id;
$message->receiver_id=$request->id;
$message->save();
return response('success');
}
How to fix this issue.
I guess it's not a problem with Laravel or anything, but with your browser. Each browser has a maximum amount of simultaneous connections it will open for a certain domain.
Read more about this problem here and here.
If you want to make a realtime chat application, consider using something like NodeJS and Socket.io.
Async and await can help. Let an async function
async function doAjax(){
await runFirstAjaxCall();
await runAfterFirstAjaxCallSuccess();
....
....
}
doAjax();

Ajax call not working in Virtual Host in WAMP

I am working on a CI project, and for that, I have created a virtual host in wamp. It's working good. But the main problem started now. Whenever I call Ajax request it with/without giving the ajax post URL it shows a result. I don't know what is the issue..
I am clicking on forgot password link and then it opens a popup with forgot password form.
Without URL
$.get('').done(function (msg) {
console.log('Yes');
console.log(msg);
}).fail(function (xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
});
Result
In this case I am getting the result (it's going in "done") but giving me the whole login page HTML.
With URL
$.get('http://fileupload.local/login/getresetpassword').done(function (msg) {
console.log('Yes');
console.log(msg);
}).fail(function (xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
});
Result
I have tried too many solutions over google, but couldn't find the right one. Now I am pulling my hair and want to complete it.
Your Ajax looks ok to me. It should work. I have some suggestions:
Open directly Url: http://fileupload.local/login/getresetpassword in your browser. We will see the result (Seem that it will return the whole page?)
Check the server code. I think it's our main issue. Will it return the JSON type or not?
It was a config issue. It resolved by just change $config['uri_protocol'] = 'QUERY_STRING'; to $config['uri_protocol'] = 'REQUEST_URI';

Can't make ajax POST calls with an express site running on Heroku

I've recently deployed an express app to heroku which was working fine locally. Now, on heroku, the parts where I make ajax post call are breaking with 500 Internal Server Errors.
In my JS my POST call looks like this:
$.post('/api/', {
'input': 'input'
}, function(data) {
if (!data) {
return console.log('success');
} else {
return console.log('failed');
}
});
And it's treated by express like this (I'm abstracting here):
app.route('/api/')
.post(function (req, res) {
var input = req.body.input;
x.doSomething(input,function (err,data) {
res.send(err);
}
});
After some googling I suspected it might have to do with Access-Control so I added some code to my express app which enabled Access-Control-Origin from everywhere. This stopped the 500 errors and instead caused the post to hang and then timeout after 30 seconds.
I assume this is something to do with Heroku because it's all working fine locally. Any suggestions would be super helpful.
** EDIT **
I've done some more digging and it turns out it's the line var = req.body.input that's causing all the trouble. If I remove this, I don't the 500 error. Another clue, is that in the breakdown of the 500 error, it seems there's some kind of crossDomain sending going on - jquery states in the first line of the error: l.cors.a.crossDomain.send. So something's clearly amiss here and I'm pretty sure it's not to do with the way I've written the ajax call...

NS_Binding_Aborted error for ajax function

I have a link on click of which a request should go to web server and on successful execution a redirection should happen. I have used ajax for this but I am getting NS_Binding_Aborted error in HTTpFox.
The code:
<a id="lnkredirect" href="javascript:void(0);" onclick="myfunction();">Some text</a>
The ajax code:
function myfunction(){
$.ajax({
url: Web server Url,
type: 'POST',
datatype: 'JSON',
timeout: 20000,
data: null,
success: function{ $("#lnkredirect").attr('href','redirection link...');},
error : function{ $("#lnkredirect").attr('href','redirection link...');}
)};
return true;
}
The redirection is happening but I am getting NS_Binding_Aborted error in Firefox. In both success and error scenario, the redirection should happen but why NS_Binding_Aborted is coming, I am not sure of this. NS_Binding_Aborted error should come only if one event is cancelling some prior running event but I have already suppressed href of the link and redirecting it once the ajax request is executed, so there should be only one server call and NS_Binding_Aborted should not come. Please let me know where am I going wrong?
I got a similar trouble, also while using both a href and a XmlHttpRequest inside a onclick. My XMLHttpRequest was aborted (ns_binding_aborted) and thus never reached status 200. I also could see that my XHR was "blocked by devtools" in Firefox console.
This was because the page was reloaded (by the href) before it could finish its job (what was in the onclick).
I had something like this:
<script type="text/javascript">
function incrementNumberOfDownloads() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) { // 4 = request ended, 200 = success
//update displayed number of downloads
document.getElementById("numberOfDownloads").innerHTML = this.responseText;
}
};
xhttp.open("GET", "incrementNumberOfDownloads.php", true);
xhttp.send();
return true;
}
</script>
<p id="numberOfDownloads">42</p>
Download my file !
I fixed the problem by adding a target="_blank" to my download link, so that the page is no more reloaded when clicking, enabling the XMLHttpRequest to finish with success.
This is caused by another request that abort your request. Generally when your goal is reload data o all page just end request and don'ts is synchronized request, a little novell error.
In this case the "return " sentence is the problem, the return sentence must be in success seccion.
My issue fixed, when I've changed calling native js form submit event to jQuery submit event.
// this code
form[0].dispatchEvent(new Event("submit"));
// changed to
form.submit();

Chrome gives "XMLHttpRequest Exception 101" in some cases when doing an Ajax request

I have a JavaScript application that works like this:
Uploads a file, receives the uploaded file ID as a response
This is done using the BlueImp uploader
Uses the file ID to refer to the file in subsequent requests, in this case to receive a preview of the uploaded file.
This is the code for the file upload 'complete' handler. It's originally written in Coffee Script (http://pastebin.com/708Cf9tu).
var completeHandler = function(e, data) {
var url;
if (data.textStatus !== 'success') {
alert("Noe gikk galt. Debug informasjon er logget i konsollen");
console.group('Upload failure');
console.error(data.textStatus);
console.error(data.result);
console.groupEnd('Upload failure');
selectButton.removeClass('disabled');
uploadButton.removeClass('disabled loading');
uploadButton.html('Last opp');
return;
}
self.fileUploadResponse = data.result;
url = "" + config.api_root + "/" + config.api_path_tabulardatafilepreview;
return $.ajax(url, {
type: 'POST',
dataType: 'json',
async: false,
data: {
'file_handle': data.result.file_handle,
'rownum': 5
},
complete: function(req, text_status) {
if (text_status !== 'success') {
alert("Noe gikk galt. Debug informasjon er logget " + "i konsollen");
console.group('Failed to receive data file preview');
console.log(text_status);
console.log(req.responseText);
console.log(req);
console.groupEnd('Failed to receive data file preview');
selectButton.removeClass('disabled');
uploadButton.removeClass('disabled loading');
uploadButton.html('Last opp');
}
self.previewData = JSON.parse(req.responseText);
return self.setStage(2);
}
});
};
This works brilliantly in FireFox, but in Chrome I just started to get an error in the second jQuery Ajax request. It now returns with status "error", with no responseText and with statusText set to "Error: NETWORK_ERR: XMLHttpRequest Exception 101". Though this doesn't happen in all cases. The uploaded file doesn't seem to have anything to do with the issue, because a 10KB csv file works, a 120KB xlsx file fails but a 1.2MB xlsx works. Additionally it's the second Ajax request that fails, and it doesn't do anything but send two small integers to the server. Why does that fail!?
Also this just started happening today. I haven't changed anything that I know of, and I have not updated Chrome.
Does anyone have a clue as to why Chrome is doing this? Can it have anything to do with an Ajax request being launched in the complete handler of a previous Ajax request?
Thanks for any guesses that can help me solve this
Turns out it's a bad idea to start lengthy processes inside Ajax event handlers. In my case, starting a new synchronous Ajax request in the event handler was the mistake. I have since made both requests asynchronous and separated the code into neat functions, and I'm no longer bothered by the exception.

Resources