Reputation: 1955
I am trying to post data to an action with ajax in yii. Currently I am hard coding true and false in the action to see if I am even posting data, and it's not getting there. I can't seem to figure out where I am going wrong. Any Information would help, Thank you
JS/AJAX below:
function printObject(o) { // alerts an object
var out = '';
for (var p in o) {
out += p + ': ' + o[p] + '\n';
}
alert(out);
}
$(function() {
var dialog, form,
//select ticket_code, I don't know if this is working properly
ticket_code = $( "#ticket_code"),
allFields = $( [] ).add( ticket_code ),
tips = $( ".validateTips" );
function addTicket() {
var valid = false;
//alert ticket_code (however, it only alerts a long error message)
//saying that the length is 1, but not sure if that is correct
//see link at the end for error message.
printObject(ticket_code);
$.ajax({
type: "POST",
url: '<?php echo Yii::app()->createUrl('ticket/addTicket'); ?>',
data: {ticket_code : ticket_code},
success: function(){
alert('got here');
valid = true;
}
});
alert("after ajax");
if ( valid ) {
dialog.dialog( "close" );
alert('yay');
}
}
actionAddTicket below:
public function actionAddTicket(){
if(isset($_POST['ticket_code'])){
return true;
}
return false;
}
form view below:
<div id="dialog-form" title="Add a Ticket">
<p class="validateTips">Please Enter Ticket Number</p>
<form>
<fieldset>
<label for="ticket_code">Ticket Code #</label>
<input type="text" name="ticket_code" id="ticket_code" placeholder="000-0000" class="text ui-widget-content ui-corner-all" title="You can find this on the bottom right hand side of your ticket">
<img src="/images/faq-ticket-codes.png" width="150";/>
<input type="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
Upvotes: 0
Views: 252
Reputation: 18783
The problem appears to be caused by two things:
AJAX requests are Asynchronous, which means the line of JavaScript immediately following the call to $.ajax
gets executed before the AJAX request comes back in, or most likely will. It becomes a race condition.
The line ticket_code = $( "#ticket_code")
is a jQuery object. You then pass it as the ticket_code
property in the request data
which jQuery is trying to serialize as a string. jQuery thinks ticket_code
is an HTMLInputElement (e.g. <input type="text">
) when it actually is a jQuery object, so there is no way for it to be serialized as a string.
Anything you want to do after the AJAX request comes back to the browser should be done in the success
callback. Secondly, you need to use ticket_code.val()
when creating your data to pass along in the request:
function addTicket() {
var valid = false;
$.ajax({
type: "POST",
url: '<?php echo Yii::app()->createUrl('ticket/addTicket'); ?>',
data: {ticket_code : ticket_code.val()},
success: function(){
// ticket_code is valid
dialog.dialog( "close" );
}
});
}
Upvotes: 1