Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AJAX POST request using JQuery with body and URL parameters

I'm learning how to make AJAX calls with JQuery and one thing I was wondering if it's possible to do is include some data as URL parameters and other data in the post body. For example, I'd like to do something like this:

$.ajax({
  url: '/myURL',
  type: 'POST',
  data: JSON.stringify(data),
  contentType: 'application/json; charset=utf-8'
})

but in addition to the JSON data which is being sent in the POST request body, I'd like to include URL parameters. Is there a way to do this?

like image 551
Daniel Avatar asked Sep 11 '25 17:09

Daniel


1 Answers

You would be able to include the variables in the url portion of your code. For example

var example1 = "some_information";

$.ajax({
  url: '/myURL',
  type: 'POST',
  data: JSON.stringify(data),
  contentType: 'application/json; charset=utf-8'
})

would become

var example1 = "some_information";

$.ajax({
  url: '/myURL?var1=example1',
  type: 'POST',
  data: JSON.stringify(data),
  contentType: 'application/json; charset=utf-8'
})

You may need to put quotes around the example1 variable to ensure it doesn't break when there are spaces in the url.

like image 113
Mark Crawford Avatar answered Sep 13 '25 07:09

Mark Crawford