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

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.

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.

jQuery Ajax post file

I try to post an uploaded file via ajax to php.
HTML:
<form id="uploadForm" name="uploadForm" action="#" enctype="multipart/form-data">
<input id="name" name="name" class="form-control" type="text" />
<input id="csv" name="csv" type="file" />
<input id="CSVUpload" type="submit" class="btn btn-default" name="Submit" value="Hochladen" />
JS
$("#uploadForm").submit(function () {
var formData = new FormData();
formData.append( 'csv', $( '#csv' )[0].files[0] );
formData.append( 'name', $( '#name'));
jQuery.ajax({
url: "../lib/import.php",
data: formData,
type: "POST",
success: alert('erfolgreich'),
error: alert('Fehler'),
cache: false,
contentType: false,
mimeType: 'multipart/form-data',
processData: false
});
});
and then i try to get the form data in PHP:
$_FILES['csv']
$_POST['name']
But the Ajax call completes with success and error... I'm confused...
The PHP file will not executed correctly...
Thanks for your help!
You aren't assigning functions to success or error.
You are calling the alert function immediately and then assigning its return value.
You need to create new functions to assign to success and error.
success: function () { alert('erfolgreich') },
error: function () { alert('Fehler') },
You are also calling the function as a submit handler, but aren't preventing the normal form submission. Consequently, the browser will load a new page before processing the response to the Ajax request.
$("#uploadForm").submit(function (event) {
event.preventDefault();
Try restructuring your AJAX call with your success and failure code like this:
$.post('../lib/import.php', formData).done(function() {
console.log('done');
}).fail(function() {
console.log('error');
});
See http://api.jquery.com/jquery.post/ for more examples.

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)

jQuery Ajax post for newbie

First let me say I'm new to Ajax. I've been reading articles from jquery.com and some tutorials but I didn't figured it out yet how this works on what I'm trying to achieve.
I am trying to get the weather for a searched city using Google's Weather API XML, without page refresh.
I managed to retrieve the Weather XML and parse the data but everytime I search for a different place, the page reloads since my weather widget is under a tab.
This is what I have in my HTML:
<script type="text/javascript">
$(document).ready(function(){
// FOR THE TAB
$('.tab_btn').live('click', function (e) {
$('.tab_content').fadeIn();
});
$(".submit").click(function(){
$.ajax({
type : 'post',
url:"weather.php",
datatype: "text",
aysnc:false,
success:function(result){
$(".wedata").html(result);
}});
});
});
</script>
<style>.tab_content{display:none;}</style>
</head><body>
<input type="button" value="Show Content" class="tab_btn">
<div class="tab_content">
<h2>Weather</h2>
<form id="searchform" onKeyPress="return submitenter(this,event)" method="get"/>
<input type="search" placeholder="City" name="city">
<input type="hidden" placeholder="Language" name="lang">
<input type="submit" value="search" class="submit" style="width:100px">
</form>
<div id="weather" class="wedata">
</div>
</div>
And here is the actual demo I'm working on: http://downloadlive.org.
Now, if I add action="weather.php" on the search form I get the results, but I get redirected to weather.php which is logical. Without the action="weather.php", everytime I search my index which I'm on, adds up /?city=CITY+NAME which shouldn't. This should be added to weather.php, get the results and then retrieve them back into my index, if that makes sense?
This is my php code for weather.php: http://pastebin.com/aidXCeQg
which can be viewed here: http://downloadlive.org/weather.php
Can someone please help me out with this please?
Thanks alot
You just need to return false; from the click event handler. This will prevent the default action from occuring - in this case, submitting the form. Also, remove the async: false setting. You almost never want synchronous ajax requests.
$(".submit").click(function(){
$.ajax({
type : 'post',
url:"weather.php",
datatype: "text",
success: function(result){
$(".wedata").html(result);
}
});
return false;
});
Alternately you can pass a parameter name to the callback and then use event.preventDefault() to accomplish the same result as above:
$(".submit").click(function(e){
$.ajax({
type : 'post',
url:"weather.php",
datatype: "text",
success: function(result){
$(".wedata").html(result);
}
});
e.preventDefault();
});
You need to send the form data with the POST. It's super-easy to do this using .serialize().
$(".submit").click(function(){
$.ajax({
type : 'post',
url:"weather.php",
data: $(this.form).serialize(),
datatype: "text",
success: function(result){
$(".wedata").html(result);
}
});
return false;
});

Categories