Send POST to mysql using js or jquery - javascript

I want to send an array of strings on my JavaScript to a MySQL table.
What is the best way and how can I do it?

You can use AJAX POST like so:
function sendArray()
{
var myArray = ["one","two","three"];
$.ajax({
url : 'YOUR_URL',
method : 'POST',
data :{
arrayData:myArray
},
success : function(response)
{
alert("data sent response is "+response);
},
error : function(e)
{
alert("data not sent")
}
});
}
</script>
<button onclick="sendArray();">Send Array</button>
here myArray is the string array you want.
on the PHP backend you can get this data as:
<?php
$arrayData = $_REQUEST['arrayData'];
foreach($arrayData as $data)
{
echo $data;
}

First of all understand the difference. Javacript is client side scripting language. It will not interact on my MySql on its own you will need to makean ajax call and then use server side scripting language like PHP to fulfil your purpose
you can use jquery to create an ajax call like
$.ajax({
type: "POST",
url: "somefile.php",
data: dataUwanttoinsert,
success: success,
dataType: dataType
});
then add your SQL query to the php file and when you make this ajax call it will do the query you have written

How I'd do it is by sending the string as a HTTP request payload using AJAX to a server that is connected to your MySQL database. Once the data is received by the server, it can process it and insert it to the database.
Here are some docs to help you get started:
Intro to ajax
Inserting data to MySQL using PHP

$.ajax({
url: 'url',
data: {'a': a, 'm': m},
type: 'POST',
cache: false ,
success: function (data, textStatus, jqXHR) {
alert(data);
}
});

Related

Ajax: How to send FormData inside of json object

To give you a better understanding consider my ajax request:
$.ajax({
url: '{% url "validate-upload-single" %}',
type: "POST",
data: JSON.stringify({
'mainForm': Myform,
'currentForm': 1,
}),
dataType: 'json', // response type
Where:
var Myform = new FormData( $(this)[0] );
The problem is that when i send the request, i get back an empty 'dict' on the server side. Im using Django as my backend
DJANGO VIEW:
print('SORTING THE POST REQUEST')
body = request.body.decode('utf-8')
serialized = loads(body)
print(f'POST: {request.POST}')
print(f'Body: {body}')
print(f'Serialized: {serialized}')
RESULT:
SORTING THE POST REQUEST
POST: <QueryDict: {'{"mainForm":{},"currentForm":1}': ['']}>
Body: {"mainForm":{},"currentForm":1}
Serialized: {'mainForm': {}, 'currentForm': 1}
I've tried $("form").serializeArray() but this only return text data, files seem to be missing
I guess the problem is with contentType header - it should be 'multipart/form-data'. Check this link to make it work with jQuery.ajax
In the .js file you HAVE TO add the fist block of csrf token for properly working.
//Getting csrf token
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
Then you use json in you ajax, getting the template that you want to display by variable here "html_form":
// Submit post on submit
$('#post-form').on('submit', function(event){
event.preventDefault();
console.log("form submitted!") // sanity check
//Send data to server for getting back sorted
$.ajax({
url: '/schedule/sort_group/',
async: true,
type: 'post',
data: { //data sent with the post request
group_field_value: $("#select_group").children("#group-option:selected").val(),
lector_field_value: $("#select_lector").children("#lector-option:selected").attr("name"),
},
dataType: 'json',
success: function (data) {
$("#change_by_select").html(data.html_form);
}
});
});
In the views.py file at the bottom you need to determine the data like that:
data['html_form'] = render_to_string('schedule/select_sort.html', context,
request=request)
return JsonResponse(data)
So I suggest the information that you want to retrieve from the server put into the particular another file, whatever it would be (dictionary or lists or other data structures or html templates).
I hope it would help. Feel free to ask any questions.

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);
}
});
});
});

How to pass data from javascript to php in same page

I want to know how I can pass data from my script javascript to my php code to use the data into a query
I tried many things but it didn't work for me
So this is my script to upload files from input type: file then i get the url in downloadURL variable
var downloadURL;
...
uploadTask.on('state_changed',function(snapshot){
},function(error){
},function(){
downloadURL=uploadTask.snapshot.downloadURL;
alert(downloadURL);
});
Now I want to pass downloadURL to my php so I can use it .
I also tried Ajax to do this task but it didn't work or the code that I used is false
Ajax code :
$.ajax({
type: "POST",
url: '', //same page
data: downloadURL ,
success: function(data)
{
//alert(data);
}
});
EDIT
Php code :
<?php
$user=$_POST['downloadURL'];
echo $user;
?>
Just a normal echo to test if data is Posted or not
Structure the data of your $.ajax request in a name-value pair manner.
Change this:
$.ajax({
type: "POST",
url: '', //same page
data: downloadURL ,
success: function(data)
{
//alert(data);
}
});
To this:
$.ajax({
type: "POST",
data: {"downloadURL":downloadURL} ,
success: function(data)
{
//alert(data);
}
});
I also removed url from your $.ajax request because by default url is set to the current page.
With the above modifications, your PHP code will remain unchanged (e.g., $user=$_POST['downloadURL'];).
Okay change your php with that code:
if(isset($_POST['downloadURL']) {
$response = array(
'user' => $_POST['downloadURL']
);
echo json_decode($response);
exit;
}
Because you are making ajax request you must return json that why we parse our Array to json(object) and then in your javascript ajax request inside success function write
console.log(data);
And after data
...
data: downloadUrl,
Add this
dataType: 'json'
This mean we are telling on our ajax request that we are expecting json response

Trouble Accessing Ajax POST variable on Codeigniter end

I'm using jquery to make ajax calls. Basically I don't know how to access the data I'm sending to the server with a post request. I don't know what the variable is called or... something. I don't know!
Ajax functions:
function ajax_client(url, json) {
return $.ajax({
url: url,
type: 'POST',
data: json,
dataType: 'json'
});
}
function gather_records(data, inp_col, fetch_col, limit) {
var json = JSON.stringify({
"ids" : data,
"inp_col" : inp_col,
"fetch_col" : fetch_col,
"limit" : limit
});
return ajax_client(base_url+'ajax_port/gather_records', json);
}
Codeigniter Function:
public function gather_records()
{
$data = json_decode($this->input->post('ids'));
log_message('debug', $data);//null
return json_encode($data);//null :(
}
I'm having no trouble receiving data back from the server here (and accessing with jQuery), my problem is that I can't get the data I'm sending to codeigniter. I'm developing on MAMP if that makes any difference.
I've tried other variable names like,
$this->input->post('data');
$this->input->post('json');
None seem to work.
Thanks very much for any help I can get!
You don't need to do JSON.stringify({..
just pass an object, and everything will be fine. I mean:
function ajax_client(url, json) {
return $.ajax({
url: url,
type: 'POST',
data: json,
dataType: 'json'
});
}
function gather_records(data, inp_col, fetch_col, limit) {
var json = {
"ids" : data,
"inp_col" : inp_col,
"fetch_col" : fetch_col,
"limit" : limit
};
return ajax_client(base_url+'ajax_port/gather_records', json);
}
One more thing. You don't need to json_decode it in your PHP side. Because default contentType in jQuery is 'application/x-www-form-urlencoded; charset=UTF-8'
Change line
$data = json_decode($this->input->post('ids'));
to
$data = $this->input->post('ids');
But if you really want to send JSON, you can add contentType
return $.ajax({
url: url,
type: 'POST',
data: json,
contentType: 'application/json',
dataType: 'json'
});
dataType you have set is "The type of data that you're expecting back from the server." (http://api.jquery.com/jquery.ajax/)

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'];

Categories

Resources