javascript - Ajax: How to pass both form data and credentials on submit?
Main Problem :- Ajax: How to pass both form data and credentials on submit?
I have the below function which is called when a user clicks on a submit button:
<script type="text/javascript">
function submitForm() {
console.log("submit event");
var fd = new FormData(document.getElementById("campaign_form"));
console.log(fd);
var username = $('#username').val();
console.log(username);
var password = $('#password').val();
console.log(password);
$.ajax({
type: "POST",
url: "http://localhost/testing/post_campaigns.php",
data: fd,
data: {
"username": $('#username').val(),
"password": $('#password').val()
},
});
return false;
}
</script>
My php URL is called properly, but I don't see that my data is passed.
For example, I would typically expect to see in developer tools:
http://localhost/testing/post_campaigns.php?username=XXX&password=YYY
But I only see:
http://localhost/testing/post_campaigns.php
My variables are written to the console properly so I know they exist and have values.
I'm sure the issue is along the lines of my syntax; but I'm not sure how to format my Ajax properly to accommodate both object FormData and string variables username/password.
Basically, my overall code asks the user for a sheet they have filled out with specific values under designated column headers, and I read that information and POST it to our ad server. So I need both the FormData and the Username/Password provided by the user to be passed to my PHP file when I execute the POST request to our ad server with the information/changes requested by the user.
If my question/dilemma is not clear or you need more code, please let me know.
Thank you,
Edit: Attaching a screenshot of FormData in console per request.
Answer
Solution:
jQuery / AJAX Code:- For Sending formdata with other javascript variable together.
<script>
$('#btn').on("click", function () {
var formData = new FormData($("#form1")[0]);
formData.append('ipid',id); //id is the variable that has the data that I need
var path = "http://localhost/testing/post_campaigns.php",
$.ajax({
url: path,
type: "POST",
data: formData,
contentType: false,
processData: false,
success: function (stuff) {
$("#resp").html(stuff);
}
});
});
});
</script>
Note:-
To append param just use append()
method:
formData.append("param", "value");
And in the php-side I catch it:
echo $pid = ($_POST['ipid']);
Note:- For more reference regarding this check this
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
Source