Call php function in javascript without waiting for response - php

I know how to use $.ajax. I have a Codeigniter project so I just call:
url:'<?php echo base_url()."somecontroller/somefunction"?>',
This is all ok but ajax waits for the response. I just want to the call the url as you would by typing it in your browser. I don't want to wait for the response because the controller does a redirect and then loads a view. Also i need to be able to send some data via POST.
How can I do this?

You can use the following for sending asynchronous request with additional parameters.
$.ajax({
type: "POST",
url: url,
data: data, // additional parameters
async:true,
success: function(response){
}
});

If you want the request to be synchronous, set async:false.
For post, type:POST
Refer http://api.jquery.com/jQuery.ajax/

Do you can try this ?
Change the (alert) function with your function
$.ajax({
url: 'test.html',
async: false,
success: function () { alert('hello people from the world'); }
});
Never use async: false.
Since Javascript runs on the UI thread, an async: false request will freeze the browser until the server replies

Related

sending array to codeigniter (php) controller using ajax and jquery and load page on existing loaded page (in any div)

function showmypage(calculated){
var sorteddata = JSON.stringify(calculated);
myurl = URL + 'personalloan/getPLOffersbyfilter/eligibility';
var request = $.ajax({
url: myurl,
method: 'POST',
data: {data:sorteddata},
dataType: 'html'
}).done(function(msg){
$(".divoffersfilter").load(myurl);//here is error
console.log(msg);
});
}
I want to send array (calculated is array name) to the controller and this and load a dynamic PHP page using content in that array. But, here it treats ".load()" function separately. the ajax is processing the request and giving back the response but the response is not loaded on view file.
Note that you are making two ajax requests to the same URL.
The first one is with the code
var request = $.ajax({
url: myurl,
...
The second ajax call is in your .done block.
$(".divoffersfilter").load(myurl);
The .load() function is shorthand that essentially amounts to this.
$.ajax({
url: myurl,
method: 'GET',
success: function(data){
$(".divoffersfilter").html = data;
}
});
Without seeing the code that executes at the URL it is not possible to provide advice on which ajax approach to use. But you probably should not use both.

jquery multiple ajax calls without using asynch false

I have a page that has to run an ajax command a few times. It has to use the results of the previous ajax call in for the current one.
in laymen's terms:
call ajax, build entity on remote server, return result (i get a proprietary id as result)
...
call ajax, use result to post additional data to remote server, get id of this post
...
call ajax, post ids..etc
my first idea was async:false, but i see this is widely unacceptable and it ruins code execution order. My goal too, is to have a dialog window that prints the results of the ajax calls as they happen. Currently, the dialog window appears once all ajax calls are done. I don't get the pretty little: Build....done then additional Options.....done and so on...
if i make asynch:true, i wont have the id's need to process the next ajax..
what other options do i have have?
//form var is set earlier, standard serialized form.
var functions = ['build','additionalOptions','completion'];
$('#submitButton').click(function(){
$('#createGroupDialog').dialog({
autoOpen:false,
width: 1200,
height:800,
modal: true,
position: {my: "top", at: "top"},
resizable: false,
closeOnEscape: true
});
$("#createGroupDialog").dialog('open').html("<p>Please Wait...</p>");
function fireAjax(form,func)
{
$.ajax({
type: "POST",
url: "createGroup/createGroupDo.php",
data: form+"&func="+func,
asynch: false,
success: function (result) {
$('#createGroupDialog').append(result);
}
});
}
jQuery.each(functions , function(i,func){
fireAjax(form,func);
});
});
asynch:false is indeed a terrible way to deal with asynchronous data. It doesn't mess with the execution order but it blocks until the request finishes meaning no other JavaScript can run in the mean time, this includes things like onclick handlers and animations.
Since your requests rely on a previous request you have to write them like that:
$.ajax({
url: "request1.php",
data: data,
success: function (result_1) {
$.ajax({
url: "request2.php",
data: result_1,
success: function (result_2) {
$.ajax({
url: "request3.php",
data: result_2,
success: function () {}
});
});
});
}
});
But as you can see this gets tedious. You can use callbacks, but it's better use the Promise API.
Use like:
$.ajax({
url: "request1.php",
data: data
}).then(function (result_1) {
alert(result_1);
return $.ajax({
url: "request2.php",
data: result_1,
});
}).then(function (result_2) {
alert(result_2);
return $.ajax({
url: "request3.php",
data: result_2
});
}).then(function (result_3) {
alert(result_3);
});
It's worth noting that jQuery does a lot of work under the hood to make this API possible. $.ajax is a very flexible function. This means you can use it in many ways. It's best to chose one way and to stick with it. The current state of art really leans towards Promises.

jquery remote ajax request is not returning any results

I am trying to make a request to this file : http://traitdesign.com/work/tattva/get.php
this is the code I have so far:
function getRemote() {
return $.ajax({
type: "GET",
url: 'http://traitdesign.com/work/tattva/get.php',
async: false,
}).responseText;
}
getRemote();
well the issue is response headers is empty it doesnt return any results. any help would be appreciated. thank you
Try with JSONP
function getRemote() {
return $.ajax({
type: "GET",
url: 'http://traitdesign.com/work/tattva/get.php',
async: false,
dataType: "jsonp",
});
}
getRemote();
"jsonp": Loads in a JSON block using JSONP. Adds an extra
"?callback=?" to the end of your URL to specify the callback. Disables
caching by appending a query string parameter, "_=[TIMESTAMP]", to the
URL unless the cache option is set to true.
Problem is 'Same Origin Policy'. but you can escape from it. but some security issues will remain.
Please check this. http://enable-cors.org/server_php.html
header("Access-Control-Allow-Origin: *");
Include this line into your get.php file.
I think the best in your case would be to write simple ajax action on your server like:
print(file_get_contents('http://traitdesign.com/work/tattva/get.php');
And make ajax call to your new action. It will got through your server so additional server work will be done but you then don't need to care about security policy.
Use JSONP with callback. Also return the value once the call is done.
function getRemote() {
var jqXHR = $.ajax({
type: "GET",
dataType: "jsonp",
url: 'http://traitdesign.com/work/tattva/get.php',
async: false,
crossDomain: true
});
return jqXHR.responseText;
}
getRemote();

javascript array to php array

i am sending data through ajax call to the php code my ajax code is this
var values = JSON.stringify({ dstring: dataString, ukey:ukey });
var page_path = server_url+"save_data.php";
$.ajax({
type: "POST",
url: page_path,
cache: false,
data: values,
dataType: "json",
success: function(msg){
},
error:function(xhr, status, error) {
}
});
and in the ajax it send data like this
{"dstring":{"q2":"11","q3":"22","q4":"33","q5":"44","q6":"55"},"ukey":"1"}
and in the php when i try to get it through REQUEST it dont show me data , i am bit confuse on how to handle this data in php
Don't stringify data on your ajax call. You should then be able to $_POST['dstring']on the PHP script. Also, you should add in some debug code at least into that error handler to know what's up. Last but not least, inspect the network calls.
You have to get file_get_contents("php://input") and run that through json_decode.

Codeigniter echo/var_dump not working

Why doesn't var_dump work here, the ajax call is successful, but there is nothing printed, not even a string literal print from the PHP.
My controller
function check_links() {
$matches = $this->input->get('matchesJSON');
var_dump($matches);
//$this->load->view('publish_links_view');
}
Ajax call
$.ajax({
type: 'GET',
dataType: 'json',
cache: false,
data: 'matchesJSON='+matchesJSON,
url: 'publishlinks/check_links',
success:
function(response) {
}
})
I assume you're expecting it to var_dump to the browser.
Ajax happens "behind the scenes", so it wouldn't output to your browser, you'd have it in your success handler's response argument.
if you want to test it just hit the url directly with your browser.
http://ciroot/index.php/publishlinks/check_links?matchesJSON=test%20text
Also, you can monitor all of your AJAX requests / responses with the Browser extension Firebug, very useful in situations like this.
it seems to be a problem with your ajax call, not with codeigniter
start with removing dataType: 'json' - jQuery will find type of content itself as it's not json
and you need to output response in your function:
function(response) { window.alert(response) }

Categories