JSON does not post data to the requested URL - javascript

Trying to post some data at URL: "
$(function() {
var frm = $(document.myform);
var data = "?lm_po_id=154668&authentication=ThisisAuth&description=ThisIsDesc";//JSON.stringify(frm.serializeArray());
//var data = JSON.stringify(frm.serializeArray()); // Also tried this
alert(data + "I am about to POST this:\n\n" + data);
$.postJSON = function (url, data, callback) {
$.ajax({
'url': frm.attr("action"),
'type': 'post',
'processData': false,
'data': JSON.stringify(data),
contentType: 'application/json',
success: function (data) { callback(JSON.parse(data)); },
});
};
});
This call the right function properly but when i check it in debug mode all parameters have null values, can some one help me what wrong i am doing.
Here is my HTML form
<form action="http://192.168.0.124:8080/Ilex-WS/service/ilexmobile/poImageUpload" name="myform" method="post" enctype="multipart/form-data">
<input type="text" value="158664" name="lm_po_id" /><br />
<input type="text" value="AuthCodeMD5" name="authentication" /><br />
<input type="text" value="584" name="imagenumber" /><br />
<input type="text" value="ImgName.png" name="name" /><br />
<input type="text" value="This is desc" name="description" /><br />
<input type="file" value="" name="uploadedimage" /><br />
<input type="button" value="Submit" onclick="javascript:document.myform.submit()"/><br />
</form>
Thanks in advance....

The only thing your JavaScript does is alert a string.
You never bind an event handler to the form's submit method, and even if you did it wouldn't fire since you use form.submit() to submit the form instead of a submit button. (So this submits form encoded data instead of JSON encoded data).
You store a function in $.postJSON, but you never call it, and it has a local variable called data which would mask var data = "?lm_po... anyway (not that it would make sense to use that value since it is a string and you run JSON.stringify over data).

Related

Submit a form with a file without refresh

