I have a script to fetch data and load it in a div, the code works fine and display the user id list if I don't use any form value and if I don't use type="POST", but it doesn't work (no result and no console error message) when I use $_POST values :
HTML :
<form name='newUser' id="searchForm" method="POST">
<input type="text" name="look_for" id="look_for">
<input type="text" name="lookage_from" id="age_from">
<input type="text" name="age_to" id="age_to">
</form>
fetchusers.php
$look_for = $_POST['look_for'];
$age_from = $_POST['age_from'];
$age_to = $_POST['age_to'];
$array = getProfilePicsList($look_for,$age_from,$age_to); //a function that select * from ...
echo json_encode($array);
jquery code:
$("#searchForm").submit(function(event)
{
$.ajax({
type: 'POST',
url: 'models/fetchUsers.php', //the script to call to get data
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
$.each($(data), function(key, value) {
$('#itemContainer').append(value.user_id);
});
}
});
return false;
});
In your ajax request, you are missing the data. just add this:
data: $("#searchForm").serialize(),
Example:
$.ajax({
type: 'POST',
url: 'models/fetchUsers.php', //the script to call to get data
dataType: 'json', //data format
data: $("#searchForm").serialize(),
success: function(data) //on recieve of reply
{
$.each($(data), function(key, value) {
$('#itemContainer').append(value.user_id);
});
}
});
Without using data param, you can't get the values in $_POST array.
Some References:
https://api.jquery.com/jquery.post/
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
Related
The output consists of the complete JSON, which is:
{reply:"Login success"}
The expected output is only the value for the key 'reply' ,
Login success
The required code:
HTML
<div id="resp" style="color:red;"></div>
JS AJAX JQUERY
$.ajax({
url: 'tt.php',
method: 'POST',
data: {'pass': pass , 'uname':uname},
success: function(data) {
document.getElementById("resp").innerHTML = data;
}
});
PHP
$data['reply'] = "Login Success";
echo json_encode($data);
Solutions tried to print the necessary data
data[0]
data[1]
data[reply]
data.reply
data["reply"]
The PHP code you show us is not outputting what you say your expected output should be but, you can tell the AJAX call to expect JSON to be returned by adding dataType: 'JSON', to the properties of the call.
Then you can address the reply as data.reply
$.ajax({
url: 'tt.php',
method: 'POST',
dataType: 'JSON', // added this line
data: {'pass': pass , 'uname':uname},
success: function(data) {
// then you can address the reply like this
document.getElementById("resp").innerHTML = data.reply;
}
});
I get the data from backend after Ajax post is being made, that data will have list of values. as user chooses a value from the list I want it to update to my object and post the ajax call again.
The problem I am facing here is I am not able to post again with chooses values, I need only one ajax call to do this. the nested ajax calls would not suffice
var searchObject = {
"research": "test"
}
$.ajax({
method: method,
data: JSON.stringify(searchObject), // while making next call the searchObject should have. "list":value of x in success
contentType: "application/json",
url: requestUrl
})
.success(function(data) {
var x = data.list2
}).error(function() {
});
I think that u can use syn ajax request rather than asyn request.You can see it from the jquery api Jquery ajax
And and you can try code like this:
var searchObject = {
"research": "test"
}
let x = undefined;
$.ajax({
async:false,
method: method,
data: JSON.stringify(searchObject), // while making next call the searchObject should have. "list":value of x in success
contentType: "application/json",
url: requestUrl
})
.success(function(data) {
x = data.list2
}).error(function() {
});
//Another syn ajax post
$.ajax({
async:false,
method: method,
data: JSON.stringify(x), // while making next call the searchObject should have. "list":value of x in success
contentType: "application/json",
url: requestUrl
})
.success(function(data) {
console.log(data)
}).error(function() {
});
If you're using POST with Ajax, this should do it for you. Just create a file and called it testing.php and enter a value in the input field and you'll see that ajax sends data to backEnd successfully. Hope it helps!
<?php
$data = array();
if(isset($_POST['research'])){
$data = $_POST['research'];
echo json_encode($data);
die();
}
?>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form>
Enter value: <input type="text" id="someID"><br>
<input value="submit" type="submit">
</form>
<p id="msg"><p/>
<script type = "text/javascript">
$("form").on("submit", function(e){
e.preventDefault();
var emailfield = $("#someID").val();
var myText ='You entered: ' + emailfield;
$.ajax({
url: "testing.php",
method: "POST",
dataType: "json",
data: {research: myText},
success: function (result) {
alert("result: " + result);
$("#msg").html(result);
},
error: function (params) {
alert("error");
}
});
});
</script>
</body>
</html>
I am submitting a form that will need to go to 2 different locations. The form is hidden and auto filled with the jquery .val method. How would I write the ajax to submit this in 2 different locations? Am I able to do this if I don't have access to my server side settings?
Here is the Form I am submitting
<form action="x" method="post" class="form-inline">
<input type="hidden" name="players_name" class="form-control" id="playersFullName_submit">
<input type="hidden" name="players_email"class="form-control" id="playersEmail_submit">
<input type="hidden" name="players_score" class="form-control" id="playersScore_submit">
<input type="hidden" name="redirect_url" class="form-control" id="redirectURL_submit" value="x">
<input id="submit endGame" type="submit" class="btn btn-default" value="Submit Your Score">
</form>
Here is my jquery filling it out
$(function () { // fill form fields
$('#playersFullName_submit').val(playersFullName);
$('#p_name').append(playersFullName);
$('#playersEmail_submit').val(playersEmail);
$('#dateSubmitted').val(submitDate);
});
Here is how I think I need to set it up
$.ajax({
type: "POST",
url : "url1.com",
data: {},
success: function(msg){
// get response here
}
});
$.ajax({
type: "POST",
url : "url2.com",
data: {},
success: function(msg){
// get response here
}
});
Would I need to enter anything into data, or will it pull it from my <form>?
You need to get the form data and inject it into the AJAX calls in the data property. You can do this with JQuery's serialize() method:
// Get your reference to the form:
var theForm = document.getElementsByTagName("form")[0];
$.ajax({
type: "POST",
url : "url1.com",
data: $(theForm).serialize(), // <-- Inject serialized form data
success: function(msg){
// get response here
}
});
$.ajax({
type: "POST",
url : "url2.com",
data: $(theForm).serialize(), // <-- Inject serialized form data
success: function(msg){
// get response here
}
});
b/c you are submitting ajax not form, you need to prevent form form action submitting, declare you server side route in ajax instead.
$('#submit_btn').on('click', function(e) {
e.preventDefault(); // you need this so the form don't submit
$.ajax({
type: "POST",
url : "url1.com",
data: {},
success: function(msg1){
var msg1;
}
});
$.ajax({
type: "POST",
url : "url2.com",
data: {},
success: function(msg2){
var msg2;
}
});
});
$.ajax({
type: "POST",
url : "url1.com",
data: $('.form-inline').serialize(),
success: function(msg){
// get response here
}
});
$.ajax({
type: "POST",
url : "url2.com",
data: $('.form-inline').serialize(),
success: function(msg){
// get response here
}
});
In case you have to find yourself having to send to many urls...
var theForm = document.getElementsByTagName("form")[0],
urls = ['url1.com','url2.com', ....];
$.each(urls, function(index,value){
$.ajax({
type: "POST",
url : value,
data: $(theForm).serialize(),
success: function(msg){
// get response here
}
});
});
The following form is what I use:
<form id="form-attachment" action="" method="post" enctype="multipart/form-data">
<input name="attachment" type="file" />
<input type="submit" />
</form>
This is what I do with jQuery:
$('body').on('submit', '#form-attachment', function(e) {
e.preventDefault();
var data = $(this).serialize();
console.log('fine', data);
var url = 'imageupload.php';
$.ajax({
type : "POST",
url : url,
data : data,
success : function(response) {
console.log('success: ' + response);
},
complete : function(response) {
console.log('complete: ', response);
},
error: function(response) {
console.log('error: ', response);
}
});
});
And this is my imageupload.php file:
$response = array();
$response["c"] = isset($_FILES["attachment"]);
echo json_encode($response);
And this is result on console on submit():
success: {"c":false}
So, what is wrong? Why my file is not visible at all?
You can use FormData object, as shown below..
$('body').on('submit', '#form-attachment', function(e) {
var data = new FormData(jQuery('#form-attachment')[0]);
jQuery.ajax({
type: "post",
contentType: false,
processData: false,
url: jQuery(this).attr('action'),
dataType: "json",
data: data,
success: function (r) {
// Success Handeling
}
});
});
NOTE:- No need to append anything as other answer suggests.
This method shall pass all the input fields just like they would in a normal http form POST method.
Use FormData object.
Here's the example how to send file via jQuery ajax request:
$(document).on('change', 'input[type=file]', function() {
formData = new FormData;
formData.append('file', $(this)[0].files[0]);
$.ajax {
url: '/upload-url',
data: formData,
type: 'post',
processData: false,
contentType: false,
success: function(data) {
console.log(data);
}
}
});
In your case you should serialize form first, append serialized data to the formData object. Then get file (or files) from a file field and append it to the same formData object. And finally send the formData object via ajax.
Here is mycode
function addPackage(elem)
{
var dataimg = new FormData();
dataimg.append('', $("#browseimg"+elem).prop('files')[0]);
var startdate=$("#from_date"+elem).val();
var enddate=$("#to_date"+elem).val();
$.ajax({
url: "addpackage/",
type:"post",
contentType:false,
data:{startdate:startdate,enddate:enddate,packageid:elem,img:dataimg},
success: function(data) {
}
});
}
I tried post method ajax to upload image and input field data without form. In ajax call it showing [object object]. How to post image with input field without form in jquery ajax?
You can do it like following. Hope this will help you.
function addPackage(elem)
{
var dataimg = new FormData();
dataimg.append('startdate', $("#from_date"+elem).val());
dataimg.append('enddate', $("#to_date"+elem).val());
dataimg.append('packageid', elem);
dataimg.append('img', $("#browseimg"+elem)[0].files[0]);
$.ajax({
url: "addpackage/",
type:"post",
cache : false,
contentType : false,
processType : false,
data: dataimg,
success: function(data) {
}
});
}
You can try this:
Your JS Code:
<script type="text/javascript">
var data = new FormData(document.getElementById("yourFormID")); //your form ID
var url = $("#yourFormID").attr("action"); // action that you mention in form action.
$.ajax({
type: "POST",
url: url,
data: data,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
dataType: "json",
success: function(response)
{
// some code after succes from php
},
beforeSend: function()
{
// some code before request send if required like LOADING....
}
});
</script>
Dummy HTML:
<form method="post" action="addpackage/" id="yourFormID">
<input type="text" name="firstvalue" value="some value">
<input type="text" name="secondvalue" value="some value">
<input type="file" name="imagevalue">
</form>
in addpackage php file:
print_r($_POST);
print_r($_FILES);