Jump to content

jquery / javascript function return


Digger

Recommended Posts

I have a .js file with the following code in


function quickUpdate(form_data, sUrl, rUrl) {
	$.ajax({
		url: sUrl,
		method: "POST",
		data: form_data,
		contentType: false,
		cache: false,
		processData: false,
		success: function(data) {
          	result = JSON.parse(data)
			Swal.fire({title: result.title, text: result.text, icon: result.icon});
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
     	alert(errorThrown);
  	}
	});
}

Everything seems to work fine but i am trying to get the results on the call page, in php it would be something like

public function quickUpdate($foo, $foo) {
	// do something 
	return bar;
}

but when i try 


	var retVal = null;
	$.ajax({
		url: sUrl,
		method: "POST",
		data: form_data,
		contentType: false,
		cache: false,
		processData: false,
		success: function(data) {
			var result = JSON.parse(data);
			retVal = result;
      return false;
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			var result = errorThrown;
			retVal = result;
      return false;
  	}
	});
	return retVal;

and call it from a page

var result quickUpdate(formData, '/admin/client/process/emailpreferences');

alert(result.title);

or

alert(result);

the alert is says Null or Undefined

Is their a way of doing this or am i just wasting my time

 

thanks

Link to comment
Share on other sites

You've posted bits and pieces. If there's nothing more to it and you've shown us everything then the answer is simple: you can't call PHP functions from Javascript like that.

But I suspect you haven't posted everything. Please do.

Link to comment
Share on other sites

i dont want to call a php function i was to get the results from the javascript function

 

java.js

function quickSubmit(form_data, sUrl) {
	var retVal = null;
	$.ajax({
		url: sUrl,
		method: "POST",
		data: form_data,
		contentType: false,
		cache: false,
		processData: false,
		success: function(data) {
			var result = JSON.parse(data);
			retVal = result;
      return false;
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			var result = errorThrown;
			retVal = result;
      return false;
  	}
	});
	return retVal;
}

something.html

var result = quickSubmit(formData, '/addresstosubmitto/page.php');

alert(result)

I just want to know if this is possible

Link to comment
Share on other sites

You cannot return the result of your ajax request.  The reason is because the function will have returned long before that result is available.  Requests are done asynchronously (the first A in AJAX) which means your code doesn't wait for the request to complete, it keeps going wile the request runs.  You get notified of the results via the callback functions (the success / error functions).  Any processing you want to do with the results needs to be contained within those functions.

Thus, you need to move the alert(result) code into your success function.  If you don't want to literally move the code, you can move it by introducing a new callback function as a parameter.  For example:

function quickSubmit(form_data, sUrl, successCB){
    $.ajax({
        url: sUrl,
        method: "POST",
        data: form_data,
        contentType: false,
        cache: false,
        processData: false,
        success: function(data){
            var result = JSON.parse(data);
            successCB(result);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
        }
    });
}

quickSubmit([], '/', function(result){
    alert(result);
});

The same is true with any error handling, either put it directly into the error callback function, or create a new error callback parameter you can use.

There are more modern and flexible ways of handling this like Promises and async/await but using them is a little more complicated. With async/await for example, you could write your function in a way that it seems to just return the results, but you need to set everything up properly first.

 

Link to comment
Share on other sites

The reason for my initial question is after submit and confirmation toast was fired the a div with dynamic contents is reloaded but on the page it was

quickSubmit(formData,'/SubmitUrl'php','toastr');
$('#div').load('new-results-after-change.php');

But the results are hit and miss, sometimes i need to refresh the whole page before the results will show so was looking for something like

if(quickSubmit(blady,bla)==='success') {
 $('div').load('newresult');
}

What i have done is

function quickSubmit(form_data, sUrl, successCB, reloadTable1, reloadTable2){
    $.ajax({
        url: sUrl,
        method: "POST",
        data: form_data,
        contentType: false,
        cache: false,
        processData: false,
        success: function(data){
            var result = JSON.parse(data);
            successCB(result);
			if(reloadTable1!=='') {
				reloadTable1
			}
			if(reloadTable2!=='') {
				reloadTable2
			}
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
        }
    });
}

I'm not sure how it will effect the other pages i call the function from but only time will tell

 

Thanks for you help

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.