Send form data as GET parameters with jsonp and ajax - php

Hi Guys I'm new to jsonp. All I'm trying to do is simply send simple form data. I understand you cannot POST using jsonp as it is a standard script GET request. Below I've tried both serialize() or serializeArray() the form data but nothing is included in the GET request, please let me know where I'm going wrong?
HTML:
<form class="qd-bd-frm" name="qd-bd-frm" id="qd-bd-frm">
<input type="hidden" value="9614d609b2b7987d734" name="uid" />
<p>
<textarea class="qd-input" placeholder="Your Message" name="msg"></textarea>
</p>
<p>
<input type="button" class="qd-btn" value="Send" />
</p>
</form>
Jquery:
$.ajax({
url: "http://www.cross-domain.com/send",
dataType: "jsonp",
data: $("#qd-bd-frm").serializeArray(),
jsonpCallback: "sent",
success: function (result)
{
alert(JSON.stringify(result));
},
complete: function (xhr, status)
{
alert(status);
},
error: function ()
{
}
});
PHP:
public function send()
{
header( "Content-Type: application/json" );
echo "sent(".json_encode( $_GET ).");";
die();
// example response: sent({"callback":"sent","_":"1425338880075"});
}
If you see above, I'm just echoing the response back and in my success function above, none of my form inputs were included. I can also see this if I check the scripts tab in firebug that only 2 parameters were sent to the server. Any ideas what I'm actually missing here?

Related

How to send part of form data using JQuery & Ajax to php without submit button

I have an application for rating a service. A on the form page has inputs for comment, giving it a star etc.
I want to make it in a way that when a user clicks on a star it should send the value of the star input to a php script for processing without having to click on the submit button. I thought of using separate forms for this, however, i just want to use one form because different forms will bring the layout.
HTML Form
<form action="" method="POST">
<input type="text" name="name">
<textarea name="comment"></textarea>
<input type="radio" name="rate" value="1">
<input type="radio" name="rate" value="2">
<button type="submit" name="submit">Submit</button>
</form>
JQuery for the sending rate to php
$("input[name=rate]").change(function(event){
var rating_num = $(this).val();
$.ajax({
url: '../handlers/rating.php',
type: 'POST',
data: rating_num,
cache: false,
contentType: false,
processData: false,
beforeSend:function(){
},
success: function (data) {
alert(data);
}
});
})
rating.php
echo $_POST['rating_num'];
The output I get is "undefined index:rating_num"
The above code is just a sketch.
First of all, you can debug your $_POST variable with var_dump function.
However, the reason why you have this error is that you need to put an object in the 'data' parameter.
{
...
data: {
rating_num: rating_num
},
...
}
Also, you could use $.post instead of $.ajax. See examples in jQuery API documentation.
$.post('rating.php', {rating_num: rating_num})
.done(function(data) {
console.log(data);
});

AJAX form posting to PHP script but $_POST is empty in PHP script

Ajax form posting to php script but $_POST is empty in php script
I have a contact us form which posts data via ajax. On form submit ajax posts data to a PHP script however the $_POST is always empty in the PHP script. Headers are sent, request payload has all the post information that I need but still, $_POST is empty in the PHP script.
HTML Form
<form action="contact.php" method="post" novalidate="novalidate"
id="contact-form">
<input name="name" id="name" type="text" value="" >
<input type="text" name="address" id="address" value="" >
<input type="submit" value="Send" id="submit_contact">
</form>
JQUERY
$.ajax({
type: 'POST',
url: 'contact.php',
dataType: 'json',
contentType: 'application/json',
cache: false,
data: $('#contact-form').serialize(),
success: function(data) {
if(data.info !== 'error'){
//success
} else {
console.log(JSON.stringify(data));
//failure
}
}
});
PHP
if(isset($_POST['name']) and isset($_POST['address']))){
//Process
} else {
//success
}
$_POST always returns null but I want to get the name and address posted values.
contentType: 'application/json',
You claim you are POSTing JSON, which PHP doesn't have a default parser for, so PHP doesn't try to parse it and doesn't populate $_POST.
Since you aren't POSTing JSON ($('#contact-form').serialize() returns URL encoded data, not JSON) simply remove the lie and it will work.

I can't get to the success block of my jquery function

