coding_beginner
coding_beginner

Reputation: 67

submit form with image as submit button - no refresh

Currently i have a form which has an image as a submit. It works fine as in the form variables get passed through and gets processed. However, the page gets refreshed every time click submit for the form since the processing page has a header back to the form page.

I need a way to send the form variables without the refreshing. I understand it can be done via ajax. However, i am facing a prob since my submit button is an image. Any help as to how i can rectify my code to submit the form without refresh would be great

    <form name ="nominate" action="" id ="nominate"  method="POST">
        <input type="hidden" name="id" value="<?php echo $id;?>">
        <input type="hidden" name="screenName" value="<?php echo $author;?>">
        <input type="hidden" name="course" value="<?php echo $course;?>">

//this is the image submit button 


 <input type="image"  style="float: left;" onMouseOver="this.src='images/nominated.png'"
            onMouseOut="this.src='images/nominate.png'" value="Place Order" src="images/nominate.png"  width="60" height="20">

</form>

<script> 
  $(function() {
    $(".button").click(function() {
     var id = $("#id").val();  
    var screenName = $("#screenName").val();


    var dataString = 'id='+ id + '&screenName=' + screenName + '&course=' + course;  
    alert (dataString);
    $.ajax({
       type: "POST",
       url: "nominate.php",
       data: dataString,
       success: function(){
         alert(dataString);
       }
    });


    });
  });

</script>

Upvotes: 0

Views: 1160

Answers (3)

Zac
Zac

Reputation: 1635

Firstly you need to add the id attribute as in jquery $("#") is the id of the element.

<input type="hidden" name="id" id="id" value="<?php echo $id;?>">
<input type="hidden" name="screenName" id="screenName" value="<?php echo $author;?>">
<input type="hidden" name="course" id="course" value="<?php echo $course;?>">

Then as said by Andrew either add the class="button" or use $("#some_id") and then give the button input an id="some_id".

$(".button").click(function(){
var url = "nominate.php";
var id = $("#id").val();  
var screenName = $("#screenName").val();
var course = $("#course").val();

$.post(url,{id:id, screenName:screenName , course:course }, function(data){

alert(data);

    });

});

This will alert whatever you send back from "nominate.php". Make sure you remove the header() from the script and send back a success or error message possibly.

Upvotes: 1

SenorAmor
SenorAmor

Reputation: 3345

Add the class 'button' to your image.

Also, you don't seem to have course defined anywhere. You might want to fix that, too.

Upvotes: 0

Andrew Hall
Andrew Hall

Reputation: 3073

The code you've done should work, if you add the class of "button" to the image.

<input type="image" class="button"....

Upvotes: 1

Related Questions