简体   繁体   中英

PHP — jquery ajax syntax help

I am new to using jquery and i have written the following code and it does not work and i am not able to figure out what the mistake is..syntax might also be wrong.

It has 2 submit buttons while using button1 it should get info from the DB and display on the same page.ie, get the title from the DB and display on the same page.

While second submit button is used to submit title into the DB and update it(written in script_2.php).

<form id="myForm" method="post">
id: <input type="text" name="search"/>
<input type="button" id="button1" value="Submit to script 1" />
<input type="button" id="button2" value="Submit to script 2" />
title:<input type="text" name="title"/>
</form>
<head>

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
   $(document).ready(function(){

$("#button1").click(function(){
$.post('script_1.php', { name: form.name.value },
function(output) {
    $('#age').html(output).show();

}) ;
}) ;



$("#button2").click(function(){
$('form#myForm').attr({action: "script_2.php"});
$('form#myForm').submit();
});
});

</script>
</head>

Help appreciated.

You have too many closing

<script type="text/javascript" src="jquery.js"></script></script>

to

<script type="text/javascript" src="jquery.js"></script>

jQuerys attr() expects strings, not an object, like:

$('form#myForm').attr("action", "script_2.php");

You form is before your <head> tag. It should be after your </head> and in a <body> tag.

You are putting the results of your ajax call in an element with id age , but I don't see any element with that id on your page.

That's all for errors (that I see as of now), but you can also speed up your selecter here $('form#myForm') by changing it to $('#myForm') since id's are unique, and I doubt you have any element with the id myForm which isn't a form.

You are missing the }); to close the $("#button1").click function:

<script type="text/javascript">
   $(document).ready(function(){
        $("#button1").click(function(){
            $.post('script_1.php', { name: form.name.value },function(output) {$('#age').html(output).show();});
        });
        $("#button2").click(function(){
            $('form#myForm').attr({action: "script_2.php"});
            $('form#myForm').submit();
        });
    });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM