jquery ajax post not executed - javascript

I have a little problem with jQuery ajax.
I want to send a POST to a .php file and afterwards change the current URL. I tried the following code:
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
window.onload = function () {
$.ajax({
type: "POST",
url: "sample.php",
data: {'username': "STRING"},
timeout: 1000,
complete: function(){
window.location.href = 'http://127.0.0.1/sample/another.php';
}
});
}
</script>
So, as I can see in the chrome developer tools Network tab, no POST is executed. Although the URL changed to another.php
Can you tell me what I am doing wrong or how I can solve this issue?

use success instead of complete
$.ajax({
type: "POST",
url: "sample.php",
data: {'username': "STRING"},
timeout: 1000,
success : function(){
window.location.href = 'http://127.0.0.1/sample/another.php';
}
});

You will never see the POST. cause the url changes and remember the another.php hasn't made any AJAX requests! so you'll never find anything there. try changing the JS code in the success method to something like an alert to know if it works! and maybe then you'll find the POST method in the console!

Alternatively, you can use .done() as well. You may also think about scoping this inside a self executing function instead of a window.onload event.
(function($){
// Make an object for your param values.
var ajaxData = {
username: 'STRING',
anotherParam: 'STRING',
andanotherParam: 'STRING',
yetanotherParam: 'STRING'
};
$.ajax({
type: "POST",
url: "sample.php",
data: ajaxData
}).done(function(){
window.location.href = 'http://127.0.0.1/sample/another.php';
}).fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}(jQuery));

Related

How to return data from PHP to a ajax function

Hi I am currently learning php and I am trying to get data from php file using the below script but i am not getting any response
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert("Response : " ); // not triggering
}
});
my php return stmt
There might be problems with File URL or file access. You can use complete callback to check request for errors like that:
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert("Response : " );
},
// This method will be fired when request completes
complete: function(xxhr, status) {
alert("Status code: " + status);
}
});
If the status code is not success that means there is something wrong with your request.
You can check more callback options here.
It doesn't matter whether you use return or echo in your PHP file.
The success method must get a call if it's fine. However, if you use
return instead of echo, nothing will append to your request's data.
On the other hand, The PHP response will include in your 'data' variable in the function success.
You need use data in the assync function success
success: function(data) {
alert("Response : " + data);
},
Thanks for your Responses. I got the Solution to my problem. It seems since Ajax is asynchronous... its taking time to receive the resultant echo value from my php file. so I had to synchronize my Jquery using async : False.
$(function(){
$('#formID').on('submit',function(){
const data_set={
name:"Nipu chakraborty",
"phone":"01783837xxx"
}
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert(data);
}
});
});
});

Calling controller function from JS file

Im using Yii framework, i want to call controller function from JS file,
My ajax code in JS file:
$.ajax({
type: "POST",
url: "operator/checkDisabledDates",
data: {
id: 1
},
success: function(data) {
alert('success');
},
error: function(data) {
alert("Fail");
}
});
where checkDisabledDates is my controller method name, and operator is my controller name.
i got wrong formation of url something like,
www.example.com/operator/agent/id/4/operator/checkDisabledDates
my ajax url just appends at last position of existing url,
i tried different combinations like,
url: "/operator/checkDisabledDates"
url: "../operator/checkDisabledDates"
url: "../checkDisabledDates"
nothing worked,
but when i use in below syntax it worked,
url: "../../checkDisabledDates"
Is there anyway to do this without hardcoding dots(.) like this???
I would suggest not using a relative path to call your controller.
Try using your domain as context
var domainName = 'yourSite.com'
url: domainName+"operator/checkDisabledDates"
I'm using in my project and it's working for me, please try this -
Define a Global Variable in JS file eg. -
var url_path = document.location.origin+document.location.pathname;
so now you can use like this
url: url_path+'?r=operator/checkDisabledDates'
or
url: url_path+'operator/checkDisabledDates'
Use this:
data = {};
data.r = 'operator/checkDisabledDates';
data.id = 1;
$.ajax({
type: "POST",
url: "index.php",
data: data,
success: function(data) {
alert('success');
},
error: function(data) {
alert("Fail");
}
});
Always works for me.

how to pass headers in jQuery.load like ajax?

I've been stuck from this issue in couple of days. I want to send some headers data in jQuery.load(). It seems that jQuery.load never send the headers, like ajax. Can somebody explain how to, or Is it necessary? Btw, sory my bad English.
This is the syntax :
$loadingBay.load(href, settings.data, function (data, status) {
prep(status === 'error' ? $tag(div, 'Error').html(settings.xhrError) : $(this).contents());
});
Many Thanks
You can not pass headers data to $.load() , but you can set default setup using $.ajaxSetup() like this :
$.ajaxSetup({
'headers':{
'header1':'value1',
'header2':'value2',
}
}
);
//give the load call here
$('selector').load('url',function(){
//do things
})
Disclaimer From jquery doc:
Its use is not recommended.
The best way is do the is thing using $.ajax() :
$.ajax({
url: "test.html",
headers : {header1 : "header1"}
}).done(function(data) {
$('selector').html(data);
});
You can use beforeSend option in jquery ajax , like as follows :
$.ajax({
url: "http://localhost/restTest",
data: { uname: "asdf" },
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('X-TOKEN', 'xxxxx');},
success: function() { alert('Success!' + authHeader); }
});
or can also use headers like,
$.ajax({
url: "http://localhost/restTest",
data: { uname: "asdf" },
type: "GET",
headers:{ "X-TOKEN": 'xxxxx'},
success: function() { alert('Success!' + authHeader); }
});

