I need to retrieve data from server using jQuery AJAX on HTML form then store the response data in a php string variable. So far my code is:
<form method="post" name="myform" id="myform" action="https://domain.com/cgi-bin/cgi.exe">
<input name="exec" value="viewproduct" type="hidden">
<input name="customer" value="customer_name" type="hidden">
<input name="sku" value="sku_number" type="hidden">
<input name="submit" type="button">
</form>
<div id="results"></div>
<script type="text/javascript">
jQuery("#myform").submit(function(e){
var postData = jQuery(this).serializeArray();
var formURL = jQuery(this).attr("action");
jQuery.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
jQuery('#results').html(data.toString());
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('fail');
}
});
e.preventDefault();
});
jQuery(document).ready(function() {
jQuery("#myform").submit();
});
</script>
But I still haven't see any result. If I just use the form normally without any js code, then I'll get the raw response data from the server/database directly on the browser. How can I save that raw response data on the browser into a string variable in php?
Change your submit() handler to include this in the first line:
jQuery("#myform").submit(function(e){
e.preventDefault(); // <---
....
and/or add return false; to the end of it.
If that stops it from reloading but doesn't show anything in your #results div, troubleshoot by changing your success() in the AJAX to use this:
jQuery('#results').html(data.toString());
If that shows something, go to your server code and split up your data into individual properties that your Javascript can separate and use individually (or combine it all into one big string if you want).
.html() takes an input of String, not an object (which data is in this case).
You won't be able to store the Javascript value into a PHP variable because PHP runs on the server and returns a response to the browser where Javascript runs on the browser. What you could do is call your script with AJAX and then set your form values with jQuery using
$("input[name=customer]").val(data);
You could either have an AJAX call for each input or you could parse out the return string to get each value. The first may be more straight forward.
If the action is becoming an issue, remove the entirely and just add an onClick to the submit button that calls a function that makes the AJAX calls.
Hope this helps!
Related
I am doing some checks on my website to assure that the web browser can run it. If the browser pass the requirements, I want to reload the webpage and send a post argument with jQuery like this.
I have tried the $.post function on jQuery like this:
$.post("index.php", {
correcto_obligatorio: true
});
window.location.reload("index.php")
However, when the browser reloads the web, there is no correcto_obligatorio parameter on $_POST. I used the var_dump php function to print it and all I get is NULL
$.post is a separate asynchronous request.
window.location.reload just reloads a page, but doesn't consider all of your async requests.
If you print $_POST['correcto_obligatorio'] not with var_dump, but log to file you will see the value there.
There is two solutions for you.
1) Await for the ajax result and respond to it.
$.post( "index.php", {
correcto_obligatorio: true
}, function (data) {
if (data.passed_validation) {
window.location.reload("index.php")
}
});
2) Second is to post a form
<form action="/index.php" method="POST" id="my_form">
<input type="hidden" name="correcto_obligatorio" value="1"/>
</form>
<script>
function myFunc() {
$("#my_form").submit()
}
</script>
The most common and rightful one is the first solution.
your code does not wait for the post to finish. You basically send the request and redirect the browser to index.php without waiting for the server to answer you. Consider using a callback function:
$.post( "index.php", {
correcto_obligatorio: true
}, function( result) {
if (result.passed) {
window.location.reload("index.php")
}
});
That is assuming that the server responds with a valid json object that contains the parameter passed (content type should be set to application/json )
I am using $.ajax to submit a form, I want to add a key-value pair to the submission that are not part of the form input and it is common for all my forms.
So i planned to move common part to ajaxsetup.
I want receive these in Action as two parameters like ModelData, TokenKey
My html code
<form id="frm">
#Html.TextBoxFor(m => m.Name)
<input type="button" value="Test" onclick="AjaxPost(); return false;" />
</form>
My Java Script
$(function () {
$.ajaxSetup({ data: { 'TokenId': 'TokenId Value'} });
});
function AjaxPost() {
var frm = $("#frm");
$.ajax({
url: '/Home/Index',
type: 'POST',
data: frm.serialize(),
success: function () { }
});
}
This is not working! If i removed data in AjaxPost function TokenId is posting,
Otherwise its not.
I think this would be a good solution:
$.ajaxPrefilter(function(options, originalData, xhr){
if (options.data)
options.data += "&TokenId=TokenValue";
});
this will affect all ajax calls. Check out the codepen DEMO
When you use the jQuery serialize() function, it simply turns your form into a string in the format a=1&b=2&c=3. So you can certainly apply this function to two forms and concatenate the result, with an & between them, and use the result in your ajax call. You'd want some checks to make sure neither string is empty when you do the concatenation.
$.post(url,{key:value,data:frm.serialize},function(){
//do somehting
})
i usually do this its simple and easy, and you can add as many key:value pairs you want...
You can add a hidden field to your form with the name of TokenId and required value. Or you can modify data like below.
data : fir.serialize()+"&TokenId=TokenId+Value";
Note: You have to Encode your data before append like above
I have tried most answers about call javascript function returned from ajax response. Every answer worked but I must call alert to show the ajax response to see the result.(If not use alert in the function refreshResults, sometime the result will show but disappear immediately) It seems the page keep refreshing.
Here is the screenshot.
I already tested the browser can receive data successfully from the server. The problem is how to show the data from the browser side.
Here is the code related to receive data from the server and how the server return data.
ajax
function sendAjaxQuery(url, data) {
$.ajax({
type: 'POST',
url: url,
data: data,
success: function (data) {
//eval(document.getElementById("refreshResults").innerHTML);
refreshResults(data);
//$("#firstname").text(data);
// alert('success '+data);
}
});
}
This is how I send data to server.
sendAjaxQuery('http://localhost:3000/results.html',JSON.stringify($('form').serializeObject()));
js
<script type="text/javascript">
function refreshResults(data){
$("#firstname").text(data);
alert(data);
}
</script>
The server side is nodejs. (The server side return a string. Status is 200). The http header is
"Content-Type": "text/plain",'Access-Control-Allow-Origin': '*'
This is the click handler.
function sendData() {
var form = document.getElementById('myform');
sendAjaxQuery('http://localhost:3000/results.html',JSON.stringify($('form').serializeObject()));
}
var sendButton = document.getElementById('sendButton');
sendButton.onclick = sendData;
This is the according html
<form id="myform">
<input type="text" name="Search" value="">
<button id="sendButton" >Search</button>
What is the whole point of the sendAjaxQuery method ?
It just recreates what the $.post does
Just use
// url and data should be whatever you pass to sendAjaxQuery now
$.post(url, data, refreshResults);
whenever you want to make an ajax call..
Update Seeing that you are submitting the contents of a form, the problem might be that you allow the form to be submitted the normal way as well (which causes a refresh of the page).
You will need to cancel the normal action of the button that started this action..
Since you are using jQuery, it is better to use that for binding the event handlers
change
var sendButton = document.getElementById('sendButton');
sendButton.onclick = sendData;
to
$('#sendButton').on('click', function(e){
e.preventDefault();
sendData();
});
I am trying to send a form via Ajax, but can not figure out how to set the receiver to be a PHP script. When trying to pass thee data I get 404 page not found. I do not know how to define the PHP script where I want the data to be sent.
I tried defining the script path at the start of the page
<?php
module_load_include('php', 'mysite', 'modules/test/customer');
?>
AJAX part
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'id' : $('input[name=mav_id]').val(),
'sku' : $('input[name=sku1]').val(),
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
//redining the base path
url: Drupal.settings.basePath + "modules/test/customer" ,
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
HTML form
<table>
<tr><th align="LEFT"><b><i>Cu data</b></i></th></tr>
<form action="modules/test/customer.php" method="post">
<div class='cu'>
<tr><td>Mav ID: <input type="text" name="mav_id"></td>
<td>sku: <input type="text" name="sku1"></td>
<tr> <td><input type="submit" value="Submit"></td> </tr>
I still get this error:
could not find the site you requested "/node/modules/test/customer.php
How can I get rid of the node part and get the script to send the data to right address?
remove the below code form page callback function
module_load_include('php', 'mysite', 'modules/test/customer');
and add it to hook_init
it will solve your problem.
I am struggling with the post() method.
I've been reading several posts on here and the jquery forums, and just trying to get a simple piece of code working is proving difficult. My ultimate goal is to pass a div #exportData and all it's children to test.php.
I started with:
$.post("ajax/test.php", $("body").html());
To my mind this should return the entire contents of the current page to test.php (unless test.php requires a holding div or element to receive the content). Currently it only returns the blank page.
I then tried looking at the parameters for post() if I need to manipulate these:
$.ajax({
type: 'POST',
url: ajax/test.php,
data: data,
success: success,
dataType: dataType
});
Also declared a variable:
var data = {
html: #exportData
};
That bit failed of course. I don't know how to define the data in the parameters, or if this is the right place to do it.
Although I would have thought if:
$.post("ajax/test.php", $("body").html());
would have worked then presumably I can substitute "body" for any class, id or selector I like.
Also does the submit button need certain parameters to tie it to the post function. At the moment it is purely:
<input type="submit" id="submit" value="send" name="submit">
Sorry this is such a basic question.
You could do
var html = $("body").html();
var data = {
html: html
};
$.post("ajax/test.php", data);
as the second parameter of $.post() is an object wich contains the data you want to send to the server.
To send the data you could do:
<input type="submit" id="submit" value="send" name="submit">
js
$('input#submit').click(function(e){
//prevent submitting the form (if there is a form)
e.preventDefault();
var html = $("body").html();
var data = {
html: html
};
$.post("ajax/test.php", data);
});
server side you receive the data
$html = $_POST['html']
$.post() expects an object to be passed to transfert data along with the post request:
jQuery.post( url [, data] [, success(data, textStatus, jqXHR)] [, dataType] )
url: A string containing the URL to which the request is sent.
data: A map or string that is sent to the server with the request.
success(data, textStatus, jqXHR): A callback function that is executed if the request succeeds.
dataType: The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).
var content = $ ('body').html(),
data = { content: content };
$.post('ajax/test.php', data);
Sending html in the post doesn't sound like a good idea. All elements type of input or select will be empty in the Html. You would need to use .serialize in order to get the values.
$('#submit').submit(function () {
$.ajax({
type: 'POST',
url: 'ajax/test.php',
data: {
html: $('body').html()
}
});
});