I am a little stuck on my jquery function below.
Here is the situation:
1) My php returns valid JSON - I can test this when I change the $_POST into $_GET and manually pass through data with the url.
2) The function below works correctly right up to the $.ajax part.
3) The function always returns ready state 0
Let me know if you need anymore data. Days of going over Stack Overflow and other forums has helped with insight, but I can not seem to fix in my instance.
//HTML
<form class="login-form" method="POST">
<input type="text" id="name" name="name" value="" placeholder="Username" required="yes">
<input type="password" id="pwd" name="pwd" value="" placeholder="Password" required="yes">
<input type="submit" id="login" name="login" value="Login" class="loginbutton" >
</form>
//JavaScript
$('#login').click(function(event)
{
//event.preventDefault();
var u = $('#name').val();
var p = $('#pwd').val();
console.log(u, p);
console.log("I am seeing this function?");
$.ajax({
contentType: "application/json; charset=utf-8",
cache: false,
type: "POST",
url: "functions/login.php",
data: {name:u, pwd:p},
datatype: "json",
error: function(msg)
{
console.log("RS - "+msg.readyState);
console.log(msg);
},
success: function(msg)
{
console.log("RS - "+msg.readyState);
console.log(msg);
$.each( msg, function( i, val ) {
console.log(val[0].session); //session is a variable in the json string
});
console.log("Success block");
}
});
});
datatype -> dataType problem, and if it does not help try out the 'text' type.
Maybe the php server send out other lines that messes up things.
event.preventDefault() or return false is missing at the end of your event handler for the click. Citation from w3schools
The event.preventDefault() method stops the default action of an element from happening.
so in our case it prevents form from sending.
These two technics prevent an event from bubbling upper. Without them, the form is sent to itself (address of your script) which results into page refresh and stop executing the script.
You can see the result (readyState) from $.ajax() function because it is faster than page reload.

not receiving data in php codeigniter when sending ajax post

I'm trying to send data by post using ajax (with codeigniter) and I don't know why but I don't receive anything...
This is how I send it:
var sendData = $('#formContact').serialize();
$.ajax({
type: 'POST',
url: '<?php echo base_url()?>/intranet/update/updateProfile',
data: sendData,
dataType: 'json',
success: function (data)
{
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
and this is an example of my form:
<form id="formContact" action="update" method="POST">
<input class="headInput" type="text" name="userName" value="Tito"/>
<input class="headInput" type="text" name="userLastName" value="Lancreo"/>
<input class="headInput" type="text" name="phone[]" value="666666"/>
<input class="headInput" type="text" name="phone[]" value="111111"/>
<input class="headInput" type="text" name="phone[]" value="222222"/>
</form>
And when I debug it, I always get 0...
[false, false, Array[0], false, null]
My controller:
$this->load->helper('form');
$this->load->library('form_validation');
//1 way
$ret=$this->input->post();
//2 way
$return=$this->input->post(NULL, TRUE);
//3 way
$all=$_POST;
json_encode($all);
//4 way
$contact=$this->input->post("userName");
//return everything...
$var[0]=$return;
$var[1]=$contact;
$var[2]=$all;
$var[3]=$ret;
$var[4]=$data;
echo json_encode($var);
How can I fix it??
SOLVED!
The problem was not to replace with:
serialize().replace(/%5B%5D/g, '[]');
But I think it's usefull...
My problem was that I'm using a library for internationalization (https://github.com/bcit-ci/CodeIgniter/wiki/CodeIgniter-2.1-internationalization-i18n) and I must add language to my url, even if I change my routes.php
url: '<?php echo base_url()?>en/intranet/update/updateProfile'
Thanks a lot!
The issue, as it seems, Is the serialize itself.
As can be seen here :
How to send serialize form data using JQuery if the input element is an array
Serialize has an issue with an array in the input fields, It replaces the square barckets :
The fiddle :
http://jsfiddle.net/3vr0dtgn/
from my fiddle:
data = $('form').serialize();
$('div').append(data);
Using the stackoverflow I supplied above gives the solution(regex replacing certain elements)

Making Ajax Form Use Native Wordpress

I have a form that uses Ajax to send a serialized forms data to send to a php file called contact-submit
i know i should wrap the contents of that page in a function...and add it to the functions.php file
i plan on calling the function MyContactForm
but i dont know the proper syntax to serialize the form and post the data to the function
heres what i have so far ...*keep in mind i left out the form fields...because we are focusing on the script part of this ...if the form is serialized...should grab everything
html
<form id="contactform" action="<?php echo home_url('contact-submit'); ?>" method="post">
<input class="textbox required" type="text" name="name2" id="name" value="Your Name" />
<input class="submit" value="Send" type="submit" alt="Send message" name="submit" />
</form>
script
jQuery("#postform").validate();
var AjaxSubmit = function(){
var btnText=jQuery('#contactform .submit').val();
// inform client that data is been sent:
jQuery('#contactform .submit').val('Sending...');
jQuery('#contactform .submit').attr('disabled', true);
jQuery.ajax({
type: 'POST',
url: jQuery('#contactform').attr('action'),
data: jQuery('#contactform').serialize(),
// successful POST - display result in success div:
success: function(msg){
jQuery('#contactform .form, #contactform .contacthead').slideUp(500,function(){
jQuery('#contactform div.success').removeClass('hiddne').fadeIn(500);
});
},
error: function(response) {
jQuery('#contactform .submit').val(btnText);
jQuery('#contactform div.error').html(response.statusText).slideDown(500);
}
});
}
jQuery("#contactform").validate({
submitHandler: AjaxSubmit
});
});
My Question is.....what is the proper syntax for serializing a form and passing the data to a php function?

Categories