How to pass parameters in GET requests with jQuery

How should I be passing query string values in a jQuery Ajax request? I currently do them as follows but I'm sure there is a cleaner way that does not require me to encode manually.
$.ajax({
url: "ajax.aspx?ajaxid=4&UserID=" + UserID + "&EmailAddress=" + encodeURIComponent(EmailAddress),
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
I’ve seen examples where query string parameters are passed as an array but these examples I've seen don't use the $.ajax() model, instead they go straight to $.get(). For example:
$.get("ajax.aspx", { UserID: UserID , EmailAddress: EmailAddress } );
I prefer to use the $.ajax() format as it's what I’m used to (no particularly good reason - just a personal preference).
Edit 09/04/2013:
After my question was closed (as "Too Localised") i found a related (identical) question - with 3 upvotes no-less (My bad for not finding it in the first place):
Using jquery to make a POST, how to properly supply 'data' parameter?
This answered my question perfectly, I found that doing it this way is much easier to read & I don't need to manually use encodeURIComponent() in the URL or the DATA values (which is what i found unclear in bipen's answer). This is because the data value is encoded automatically via $.param()). Just in case this can be of use to anyone else, this is the example I went with:
$.ajax({
url: "ajax.aspx?ajaxid=4",
data: {
"VarA": VarA,
"VarB": VarB,
"VarC": VarC
},
cache: false,
type: "POST",
success: function(response) {
},
error: function(xhr) {
}
});
Use data option of ajax. You can send data object to server by data option in ajax and the type which defines how you are sending it (either POST or GET). The default type is GET method
Try this
$.ajax({
url: "ajax.aspx",
type: "get", //send it through get method
data: {
ajaxid: 4,
UserID: UserID,
EmailAddress: EmailAddress
},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
And you can get the data by (if you are using PHP)
$_GET['ajaxid'] //gives 4
$_GET['UserID'] //gives you the sent userid
In aspx, I believe it is (might be wrong)
Request.QueryString["ajaxid"].ToString();
Put your params in the data part of the ajax call. See the docs. Like so:
$.ajax({
url: "/TestPage.aspx",
data: {"first": "Manu","Last":"Sharma"},
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
Here is the syntax using jQuery $.get
$.get(url, data, successCallback, datatype)
So in your case, that would equate to,
var url = 'ajax.asp';
var data = { ajaxid: 4, UserID: UserID, EmailAddress: EmailAddress };
var datatype = 'jsonp';
function success(response) {
// do something here
}
$.get('ajax.aspx', data, success, datatype)
Note
$.get does not give you the opportunity to set an error handler. But there are several ways to do it either using $.ajaxSetup(), $.ajaxError() or chaining a .fail on your $.get like below
$.get(url, data, success, datatype)
.fail(function(){
})
The reason for setting the datatype as 'jsonp' is due to browser same origin policy issues, but if you are making the request on the same domain where your javascript is hosted, you should be fine with datatype set to json.
If you don't want to use the jquery $.get then see the docs for $.ajax which allows room for more flexibility
Try adding this:
$.ajax({
url: "ajax.aspx",
type:'get',
data: {ajaxid:4, UserID: UserID , EmailAddress: encodeURIComponent(EmailAddress)},
dataType: 'json',
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
Depends on what datatype is expected, you can assign html, json, script, xml
Had the same problem where I specified data but the browser was sending requests to URL ending with [Object object].
You should have processData set to true.
processData: true, // You should comment this out if is false or set to true
The data property allows you to send in a string. On your server side code, accept it as a string argument name "myVar" and then you can parse it out.
$.ajax({
url: "ajax.aspx",
data: [myVar = {id: 4, email: 'emailaddress', myArray: [1, 2, 3]}];
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
You can use the $.ajax(), and if you don't want to put the parameters directly into the URL, use the data:. That's appended to the URL
Source: http://api.jquery.com/jQuery.ajax/
The data parameter of ajax method allows you send data to server side.On server side you can request the data.See the code
var id=5;
$.ajax({
type: "get",
url: "url of server side script",
data:{id:id},
success: function(res){
console.log(res);
},
error:function(error)
{
console.log(error);
}
});
At server side receive it using $_GET variable.
$_GET['id'];

PhoneGap AJAX Login

I am trying to build a log in application in PhoneGap. Ive been looking around a lot for similar things and I found them plenty... but I do not understand why this pieces of code does not work. When i press the logIn_btn it shows that It cannot reach the "success" piece of code. Thank you for your help!
$('#logIn_btn').click(function(){
user = $('#username').val();
pass = $('#password').val();
var ev = {'papa':true};
if(user!='' && pass!=''){
alert('trying login');
$.ajax({
url: 'https://localhost/server/IF/mobileApp/login.php',
type: 'post',
datatype: 'json',
data: ev,
success: function(data){
alert('asd');
}
});
console.line('done.')
} else {
alert('Please insert your username and password.');
}
});
Your server should not be https://localhost, it should be the name/ip of the server that you'll be logging into.
For additional information, look at your network tab with Chrome, or install a fail handler
$.ajax({
url: 'https://localhost/server/IF/mobileApp/login.php',
type: 'post',
datatype: 'json',
data: ev,
success: function(data){
alert('asd');
}
}).fail(function(jqXHR, textStatus){
});
console.line?I think it would be console.log. Rather try alerting the message. Also make sure the javascript executes after deviceready. Also localhost in android is a very different thing. Try using the ipadress or domain name to access the server.

Categories

Resources