Hello guys i don't know to submit a form without page refresh.
This is my code:
My form:
<form method="POST" id="post123" action="" enctype="multipart/form-data">
<input class="form-control input-lg" name="book_name" id="inputLarge" type="text">
<input class="form-control" name="book_price" type="number">
<textarea class="form-control" id="exampleTextarea2"
name="book_description" maxlength="100" rows="7"></textarea>
<textarea class="form-control" name="book_content" id="exampleTextarea4" maxlength="200" rows="7"></textarea>
<input type="file" name="file" id="imgInp44" >
<button type="submit" name='action' id="sendbutton21" value="post1" class="btn btn-primary">
Submit
</button>
</form>
Javascript:
$("#sendbutton21").click(function() {
var url = "http://localhost:5000/magazin_insert"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#post123").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
How i can modify my code to submit along with text a file towards the mysql db?
Your first issue is in this line:
<button type="submit" name="action" ... />
You have two possibilities:
change type="submit" to type="button"
use event.preventDefault() in your $("#sendbutton21").click(function() {
After, your ajax call can be changed in order to include the file:
var form = document.getElementById('post123');
var formData = new FormData(form);
$.ajax({
url: url,
data: formData,
type: 'POST',
processData: false,
success: function(data) {
alert(data);
}
});
$("#sendbutton21").click(function() {
var url = "http://localhost:5000/magazin_insert"; // the script where you handle the form input.
// for testing...
url = 'https://api.github.com/repositories';
var form = document.getElementById('post123');
var formData = new FormData(form);
$.ajax({
url: url,
data: formData,
type: 'GET',
processData: false,
success: function (data) {
console.log(data[0].id);
}
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<form method="POST" id="post123" action="" enctype="multipart/form-data">
<input class="form-control input-lg" name="book_name" id="inputLarge" type="text">
<input class="form-control" name="book_price" type="number">
<textarea class="form-control" id="exampleTextarea2"
name="book_description" maxlength="100" rows="7"></textarea>
<textarea class="form-control" name="book_content" id="exampleTextarea4" maxlength="200" rows="7"></textarea>
<input type="file" name="file" id="imgInp44" >
<button type="button" name='action' id="sendbutton21" value="post1" class="btn btn-primary">
Submit
</button>
</form>
Try https://jquery-form.github.io/form/ plugin to easily send form via ajax sample code:
$('#post123').ajaxForm(function() {
// SUCCESS CALLBACK
});
To submit a form without refresh, use event.preventDefault().
$("#sendbutton21").click(function(event) {
event.preventDefault();
var url = "http://localhost:5000/magazin_insert"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#post123").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
Instead of
$("#sendbutton21").click(function() {
use
$("#post123").submit(function() {

jQuery Ajax post to php not printing response

I am using the new way to post data to a php page through ajax without a page refresh but the response is not printing to the console.
Note: I am not yet collecting form data to send until I can actually get the ajax to work.
HTML:
<form id="myForm" action="process.php" method="post">
<input type="text" placeholder="Email" id="email" name="email">
<span class="error">Email not entered</span><br />
<input type="password" placeholder="Password" id="pword" name="pword">
<span class="error">Password not entered</span><br />
<input type="text" placeholder="First Name" id="fname" name="fname">
<span class="error">First Name not entered</span><br />
<input type="text" placeholder="Last Name" id="lname" name="lname">
<span class="error">Last Name not entered</span><br />
<input type="submit" value="Submit">
</form>
jQuery:
$('#myForm').on('submit', function(e){e.preventDefault()});
var request = $.ajax({
url : 'process.php',
method : 'POST',
data : {name: 'Robert'},
dataType : 'html'
});
request.done(function(response){
console.log(response);
});
request.fail(function(){
console.log('fail');
});
PHP:
<?php
echo "<pre>";
print_r($GLOBALS);
echo "</pre>";
?>
Your on submit function is not doing anything. You need to have the ajax call inside of it.
Try:
jQuery(document).ready(function ($) {
$('#myForm').on('submit', function(e){
e.preventDefault();
$.ajax({
url : 'process.php',
method : 'POST',
data : {name: 'Robert'},
dataType : 'html'
})
.done(function(response){
console.log(response);
})
.fail(function(){
console.log('fail');
});
});
});
Also I do not know where you are loading the JS. But you might want to wrap it in a document ready function to make sure your form exist when it is called.
Lastly there is a very nice plugin for forms that will make this easier for you. JQuery.Form.
http://malsup.com/jquery/form/

ajax upload file form

I have two forms, one for uploading a file and another for filling the form with information. I need to upload the file without refreshing the page first and then submit the form using ajax. And here are the codes:
form_file
<h1>Insert Employee</h1>
<form id="form">
<input id="name" placeholder="arabic name.." type="text" name="name_ar"/><br>
<input id="name" placeholder="english name.." type="text" name="name_en" value=""/><br>
<input id="name" placeholder="arabic department.." type="text" name="dep_ar" /><br>
<input id="name" placeholder="english department.." type="text" name="dep_en" /><br>
<input id="name" placeholder="arabic job.." type="text" name="job_ar"/><br>
<input id="name" placeholder="english job.." type="text" name="job_en" /><br>
<input id="name" placeholder="extention#.." type="text" name="ext" /><br>
<input id="name" placeholder="office#.." type="text" name="office" /><br>
<input id="name" placeholder="mobile#.." type="text" name="mobile" /><br>
<input id="email" placeholder="email" type="text" name="email"/><br>
<br /><br />
<div class="upload_form">
<form id='form1'>
<input type="file" name="userfile" size="20" />
<input type="button" value="upload" id="upload" />
</form>
<br/><br/>
</div>
<input type="button" value="Click" id="submit"/>
<input type="reset" value="Reset"/>
</form>
</div>
AND HERE IS THE AJAX: I know how to submit data using ajax but I need help for how to upload a file using ajax without refreshing the page, and then take the name of that file, send it again with the form, and save it to database.
<script>
$(document).ready(function(){
$('#upload').click(function(){
console.log('upload was clicked');
//ajax POST
$.ajax({
url:'upload/do_upload',
type: 'POST',
success: function(msg) {
//message from validation php
//append it to the contact_form id
$('#uploud_form').empty();
$('#uploud_form').append(msg);
}
});
return false;
});
$('#submit').click(function(){
console.log('submit was clicked');
//empty msg value
//$('#msg').empty();
//Take form values
var form_data = {
name: $('#name').val(),
email: $('#email').val(),
message: $('#message').val()
};
//ajax POST
$.ajax({
url:'',
type: 'POST',
data: form_data,
success: function(msg) {
//message from validation php
//append it to the contact_form id
$('#contact_form').empty();
$('#contact_form').append(msg);
}
});
return false;
});
});
</script>
Not sure whether I get it properly or not. I will try to answer as per my understanding.
You need to write server side code which will save the image on server.
I believe you are able to make the AJAX call to initiate point 1.
From your upload service (point 1), your should return the "relative path" of the image which was uploaded.
In success callback of your AJAX call (point 2) you should be able to capture the relative path.
Once the relative path has been captured you should add it to DOM or say any element.
Then you can start another AJAX call or post back (submit form) based on your requirement.
If this is not the problem then please be specific in what you need and provide more information.
I do it like this and it's work for me :)
<div id="data">
<form>
<input type="file" name="userfile" id="userfile" size="20" />
<br /><br />
<input type="button" id="upload" value="upload" />
</form>
</div>
<script>
$(document).ready(function(){
$('#upload').click(function(){
console.log('upload button clicked!')
var fd = new FormData();
fd.append( 'userfile', $('#userfile')[0].files[0]);
$.ajax({
url: 'upload/do_upload',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
console.log('upload success!')
$('#data').empty();
$('#data').append(data);
}
});
});
});
</script>

How can I pass in this data into a form submit call (similar to data parameter for an ajax post)?

I have the following code that submits data to an asp.net-mvc controller action via jquery ajax
var queryString = "name=Joe&age=22&weight=200";
$.ajax({
url: '/MyController/Generate',
type: 'post',
data: queryString,
dataType: 'json'
});
this works fine and binds to the controller action parameter
public ActionResult Generate(MyParams p)
{
Console.Write(p.name);
Console.Write(p.age);
Console.Write(p.weight);
}
The issue now is that I need to change this from ajax to being a regular form post (I need to use regular form post as I am now returning a file from the controller action). I am trying to figure out how I can get that same querystring variable to get submitted as part of a regular form post (non ajax).
Is this possible?
try with html.beginform
#using (Html.BeginForm("Generate", "MyController","name=Joe&age=22&weight=200", FormMethod.Post, new { id = "frmMyForm" }))
{
// Your form elements
}
If you want that data to be fixed you can make a form like this:
<form action="/MyController/Generate" method="post">
<input type="hidden" name="name" value="Joe" />
<input type="hidden" name="age" value="22" />
<input type="hidden" name="weight" value="200" />
<input type="submit" />
</form>
Otherwise, if you want the data to be editable, it goes like this:
<form action="/MyController/Generate" method="post">
<input type="text" name="name" />
<input type="number" name="age" />
<input type="number" name="weight" />
<input type="submit" />
</form>

Javascript/AJAX - Sending a reverse image search request to google

so i've been trying to do a reverse image search request through ajax, and it's giving me 302 errors. looking at the firebug console, i found out that the url in the response header sent back by google is linking me to the results, but i have no idea how to access that and send another ajax query to the new location. any help would be appreciated!
this is the response header:
This is my current code:
<form action="http://images.google.com/searchbyimage/upload" id="contactForm1" method="post"
enctype="multipart/form-data">
<input type="hidden" name="image_url" id="image_url" />
<input type="hidden" name="btnG" id="btnG" value="Search" />
<input type="file" name="encoded_image" id="encoded_image" />
<input type="hidden" name="image_content" id="image_content" />
<input type="hidden" name="filename" id="filename" />
<input type="hidden" name="hl" id="hl" value="en" />
<input type="hidden" name="bih" id="bih" value="507" />
<input type="hidden" name="biw" id="biw" value="1920" />
<input type="button" name="submit" value="Submit" />
</form>
$(document).ready(function () {
$("form").bind("click", "input[type='button']", function () {
var formData = new FormData($("form")[0]);
$.ajax({
type: "post",
url: "http://images.google.com/searchbyimage/upload",
enctype: 'multipart/form-data',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function (text) {
console.log(text);
}
});
});
});
I think you should try with this:
var formData = new FormData($(this).closest("form").serialize());

Categories