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.
Related
I basically don't seem to understand sending a variable to another page.
I've tried PHP sessions, javascript cookies and ajax POST and GET.
I'm trying to send the innerHTML of a div, with the data created by a jQuery call,
a variable called savedartists. It displays correctly in the console.log on the sending page but the $_POST['savedArtists']
is undefined in the receiving page. I have spent hours looking at different posts on this site but I haven't been able to get it to work.
Any help is appreciated.
<input class="et_pb_button et_pb_button_0 et_pb_bg_layout_light" onClick="savequote();" type="button" id="savedchoices" value="Commander la prestation" >
<script>
function savequote() {
var savedartists = document.getElementById('selectedList').innerHTML;
console.log(savedartists);
$.ajax({
type: "POST",
url: 'example.com/artiste/mise-en-relation/',
data: { savedArtists : savedartists },
success: function(data) {
console.log("success!");
location.href = "example.com/artiste/mise-en-relation/";
}
});
}
</script>
On the receiving page (example.com/artiste/mise-en-relation/)
<?php
if(isset($_POST['savedArtists']))
{
$uid = $_POST['savedArtists'];
echo $uid;
} else {
echo 'zit!';
}
?>
Thanks for your time
Capturing as an answer for future readers...
Fundamentally what's happening here is that two requests are being made to the target page. The first one is the AJAX request:
$.ajax({
type: "POST",
url: 'example.com/artiste/mise-en-relation/',
data: { savedArtists : savedartists },
success: function(data) {
//...
}
});
This is a POST request which contains the data you expect, and works just fine. However, the result of this request is being ignored. That result is available in the success callback, but the code doesn't do anything with it:
console.log("success!");
location.href = "example.com/artiste/mise-en-relation/";
Instead, what the code is doing is performing a redirect. This creates a second request to that same page (though it's essentially irrelevant that it's the same page). This is a GET request and contains no data to send to the server.
At its simplest, you should either use AJAX or redirect the user. Currently you're mixing both.
I want to redirect to the other page.
In that case AJAX is the wrong tool for the job. You may not even need JavaScript at all, unless you want to modify the elements/values of a form before submitting that form. But if all you want is to POST data to another page while directing the user to that page, a plain old HTML form does exactly that. For example:
<form method="POST" action="example.com/artiste/mise-en-relation/">
<input type="text" name="savedArtists">
<button type="submit">Submit</button>
</form>
In this case whatever value the user enters into the <input> will be included in the POST request to example.com/artiste/mise-en-relation/ when the user submits the form.
I´am a UX designer and one of these JS dummie/"HTML coder" guys.
I need help or a hint to validate a simple HTML form via a second request which returns a JSON answere, before the form is send.
I have a really simple HTML form on a landingpage where the user can enter a coupon code:
<form id="tokensubmit" method="GET" action="https://www.xyz/cart.html">
<div class="form-group">
<input type="text" name="tokenCodeAdd" id="tokenCodeAdd" size="25" value="" class="form-control input-lg" placeholder="Please enter Coupon Code">
</div>
<input id="input_id" type="submit" class="btn btn-lg btn-warning btn-block" value="Submit">
</form>
If a user enters his Coupon code and hit the submit button, the code will be added to the action URL (https://www.xyz/cart.html) and the User is redirected to this cart.html page. If the coupon code is correct everything is fine. If not he receives an error message on the cart.html page.
So far so good.
BUT: I want to validate the coupon code without redirecting the user to a new website(cart.html).
The system offers a second URL for this already. A url like:
/checkout/validate.html?tokenCode=12345678
This returns a JSON answere with a status like:
{"error":"Wrong Coupon Code."}
if the Coupon code isnt right.
If it is valid, something like:
{"error":"null"}
returns.
What I am searching for is a simple solution to call the validation URL (validation.html) first on click on the "submit" button, parse the returning JSON, prevent the form from sending if "error" is something else than "null" and print the JSON message ("Wrong Coupon Code.") right above the form input.
If "error" = "null" the forms behavior should not change. It should just open the https://www.xyz/cart.html URL with the tokenCode attached as parameter.
What I´am trying/starting with looks like:
$('#tokensubmit').submit(function(event){
event.preventDefault();
var tokenCheck = $(this).find('input[id="tokenCodeAdd"]').val();
$.ajax({
url: '/checkout/validate.html'+tokenCheck,
type: 'GET',
success: function(data){
var jsonData = $.parseJSON(data);
}
});
});
Its just the beginning, I know. The real parsing part is missing and the error message output if the validation fails, or the redirect if not.
Anyone who could help?
And thx in advanced!
Small hint: The form is placed on a WordPress driven landingpage, so PHP and JQuery is an option.
The code you have for getting the validation is almost correct:
$('#tokensubmit').submit(function(event){
event.preventDefault();
var tokenCheck = $(this).find('input[id="tokenCodeAdd"]').val();
$.ajax({
// either attach the parameter like you are trying to do directly to the url,
// but in this way:
url: '/checkout/validate.html?tokenCode='+tokenCheck,
// or give the URL parameter(s) as data object to jQuery:
data: {
tokenCode: tokenCheck
}
type: 'GET',
// if you specify the dataType you want to receive as json,
// jQuery will parse it for you already
dataType: 'json',
success: function(data){
// now you can check the data for error or not, for example like:
if(data.error == null){
// do something (most likely REALLY submit the form now?)
}else{
alert('tokenCode invalid');
}
}
});
});
With jquery you can send through a data parameter and it will work out how to place it in the URL:
$.ajax({
url: '/checkout/validate.html',
type: 'GET',
data: {"tokenCode": tokenCheck}
success: function(data){
var jsonData = $.parseJSON(data);
}
});
I would also advise not doing an Ajax request at all if tokenCheck is empty.
Wouldn 't it be easier to check the coupon code when the user leaves the input field? First the example while submitting the whole form.
$('#tokensubmit').on('submit', function(event) {
event.preventDefault();
var validationSuccess = false;
$.ajax({
url : '/checkout/validate.html',
type : 'GET',
data : { tokenCode : $('#tokeninput').val() }
success : function(response) {
var data = $.parseJSON(response);
if (data.error === null) {
validationSuccess = true;
}
}
if (validationSuccess === true) {
$('#tokensubmit').off('submit').submit();
}
});
So what we 've done here? The submit event listener is nearly the same you 've done. We prevent the default submitting of the form and do an ajax request for validation the input value. If the request returns no error as response, we simply unbind the submit event listener from the form and submit the form again.
In my opinion it would be better to work with the blur event listener on the input field. In combination you could use the HTML5 Constraint Validation API. So you don 't have to submit the form and the ajax request would be done on blurring the input field. I think that would be the better user experience.
So here 's the blur event listener:
<input type="text" name="the-input-field" id="the-input-field" value="" required>
$('#the-input-field').on('blur', function(event) {
var element = this;
$.ajax({
url : '/checkout/validate.html',
type : 'GET',
data : { tokenCode : element.val() }
success : function(response) {
var data = $.parseJSON(response);
if (data.error !== null) {
element.setCustomValidity('Your input is invalid!');
// place some error message elsewhere in the markup
} else {
element.setCustomValidity('');
}
}
});
});
First we placed the required Attribute in the input element. It marks the input element as required. So if it 's empty you could not submit the form. Then we placed the blur event listener, which is doing the ajax request. If the response is false, we place a custom error via setCustomValidity. It is a native HTML5 Constraint Validation API function. If the custom error on the input element is set, you could not submit the form. If the user enters another token the request is done again on leaving the input element. If the token is valid, the custom error message will be removed and the form can be submitted.
My problem is this: I have a HTML form for sending an EMail. And I have a PHP file to process said Form and send the EMail. The problem is, they are not on the same server (I have access to the PHP file, though). I have Bootstrap and JQuery on my page.
My form looks like this: (simplified)
<div id='form-messages'></div>
<form id='ajax-contact'>
several text fields, each one with name and id
<button type="submit" id="submit">SUBMIT</button>
</form>
It's a simple form and it works. The problem is how I send the data to the PHP script. These script tags are at the end of the <body> tag:
<script>
$(document).ready(function() {
$('#ajax-contact').on('click', function () {
// Get the form.
var form = $("#ajax-contact");
// Get the messages div.
var formMessages = $("#form-messages");
// Set up an event listener for the contact form.
$(form).submit(function(event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data
var formData = $(form).serialize();
});
$.getJSON("my_path_to_the_php_script.php", function(formData){
});
});
});
</script>
I was told to use getJSON to work around the fact that the PHP script doesn't lie on the same server as the HTML. AFAIK .getJSON sends a JSONP-string to the PHP file. What I want to check for is simply if the PHP-script has failed or not and display an error message above the form.
The reason I try to use .getJSON is because I already tried this:
$.ajax({
url:'my_path_to_the_php_script.php',
type:'post',
data: formData,
jsonp: 'jsonp',
dataType: 'jsonp', // use JSONP
success: function(data){
// Display OK message
$(formMessages).html(<div class="alert alert-success">
X
Success!
</div>)
// Clear the form.
$(formMessages).each(function(){
this.reset();
});
}
},
error: function (error) {
$(formMessages).html(<div class="alert alert-danger">
X
Warning Message!
</div>)
}
});
Both methods don't work. All I want to do is to check if the script has failed or not. The $.getJSON() way doesn't work, it stays on the same page (as I expect), but the server returns an Error 405 page (Method not allowed). I don't have access to the header files of the PHP installation of that server. The $.ajax(dataType: 'jsonp') way doesn't work, returns Error 405.
Thanks for reading, please help.
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!
What is the bestHi everyone, a MVC3 newbie here! please take a look at these:
in my View page, i have there:
<div id = "AccounStatusDiv" class="display-field">
#Html.DisplayFor(m => m.AccountStatus)
<input id="btnBool" type="button" class="btnGrid ActStatBtn" value="#(Model.AccountStatus ? "Deactivate" : "Activate")" onclick="ChangeStatus()"/>
</div>
and a script:
<script type="text/javascript">
function ChangeStatus() {
$.post('#Url.Action("SetAccountStatus", "User")',
{ UserName: "#(Model.UserName)",
accountStatus: "#(Model.AccountStatus)" });
// change the display of the AccounStatusDiv elements, or maybe just reload the div element if possible. is it?
}
</script>
while in my Display Template, i have there:
<div id = "AccountStatusDiv" style="display:inline-block;">
<img src="#Html.Custom().ResolveImage((bool)Model ? imgPositive : imgNegative)" alt="#Model" />
<label> #ResourceManager.Localize(resource, display)</label>
</div>
in the controller:
public ActionResult SetAccountStatus(string userName, bool accountStatus)
{
SecurityManager.GetMembershipProvider().SetStatus(userName, !accountStatus);
return AjaxResult.JsonRedirect("/User/ViewUser?username=" + userName);
}
The results are shown only after I reload the page.
I want to display the updated img, label and btnBool elements right after clicking the btnBool without reloading the whole page. What is the best way in such case?
Please post your code suggestions, it would be a great help for me!
Thanks in advance!
You're only using $.post() to send data (request) to the server. AJAX can be two-fold: send a request, and receive the corresponding response. In your code, you're not receiving data back (or, at least, making the necessary arrangements so that you are).
If the SetAccountStatus action of your UserController is set to return some data back (maybe through return Json(), or similar), you can modify the $.post() call to receive it, and have your Javascript react accordingly using a callback function.
var data = {
UserName: "#Model.UserName",
accountStatus: "#Model.AccountStatus"
};
var call = $.post(
'#Url.Action("SetAccountStatus", "User")',
data
);
// set the success callback here
call.success(function (m) {
// the [m] variable contains the data returned by the server
// during the resolution of your call
// this will be called when your AJAX call succeeds,
// and you can use this opportunity to update the HTML DOM with new data
});
this is to event click in button and without refresh page
$("#btnBool").click(function(e){
e.preventDefault();
//to do your code, you can use `$.ajax` to request and get response from server
$.ajax({
url: '#Url.Action("SetAccountStatus", "User")',
type:"GET",
dataType: 'json',
data: { UserName: "#(Model.UserName)",accountStatus: "#(Model.AccountStatus)" },
async:'true',
success:function (data) {
alert(data);
//success to parsing json if you data type of your response is json
}
});
}
you can use web service to send request and get response from server , and to request,get response from server you can use $.ajax() in jquery http://api.jquery.com/jQuery.ajax/